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.

QtCore.QObject.connect(self.treeWidget, QtCore.SIGNAL("clicked(QModelIndex)"), self.treefunction)

def treefunction(self, index):
    print index

Output on clicking the item in treeview is:

<PyQt4.QtCore.QModelIndex object at 0x8835a74>

Instead of the actual string.

Dani AI

Generated

Printing a QModelIndex shows you the index object, not the cell contents — was right about that. The index is just a location in the model; you need to ask the model or the widget for the data. 's approach of converting the index to an item and reading its text is the right idea, but there are a couple of clearer, more robust options depending on whether you use a convenience widget or a model/view.

If you are using QTreeWidget, prefer the widget-level signal that already gives you the item, or convert the clicked index back into a QTreeWidgetItem and read the column text. Example (QTreeWidget):

# recommended for QTreeWidget
self.treeWidget.itemClicked.connect(self.on_item_clicked)

def on_item_clicked(self, qitem, column):
    print qitem.text(column)   # column is often 0

If you are using a model (QTreeView / QStandardItemModel or a custom model), use the model API or the index data role. The display string is normally available with the Qt.DisplayRole; in PyQt4 that value may be a QVariant or a native Python type, so handle both cases:

from PyQt4.QtCore import Qt

value = index.data(Qt.DisplayRole)
if hasattr(value, 'toString'):
    text = unicode(value.toString())
else:
    text = unicode(value)
print text

Troubleshooting tips: check index.isValid() before using it, verify index.row()/index.column() to ensure you clicked where you expect, and use selectionModel().currentIndex() or itemClicked when you want the currently selected item. If you store Python objects in the model, use a non-display role (Qt.UserRole) and retrieve that role explicitly. This covers the common pitfalls and keeps the view/model usage clear and portable.

Recommended Answers

All 2 Replies

You are getting the memory adress of object.

class Foo(object):
    def bar(self):
        return 'Hello'

Test class.

>>> obj = Foo()
>>> print obj
<__main__.Foo object at 0x0356B110>
>>> print obj.bar
<bound method Foo.bar of <__main__.Foo object at 0x0356B110>>
>>> print obj.bar()
Hello

As you see until a make correct call i get memory adress of object at 0x......
You can try something like index(), index.method_name, index.method_name().

I figured it out:

def treefunction(self, index):

 index.model().itemFromIndex(index).text()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.