Using PyQt to Retrieve Data from a QTableWidget and Save it to a Database

Posted by


PyQt is a set of Python bindings for the Qt application framework and runs on all platforms supported by Qt including Windows, MacOS, iOS, and Android. It is widely used for creating desktop applications with a modern and user-friendly interface. In this tutorial, we will learn how to read data from a QTableWidget in PyQt and insert it into a database using SQLite.

Let’s start by creating a PyQt application with a QTableWidget and a QPushButton. The QTableWidget will display some data, and the QPushButton will allow us to read this data and insert it into a database.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QPushButton, QVBoxLayout, QWidget
import sqlite3

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 600, 400) 
        self.setWindowTitle("PyQt Read Data From QTableWidget and Insert Into Database")

        self.table = QTableWidget()
        self.table.setColumnCount(2)
        self.table.setHorizontalHeaderLabels(['Name', 'Age'])

        self.button = QPushButton("Insert Data Into Database")
        self.button.clicked.connect(self.insert_data_into_database)

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        layout.addWidget(self.button)

        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)

    def insert_data_into_database(self):
        conn = sqlite3.connect('data.db')
        c = conn.cursor()

        c.execute("CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)")

        for row in range(self.table.rowCount()):
            name = self.table.item(row, 0).text()
            age = int(self.table.item(row, 1).text())

            c.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))

        conn.commit()
        conn.close()

        print("Data inserted into database")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

In this code snippet, we create a PyQt application with a main window that contains a QTableWidget and a QPushButton. We set up the layout using QVBoxLayout and add the widgets to the layout. The QPushButton is connected to a method called insert_data_into_database. Inside this method, we establish a connection to a SQLite database named data.db, create a table named users if it doesn’t exist, and then loop through the rows of the QTableWidget to fetch the data in each cell and insert it into the database.

To run this code, save it in a file named main.py and run it using the following command:

python main.py

Now, let’s add some data to the QTableWidget in our PyQt application. We can do this by adding a few lines of code in the MyWindow class:

    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 600, 400)
        self.setWindowTitle("PyQt Read Data From QTableWidget and Insert Into Database")

        self.table = QTableWidget()
        self.table.setColumnCount(2)
        self.table.setHorizontalHeaderLabels(['Name', 'Age'])

        data = [['Alice', '25'], ['Bob', '30'], ['Charlie', '35']]

        for i, (name, age) in enumerate(data):
            self.table.insertRow(i)
            self.table.setItem(i, 0, QTableWidgetItem(name))
            self.table.setItem(i, 1, QTableWidgetItem(age))

        self.button = QPushButton("Insert Data Into Database")
        self.button.clicked.connect(self.insert_data_into_database)

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        layout.addWidget(self.button)

        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)

Now, when you run the application, you will see the data displayed in the QTableWidget. Clicking the "Insert Data Into Database" button will insert this data into the SQLite database.

That’s it! You have successfully learned how to read data from a QTableWidget in PyQt and insert it into a database using SQLite. PyQt is a powerful framework for creating desktop applications with Python, and it provides a wide range of tools for creating interactive and user-friendly interfaces. If you have any questions or run into any issues, feel free to ask for help in the comments. Happy coding!

0 0 votes
Article Rating

Leave a Reply

9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@le_travie7724
3 days ago

Thank you very much sir. This method is by far the simplest solution I've seen all day and saved me from committing several unnecessary functions into my application. Many thanks.

@Life-zx5wp
3 days ago

how can i read that cell like label.text()

@chambasv5402
3 days ago

Man, I'm a noob on this hehe. Can you tell me what's in line 29? (queryStr) because it gives me an error "sqlite3.OperationalError: incomplete input" :'3

@akhilbabu476
3 days ago

How to update data by clicking the values in the qtableview

@freegymmanagementsoftware8975
3 days ago

Thank you

@KurtKeunen
3 days ago

Hi! great video/tutorial! could you please reupload the files? the files are no longer available, thx!

@suganthiganesh6101
3 days ago

Hi,
How to append the qtable widget data as a numpy array?
I have to give the input as numeric values then do some calculation like below.

rowCount = self.tableWidgetInput.rowCount()

columnCount = self.tableWidgetInput.columnCount()

if (rowCount==columnCount):

size=rowCount

print("The size of the matrxi is %d * %d "%(size,size))

print("The Given matrxi is", "SUM of Row" )

for row in range(size):

rowData =[]

for column in range (size):

widegetItem = self.tableWidgetInput.item(row,column)

if(widegetItem and widegetItem.text):

rowData.append(widegetItem.text())

else:

rowData.append('NULL')

inputArray = np.array(rowData,dtype=np.float64) ###convert the list into numpy array.

print(inputArray)

sumofCol = np.sum(inputArray,axis = 0,dtype='float') ###find the sum of Column

sumofRow = np.sum(inputArray,axis = 0,dtype='float') ### find the sum of Row

@suganthiganesh6101
3 days ago

Hi ,
Thank you so much for the great tutorial. I can't find where i am doing mistakes? Can you Please help . I Was trying to store 4*4 array values into db
The size of the matrxi is 4 * 4

['NULL', 'NULL', 'NULL', 'NULL']

Traceback (most recent call last):

File "DEMATMM.py", line 75, in submit

self.insertRowintoDB(rowData)

File "DEMATMM.py", line 32, in insertRowintoDB

queryStr.execute(queryStr,rowData)

AttributeError: 'str' object has no attribute 'execute'

@mitochondria7846
3 days ago

i can make Database with Qlistwidget ?

9
0
Would love your thoughts, please comment.x
()
x