使用pyqt

问题描述

我想用列表中的给定数据创建一个TreeTable。目前,我仅在QTableView和QAbstractTableModel的帮助下创建了一个普通表。现在,我想将其转换为树。

树应该看起来像这样:

Event        Time       Parent    Deepness
A           00:00:01    True        0
--> B       00:00:05    False       1
----> C     00:00:07    False       2
-------> D  00:00:08    False       3
----> E     00:00:13    False       2
--> F       00:00:17    False       1
G           00:00:21    True        0
--> H       00:00:21    False       1   
--> I       00:00:21    False       1,J           00:00:21    True        0

这意味着A是B的父级,而B是C的父级,依此类推...每个列表的最后一个值将显示每一行的深度。因此0表示父母,1表示孩子,2表示孩子... 如果有更好的方式来显示给定的数据,我可以对其进行自定义

这是我创建标准QTableView的方法

from PyQt5 import QtWidgets,QtGui,QtCore
import pandas as pd
import sys

class MainFrame(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)

        data = [["A","00:00:01",True,0],["B","00:00:05",False,1],["C","00:00:07",2],["D","00:00:08",3],["E","00:00:13",["F","00:00:17",["G","00:00:21",0]]
        
        self.event_table = QtWidgets.QTableView()
        self.event_table.resizeRowsToContents()
        self.event_table.horizontalHeader().setStretchLastSection(True)
        
        df = pd.DataFrame(data,columns=["Event","Time","root","Deepness"])
        self.model = EventTableModel(df)
        self.event_table.setModel(self.model)
        self.setCentralWidget(self.event_table)


class EventTableModel(QtCore.QAbstractTableModel):
    def __init__(self,data):
        super(EventTableModel,self).__init__()
        self._data = data
        self._color = QtGui.QBrush(QtGui.QColor(230,230,230))

    def data(self,index,role):
        if role ==  QtCore.Qt.displayRole:
            value = self._data.iloc[index.row(),index.column()]
            return str(value)
        
        if role == QtCore.Qt.BackgroundRole and index.row() % 2 == 0:
            #return QtGui.QBrush(QtGui.QColor(230,230))
            return self._color
    
    def headerData(self,section,orientation,role):
        # section is the index of the column/row.
        if role ==  QtCore.Qt.displayRole:
            if orientation ==  QtCore.Qt.Horizontal:
                return str(self._data.columns[section])

            if orientation ==  QtCore.Qt.Vertical:
                return str(self._data.index[section])

    def rowCount(self,index):
        return self._data.shape[0] 

    def columnCount(self,index):
        return self._data.shape[1]


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main = MainFrame()
    main.show()
    sys.exit(app.exec_())

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)