Reputation: 41
I'm trying to learn PyQt and follow its documentation. So I have this simple code which is supposed to expand a selected item in a QteeView.
Documentation https://doc.qt.io/qt-5/qtreeview.html#expand says that expand()
method "Expands the model item specified by the index." but it does not work. I also tried setExpand()
and expandAll()
both don't work neither.
How should I read this documentation to make my code do what it is supposed to do?
This exercise is the first step to help me expand all folders to the very deepest one since expandAll()
expands only the first level of the tree.
from PyQt5.QtWidgets import *
class GUI(QWidget):
def __init__(self, parent=None):
super(GUI, self).__init__(parent)
path = "C:/TEMP"
self.model = QFileSystemModel()
self.model.setRootPath(path)
self.view = QTreeView()
self.view.setModel(self.model)
self.view.setRootIndex(self.model.index(path))
self.but_1 = QPushButton(self)
self.but_1.setText("BUT 1")
self.but_2 = QPushButton(self)
self.but_2.setText("BUT 2")
self.V_layout = QVBoxLayout()
self.V_layout.addWidget(self.view)
self.V_layout.addWidget(self.but_1)
self.V_layout.addWidget(self.but_2)
self.setLayout(self.V_layout)
index_1 = self.model.index("C:/TEMP")
index_2 = self.model.index("C:/TEMP/bbbbb")
self.but_1.clicked.connect(lambda: self.aaa(index_1))
self.but_2.clicked.connect(lambda: self.aaa(index_2))
self.view.expandAll()
def aaa(self, index):
self.view.expand(index)
self.view.setExpanded(index, True)
print(index)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
g = GUI()
g.show()
sys.exit(app.exec_())
Upvotes: 1
Views: 845
Reputation: 17345
Instead of passing the index in the lambda function, try passing the path instead, and then getting the index just before calling expand. I am not entirely sure why, but doing it this way worked fine for me.
For example:
path_1 = "C:/TEMP"
path_2 = "C:/TEMP/bbbbb"
self.but_1.clicked.connect(lambda: self.aaa(path_1))
self.but_2.clicked.connect(lambda: self.aaa(path_2))
def aaa(self, path):
index = self.model.index(path)
self.view.expand(index)
Upvotes: 0