sqlite3 table into QTableWidget, sqlite3, PyQt5

后端 未结 1 717
我寻月下人不归
我寻月下人不归 2020-12-18 15:09

I have created a program that manages tables in a database, now i\'m trying to make a gui for it, and i figured the easiest way would be to do it with Qt Designer and then c

相关标签:
1条回答
  • 2020-12-18 16:05

    Before I answer this question, I highly recommend you open up your UI file in the Qt Designer and change your object names from tableWidget_2 and pushButton to something more appropriate as you are going to drive yourself insane.

    Second of all, PyQt provides an entire API to work with databases called QtSql. You can access the api like so:

    from PyQt5.QtSql import (QSqlDatabase, QSqlQuery) #and so on.
    

    Rant over. I will answer your question now.

    QTableWidgets are quite precarious to work with and require a couple of things:

    1. A Counter Flag
    2. Row Count
    3. Column Count
    4. Data (Obviously)

    To insert data into the table you could do something like this.

    def add_values(self):
        self.count = self.count + 1 # this is incrementing counter
        self.tableWidget_2.insertRow(self.count)
        self.tableWidget_2.setRowCount(self.count)
        # these are the items in the database
        item = [column1, column2, column3]
        # here we are adding 3 columns from the db table to the tablewidget
        for i in range(3):
            self.tableWidget_2.setItem(self.count - 1, i, QTableWidgetItem(item[i]))
    

    However, if you just want to load the data into the QTableWidget you could do something like this and call it in the setup:

    def load_initial_data(self):
        # where c is the cursor
        self.c.execute('''SELECT * FROM table ''')
        rows = self.c.fetchall()
    
        for row in rows:
            inx = rows.index(row)
            self.tableWidget_2.insertRow(inx)
            # add more if there is more columns in the database.
            self.tableWidget_2.setItem(inx, 0, QTableWidgetItem(row[1]))
            self.tableWidget_2.setItem(inx, 1, QTableWidgetItem(row[2]))
            self.tableWidget_2.setItem(inx, 2, QTableWidgetItem(row[3]))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题