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

How to scrollTo the desired item when the root of model changed



  • I've used QListView and QFileSystemModel to show local files. I expect to locate specific file by changing root directory and scrolling to show it, but scrollTo() does not work.

    def locateFile(self, fileDIr, filePath):
            self.listView.setRootIndex(self.listView.model().setRootPath(fileDir)
            posidx = self.listView.model().index(filePath)
            self.listView.setCurrentIndex(posidx)
            self.listView.scrollTo(posidx)
    

    How to resolve this issue?



  • @ridincal
    Show the value of posidx at least. Also please post code that actually compiles/is your actual code, the above does/is not, and then all bets are off.



  • @JonB

    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
            MainWindow.setObjectName("MainWindow")
            MainWindow.resize(800, 600)
            self.centralwidget = QtWidgets.QWidget(MainWindow)
            self.centralwidget.setObjectName("centralwidget")
            MainWindow.setCentralWidget(self.centralwidget)
            self.listView = QtWidgets.QListView(self.centralwidget)
            self.listView.setGeometry(QtCore.QRect(20, 10, 531, 521))
            self.listView.setObjectName("listView")
            self.model = QtWidgets.QFileSystemModel()
            self.listView.setModel(self.model)
            self.locateFile("D:\\=test=\\fonts", "D:\\=test=\\fonts\\HYYouYuanTiW.ttf")
            self.retranslateUi(MainWindow)
            QtCore.QMetaObject.connectSlotsByName(MainWindow)
    
        def retranslateUi(self, MainWindow):
            _translate = QtCore.QCoreApplication.translate
            MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    
        def locateFile(self, fileDir, filePath):
            self.listView.setRootIndex(self.listView.model().setRootPath(fileDir))
            posidx = self.listView.model().index(filePath)
            self.listView.setCurrentIndex(posidx)
            self.listView.scrollTo(posidx)
    
    class AppMainWnd(QMainWindow , Ui_MainWindow):
        def __init__(self, parent=None):
            super(AppMainWnd, self).__init__(parent)
            self.setupUi(self)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        AppWnd = AppMainWnd()
        sys.exit(app.exec_())
    

Log in to reply