Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically scroll QScrollArea

Tags:

qt

qt4

I have a Widget with QScrollArea in it and I want it to be scrolled down right after the widget containing it is shown. I tried:

scrollArea->ensureVisible(0,100, 20, 20);

It works only when invoked by user (pushing button for example). Putting it in widget contstructor or showEvent doesn't work. Can it be done automatically?

like image 441
majaen Avatar asked Aug 27 '10 23:08

majaen


2 Answers

I believe you can scroll the QScrollArea content by setting positions to its horizontal and vertical scrollbars. Smth, like this:

scrollArea->verticalScrollBar()->setValue(scrollArea->verticalScrollBar()->value() + 10);
scrollArea->horizontalScrollBar()->setValue(scrollArea->horizontalScrollBar()->value() + 10);  

code above should scroll contents of the scroll area 10 pixels down and 10 pixels right each time it gets called

hope this helps, regards

Edit0: extra code snippet showing how to scroll the area in the form's constructor:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QLabel *imageLabel = new QLabel;
    QImage image("my_large_image_file.JPG");
    imageLabel->setPixmap(QPixmap::fromImage(image));

    ui->scrollArea->setBackgroundRole(QPalette::Dark);
    ui->scrollArea->setWidget(imageLabel);

    ui->scrollArea->horizontalScrollBar()->setValue(100);
    ui->scrollArea->verticalScrollBar()->setValue(100);
}
like image 65
serge_gubenko Avatar answered Oct 22 '22 21:10

serge_gubenko


I have spent some time with the debugger and find out that scriollArea has 0 sizes in the constructor, so it looks like it is possible to scroll something only when all the widgets are created and visible. Scrolling in the showEvent of window works fine.

like image 3
Slavenskij Avatar answered Oct 22 '22 22:10

Slavenskij