0

我将 qt 与 Python 一起使用。

我想实现一个多列的树视图。一列已经在工作。

如果我只向 treeView 添加一个文本项(变量 txt),它可以工作)


class TreeStandardItem(QStandardItem):
    def __init__(self, txt='', font_size=12, set_bold=False, color=QColor(0, 0, 0)):
        super().__init__()

        fnt = QFont('Open Sans', font_size)
        fnt.setBold(set_bold)

        self.setEditable(False)
        self.setForeground(color)
        self.setFont(fnt)
        
        # one Item is added to treeView
        self.setText(txt) 


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
       #...
       #...
       texas = TreeStandardItem('texas', 10)
       nyc = TreeStandardItem('NYC', 10)

       # Create Link between parent and child
       texas.appendRow(nyc)

       treeView = self.ui.treeView1

       # Create Model
       treeModel = QStandardItemModel()
       rootNode = treeModel.invisibleRootItem()

       # Header
       treeModel.setHeaderData(0, Qt.Horizontal, 'Column-1')
       treeModel.setHeaderData(1, Qt.Horizontal, 'Column-2')
       treeModel.setHeaderData(2, Qt.Horizontal, 'Column-3')

        # Add roots to  the view
        rootNode.appendRow(texas)
   
        #...  

我想为 treeView 的层次结构添加一些数据库日期,例如:

Column1-------------------------------Column2------------------------Column3

-> Parent                            Firstname Lastname             User-ID
    -> Child 01                      Firstname Lastname             User-ID
       -> Another Child 01           Firstname Lastname             User-ID
       -> Another Child 02           Firstname Lastname             User-ID
    -> Child 02                      Firstname Lastname             User-ID

有什么解决办法吗?如果我将 txt 变量从字符串更改为列表,则会出现错误。这是修改后的代码:

class StandardItem(QStandardItem):
    def __init__(self, txt=[], font_size=10, set_bold=False, color=QColor(0, 0, 0)):
        super().__init__()

        fnt = QFont('Open Sans', font_size)
        fnt.setBold(set_bold)

        self.setEditable(False)
        self.setForeground(color)
        self.setFont(fnt)

        # works - iterating with list item is ok
        # self.setText(txt[1]) 

        # --------------- !!!! ---------------
        # Need something to loop over the columns..
        # --------------- !!!! ---------------



class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        # .....

        # Create model 
        
        treeModel = QStandardItemModel()
        rootNode = treeModel.invisibleRootItem()

        parent01 = StandardItem(['108112', 'Mary Luke', '55' ], 12, set_bold=True)
        rootNode.appendRow(parent01)

        child01 = StandardItem(['108108', 'Lukas Andrews', '13' ], 12, set_bold=True)
        parent01.appendRow(child01)

4

0 回答 0