L.John.B
L.John.B

Reputation: 120

How to set index of QTreeView as first item in tree automatically

I have a program that when clicking an item in a QTreeView shows details about the item and at the click of a button you can open the file, however if no file is selected the program closes. I have tried setCurrentIndex() however I'm not sure if I'm using it right at the only exampled i can find are PyQt4 or C++.

I'm runnng PyQt5 windows 7.

    self.treeView = QtWidgets.QTreeView(self.centralWidget)
    self.treeView.setSortingEnabled(True)
    self.treeView.setObjectName("treeView")
    self.horizontalLayout_4.addWidget(self.treeView)
    self.file_model=QtWidgets.QFileSystemModel()
    self.file_model.setRootPath('C:\My Stuff\Movies')
    self.treeView.setModel(self.file_model)
    self.treeView.setRootIndex(self.file_model.index('C:\My Stuff\Movies'))
    self.treeView.setHeaderHidden(True)
    self.treeView.hideColumn(1)
    self.treeView.hideColumn(2)
    self.treeView.hideColumn(3)
    self.treeView.setCurrentIndex(self.file_model.index(0,0))

Alternatively, i would prefer if a QMessagebox to appear say no file is selected, i have made the message box and it is working however i cant get it to show when no file is selected in the tree view as the program crashes before it displays the error message.

Upvotes: 0

Views: 2156

Answers (1)

Marcus
Marcus

Reputation: 1713

self.file_model.index(0,0) just gives you the information of the root directory, in your case, C:. What you need to do, is wait for the directoryLoaded( QString ) signal to be emitted, then choose the index at (0, 0)

Here is the simplified version of the code. Perhaps you can make the necessary changes in your code.

import os, sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

if __name__ == '__main__' :

    app = QApplication( sys.argv )

    treeView = QTreeView()
    treeView.setSortingEnabled( True )
    treeView.setObjectName("treeView")

    fsm = QFileSystemModel()
    fsm.setRootPath( 'C:\My Stuff\Movies' )

    def selectZeroZero( path ) :
        if fsm.rowCount( fsm.index( path ) ) :
            treeView.setCurrentIndex( fsm.index( 0, 0, fsm.index( path ) ) )

    fsm.directoryLoaded.connect( selectZeroZero )

    treeView.setModel( fsm )
    treeView.setRootIndex( fsm.index( 'C:\My Stuff\Movies' ) )

    treeView.setHeaderHidden( True )
    treeView.hideColumn( 1 )
    treeView.hideColumn( 2 )
    treeView.hideColumn( 3 )

    treeView.show()

    sys.exit( app.exec_() )

Upvotes: 1

Related Questions