如何记录双击QTreeView项目?

时间:2017-10-25 05:40:13

标签: python pyqt qtreeview qstandarditemmodel

我有QTreeView我正在听doubleClicked信号。然后,如果我双击该项目,我将在QTabwidget中打开一个文本文件。如果我已经从项目中打开文本,有没有好的方法来记录?

我想也许我应该创建类似DataFrame的东西来记录它,但我不确定这是否是一个好的解决方案。有什么建议吗?

class PrjTreeModel(QStandardItemModel):
    def __init__(self, parent,data):
        super(PrjTreeModel, self).__init__(parent)
        self.items = datapd.DataFrame([['HHH','BBB','RRR']],columns=['UserId','ProjectId','Status']) 
        self.refreshItems()

    def refreshItems(self):
        prjId = self.items['ProjectId']
        child = ['A','B','C']
        for i,row in prjId.iteritems():
            parent = QtGui.QStandardItem(row)
            for j in child:
                parent.appendRow(QtGui.QStandardItem(j))
            self.appendRow(parent)

    def flags(self, index):
        if not index.isValid():
            return QtCore.Qt.ItemIsEnabled   
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if (role == QtCore.Qt.DisplayRole) and (orientation == QtCore.Qt.Horizontal) and (self.items is not None):
            return self.items['UserId'][0]
        else:
            return QStandardItemModel.headerData(self, section, orientation, role)

class MainWindow(QMainWindow):
    [...]
    qTreeView.setModel(PrjTreeModel())
    qTreeView.doubleClicked.connect(self.dClicked)

    self dClicked(self):
        [...]
        ## open txtfile to add in QTabWidget
        ## when doubled clicked, I don't want to open same item again
        ## how should I check the state?

1 个答案:

答案 0 :(得分:0)

您可以使用自定义角色在双击项目上设置标记:

class MainWindow(QMainWindow):
    def __init__(self):
        ...
        qTreeView.setModel(PrjTreeModel())
        qTreeView.doubleClicked.connect(self.dClicked)

    def dblClicked(self, index):
        item = index.model().itemFromIndex(index)
        if not item.data(Qt.UserRole + 1):
            item.setData(True, Qt.UserRole + 1)
            print('open txt file:', item.text())
        else:
            print('already double-clicked')