PySide6中的TableView是一个用于显示和编辑表格数据的控件。以下是一个简单的使用TableView的示例代码:

from PySide6.QtCore import Qt, QAbstractTableModel
from PySide6.QtGui import QStandardItemModel
from PySide6.QtWidgets import QApplication, QMainWindow, QTableView

class MyTableModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self.data = data

    def rowCount(self, parent):
        return len(self.data)

    def columnCount(self, parent):
        if len(self.data) > 0:
            return len(self.data[0])
        return 0

    def data(self, index, role):
        if role == Qt.DisplayRole:
            row = index.row()
            col = index.column()
            return str(self.data[row][col])

    def headerData(self, section, orientation, role):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return f"Column {section+1}"
            else:
                return f"Row {section+1}"

if __name__ == "__main__":
    app = QApplication([])
    window = QMainWindow()
    
    # 创建模型和数据
    data = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    model = MyTableModel(data)

    # 创建TableView并设置模型
    table = QTableView()
    table.setModel(model)

    # 设置TableView的行和列大小调整模式
    table.resizeColumnsToContents()
    table.resizeRowsToContents()

    # 将TableView添加到主窗口
    window.setCentralWidget(table)
    window.show()

    app.exec()

在这个示例中,我们首先定义了一个自定义的TableModel类,继承自QAbstractTableModel。在该类中,我们重写了rowCount()、columnCount()、data()和headerData()等方法,用于定义表格的行数、列数、数据以及表头。然后,我们创建了一个数据列表,并将其传递给TableModel。接下来,我们创建一个TableView,并将TableModel设置为其模型。最后,将TableView添加到主窗口并显示出来。

这是一个非常简单的TableView使用示例,你可以根据自己的需求进一步扩展和定制TableView的功能

pyside6 tableView的用法

原文地址: https://www.cveoy.top/t/topic/h2rV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录