简体   繁体   English

使用PyQt4中的QTableWidget显示来自sqlite数据库的行

[英]Displaying rows from sqlite databse using QTableWidget in PyQt4

    with sqlite3.connect('database.db') as db:
        cursor=db.cursor()
        cursor.execute('select* from Item Order BY Name ASC')
        title = [cn[0] for cn in cursor.description]
        rows = [cn[0] for cn in cursor.description]
        cur=cursor.fetchall()


        layout = QtGui.QGridLayout() 
        self.test = QtGui.QLineEdit('test') #This is just a test for printing text into the table and works fine.

        self.table = QtGui.QTableWidget()

        for rows in cur:
            print(rows[1]) #This is just a test to see if the data could be printed into python shell, which worked.


            #self.test2 = QtGui.QLineEdit(cur)
            #self.table.setVerticalHeaderLabels(rows)

        self.table.setRowCount(3)
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(title) #This code works fine, the column headers are the ones from my database.
        #self.table.setVerticalHeaderItem(1,row)

        layout.addWidget(self.table, 0, 0)
        self.table.setItem(0, 0, QtGui.QTableWidgetItem(self.test.text()))
        #self.table.setItem(1, 0, QtGui.QTableWidgetItem(self.test2.text()))

        self.setLayout(layout)

Hashed out code are areas I played with but are causing errors, or just not working. 隐藏的代码是我玩过的区域,但是会导致错误,或者就是行不通。 I attached all of the code for the table to make it easier to understand what I am trying to accomplish. 我附加了表的所有代码,以使您更容易理解我要完成的工作。

This program currently opens a table with the column headers from the database, with 3 empty rows (excluding test). 该程序当前使用数据库中的列标题打开一个表,其中包含3个空行(不包括测试)。 I would like the fill these rows automatically with the value from my sqlite database. 我想用sqlite数据库中的值自动填充这些行。 If there is any information you need to know please ask. 如果您需要了解任何信息,请询问。

You can do something like this: 您可以执行以下操作:

    cur=cursor.fetchall()   
    for i,row in enumerate(cur):
        for j,val in enumerate(row):
            table.setItem(i, j, QtGui.QTableWidgetItem(str(val)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM