Search code examples
pythonpyqtdesignerqtreeview

minimal example qtreeview for pyqt and the qt designer


I am trying to get a minimal example for an application designed by the qt designer with pyqt involving a QTreeView to work

1) i can start the app this way but if i push the butten, no entry in the TreeView widget is shown, i do not get any error message, and the layout looks fine, is there some kind of update method?

if you answer, please be specific, as i am still a beginner with qt and much of the documentation is written with c++ examples, and i only have some experience with basic c and python

from PyQt4 import uic, QtGui, QtCore


(Ui_MainWindow, QMainWindow) = uic.loadUiType('main_window.ui')


class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.model = QtGui.QStandardItemModel()
        self.connect(self.ui.pushButton_NeuesMoebel, QtCore.SIGNAL('clicked()'), self.add_item)

    def add_item(self):
        t = self.ui.lineEdit_Moebel.text()
        if len(t) > 0: 
            item = QtGui.QStandardItem(t)
            self.model.appendRow(item)
            self.ui.lineEdit_Moebel.clear()
        else:
            self.ui.statusBar.showMessage('error: no text in Moebel')


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

2) additionally, is there a cleaner way to directly use the *.ui file than this, to sort of directly subclass the MainWindow of the that file? the ui stuff seems a bit messy

3) for example it would be nicer to have the add_item method in a subclass of the window created by the *.ui file, are we supposed to use the intermediate step of translating the *.ui file to a *.py file?


Solution

  • You just forgot to set the model on your QTreeView. Right now the tree view has no model so it never sees the data update:

    def __init__(self, parent=None):
        ....
        self.ui.treeView.setModel(self.model)
    

    Also as a suggestion, save yourself some typing and use the new-style signal/slot connections that are more pythonic and don't make you type out signatures:

    self.ui.pushButton_NeuesMoebel.clicked.connect(self.add_item)