python - 在 TreeView PyQt4 中单击时无法抓取项目?

标签 python qt4 pyqt pyqt4

我正在尝试从 TreeView 中获取字符串/对象。所以当用户点击 TreeView 中的任何项目时,我可以在终端上显示它。感谢任何帮助。这是代码。当我单击 TreeView 中的字符串/项目时,它会显示: PyQt4.QtCore.QModelIndex 对象在 0xb6b6c7d4 代替 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_())

最佳答案

轻松修复。您的信号返回 QModelIndex,但您需要使用 itemFromIndex 在模型中查找该索引的项目:

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

您可以从索引中获取模型,或者专门使用您的模型属性。

虽然我有讲台,但我想提一下连接信号和槽的非常棒的新型方法,只要您使用的是 Qt 4.5+

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

请注意您不必再指定基于字符串的签名。它完全是对象风格,您可以直接访问信号对象,只需告诉它要连接的可调用槽。

关于python - 在 TreeView PyQt4 中单击时无法抓取项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11496799/

相关文章:

python 全局命名空间不可访问

python - 在python中定位大数据集中的多个文件

c++ - QDeclarativeExtensionPlugin 与 QML 通信

python - pylint 找不到 QWidget 和 QApplication

python - 使用 root 安装 Setuptools - 出现 PythonPath 错误

python - 当我想增加对象并将其放入字典时出现 KeyError

python - 将 QML 元素锚定到窗口

c++ - 在 Qt 应用程序启动之前设置系统环境变量

python - 画半无限线?

python - PyQt5:使用 QTableView.setSortingEnabled 和 QSortFilterProxyModel 时的幻像列