Bug Fisher
Bug Fisher

Reputation: 23

QScrollbar scroll to center

I would like to scroll my QScrollbar to center; I thought it was easy, but

QScrollBar *bar = ui->scrollArea->horizontalScrollBar();
bar->setValue(bar->maximum()/2);
bar->update();
ui->scrollArea->update();

doesn't do the job. What goes wrong?

Upvotes: 1

Views: 1208

Answers (3)

SiGa
SiGa

Reputation: 187

I encountered the same problem, and noticed that the values of maximum/minimum changed when the widget is shown. The values for maximum/minimum were different in the constructor of my widget.

Seems like Qt layouts the widget when it is shown. I overloaded the showEvent of the widget and set my cursors there, which I saved as a member in the constructor.

//header of widget
...
void showEvent(QShowEvent *event) override;
...

// cpp of widget (in my case LiveTab)
void LiveTab::showEvent(QShowEvent *event)
{
  std::cout << "show called" << std::endl;
  int max = hScrollBar->maximum();
  int min = hScrollBar->minimum();
  this->hScrollBar->setValue((max - min) / 2);

  max = vScrollBar->maximum();
  min = vScrollBar->minimum();
  this->vScrollBar->setValue((max - min) / 2);
}

Depending on what you want to achieve you could overload the showEvent of another widget.

Upvotes: 0

awpitt13
awpitt13

Reputation: 155

In Qt's documentation the actual document length is defined by

document length = maximum() - minimum() + pageStep() (See QScrollBar Class Reference)

So try replacing

int center = (min+max)/2;

with

int center = (max+min+bar->pagestep())/2;

Upvotes: 2

Dimitry Ernot
Dimitry Ernot

Reputation: 6584

A QScrollBar has a minimum, too. So to center a scrollbar:

int max = bar->maximum();
int min = bar->minimum();
int center = (  min + max ) / 2;
bar->setValue( center );

Upvotes: 0

Related Questions