Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

scrollTo(index) not working if view was hidden



  • Re: How to scrollTo(index) if view was hidden

    This is a follow-up with a better solution to this issue. To recap, a QListView with many icons can take time to be repainted when it is made visible. If you want to scrollTo an index you have to wait for the repainting of the scrollbars to complete. It turns out this is only an issue if QListView::setLayoutMode(QListView::Batched) is used. Here is some code that illustrates the issue:

    #include <QtWidgets>
    #include <QDebug>
    
    int main(int argc, char* argv[])
    {
        QApplication a(argc, argv);
        auto f = new QFrame;
        auto blank = new QListView;
        auto view = new QListView;
        view->setViewMode(QListView::IconMode);
        view->setResizeMode(QListView::Adjust);
    
        // this prevents the scrollTo working in time
        view->setLayoutMode(QListView::Batched);
    
        auto stack = new QStackedLayout;
        f->setLayout(stack);
        f->layout()->addWidget(blank);
        f->layout()->addWidget(view);
    
        QFile file("D:/Pictures/Avatars/frog.jpg");  // substitute your own image
        QImage image;
        QImageReader thumbReader;
        thumbReader.setFileName("D:/Pictures/Avatars/frog.jpg");
        thumbReader.setScaledSize(QSize(40,40));
        image = thumbReader.read();
    
        auto model = new QStandardItemModel;
        view->setModel(model);
        for (int row = 0; row < 50000; ++row) {
            auto item = new QStandardItem();
            item->setData(QString::number(row), Qt::DisplayRole);
            item->setIcon(QPixmap::fromImage(image));
            model->appendRow(item);
        }
        stack->setCurrentIndex(1);
    
        // scrollTo does not work if view->setLayoutMode(QListView::Batched) without a delay
        view->scrollTo(model->index(40000,0), QAbstractItemView::PositionAtCenter);
        f->show();
        return a.exec();
    }
    

Log in to reply