jackdear09
jackdear09

Reputation: 25

Unable to grab the item on click in TreeView PyQt4?

I am trying to grab the string/object from the treeview. So when a user click on any item in the treeview, I can show it on the terminal. ANy help is appreciated.Here is the code. When I click the string/item in the treeview it shows this: PyQt4.QtCore.QModelIndex object at 0xb6b6c7d4 instead of Linux

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtCore, QtGui

data = root = [

    ("Linux", [

        ("System",

                [("System name",[]),
         ("Kernel", []),
         ("Drivers", []),
         ("Memory", []),
         ("Processes", []),
                 ("Disk mounted", []), 
         ("Services Running", []),
         ("Installed Packages", [])]),
        #[("System name", [])]),

        ("Network",
        [("Nework confi.",[]),
        ("Interface test", [])]),

        ("PCI Devices",
        [("PCI devices", [])]),

        ("Logs", 
        [("Messages",[]),
        ("Dmesg", [])]),


        ])]

class Window(QWidget):

    def __init__(self):

        QWidget.__init__(self)

        self.treeView = QTreeView()


        self.model = QStandardItemModel()
        self.addItems(self.model, data)
        self.treeView.setModel(self.model)

        self.model.setHorizontalHeaderLabels([self.tr("Object")])

        layout = QVBoxLayout()
        layout.addWidget(self.treeView)
        self.setLayout(layout)
    self.treeView.connect(self.treeView, QtCore.SIGNAL('clicked(QModelIndex)'), self.treefunction)

    def treefunction(self, index):
    print index


    def addItems(self, parent, elements):

        for text, children in elements:
            item = QStandardItem(text)
            parent.appendRow(item)
            if children:
                self.addItems(item, children)
if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 3563

Answers (1)

jdi
jdi

Reputation: 92569

Easy fix. Your signal returns a QModelIndex, but you need to lookup up the item for that index in your model using itemFromIndex:

def treefunction(self, index):
    print index.model().itemFromIndex(index).text()
    # print self.model.itemFromIndex(index).text()

You can either get the model off the index, or specifically use your model attribute.

And while I have the podium, I wanted to mention the really awesome new-style approach to connecting signals and slots, as long as you are using Qt 4.5+

self.treeView.clicked.connect(self.treefunction)

Notice how you don't have to specify the string-based signature anymore. Its completely object-style where you access the signal object directly and just tell it the callable slot to connect with.

Upvotes: 5

Related Questions