TypeError:QTableView(父:QWidget=None):参数1具有意外的类型“int”

2024-06-02 10:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的QTableView中显示数据库中的所有数据,但是错误

TypeError: QTableView(parent: QWidget = None): argument 1 has unexpected type 'int'

总是在最后出现。我不明白,因为我数据库中的所有数据类型都是varchars而不是int

下面是我调用数据的函数:

def connectDB(self):

        # TABLE
        columns = ['Time In','Time Out', 'Class', 'Color', 'Specific Attribute', 'Camera Number']
        tableWidget = QTableView(22, 6, self)
        tableWidget.setHorizontalHeaderLabels(columns)
        tableWidget.setGeometry( 400, 50, 850, 692)
        tableWidget.resizeRowsToContents()


        # CONNECTION
        conn = mariadb.connect(
        user="root",
        password="",
        host="localhost",
        port=3306,
        database="IRIS")

        cur = conn.cursor()
        cur.execute("SELECT * FROM iris_table")

        allSQLRows= cur.fetchall()
        tableWidget.setRowCount(len(allSQLRows))

        data = [allSQLRows]
        tableWidget.setModel(data)

Tags: columns数据self数据库datatime错误conn
1条回答
网友
1楼 · 发布于 2024-06-02 10:44:51

您有以下错误

  • QTableView不接受构造函数中的行数或列数,因此您似乎复制了接受它的QTableWidget的代码

  • Qt中的模型不是数组、列表等,而是从QabstracteModel继承的类

  • 如果您使用QTableWidget,那么您就不能使用模型,因为默认情况下它已经有一个不能修改的模型

考虑到上述情况,有两种可能的解决方案:

  • 将QTableView与模型一起使用

    labels = [
        "Time In",
        "Time Out",
        "Class",
        "Color",
        "Specific Attribute",
        "Camera Number",
    ]
    view = QTableView(self)
    model = QStandardItemModel(0, 6)
    view.setModel(model)
    model.setHorizontalHeaderLabels(labels)
    view.setGeometry(400, 50, 850, 692)
    view.resizeRowsToContents()
    
    conn = mariadb.connect(
        user="root", password="", host="localhost", port=3306, database="IRIS"
    )
    
    cur = conn.cursor()
    cur.execute("SELECT * FROM iris_table")
    
    allSQLRows = cur.fetchall()
    model.setRowCount(len(allSQLRows))
    
    for i, row_data in enumerate(allSQLRows):
        for j, data in enumerate(row_data):
            item = QStandardItem()
            item.setData(data, Qt.DisplayRole)
            model.setItem(i, j, item)
    
  • 使用QTableWidget

    labels = [
        "Time In",
        "Time Out",
        "Class",
        "Color",
        "Specific Attribute",
        "Camera Number",
    ]
    view = QTableWidget(0, 6, self)
    view.setHorizontalHeaderLabels(labels)
    view.setGeometry(400, 50, 850, 692)
    view.resizeRowsToContents()
    
    conn = mariadb.connect(
        user="root", password="", host="localhost", port=3306, database="IRIS"
    )
    
    cur = conn.cursor()
    cur.execute("SELECT * FROM iris_table")
    
    allSQLRows = cur.fetchall()
    view.setRowCount(len(allSQLRows))
    
    for i, row_data in enumerate(allSQLRows):
        for j, data in enumerate(row_data):
            item = QTableWidgetItem()
            item.setData(Qt.DisplayRole, data)
            view.setItem(i, j, item)
    

相关问题 更多 >