Using PyQt to Display Database Data in a QTableWidget

Posted by


In this tutorial, we will learn how to fetch data from a database and display it in a QTableWidget using PyQt. We will use Python as the programming language and SQLite as the database.

Step 1: Install PyQt and SQLite
Before we start, make sure you have PyQt and SQLite installed on your machine. You can install these packages using pip:

pip install PyQt5
pip install sqlite3

Step 2: Create a SQLite Database
We will create a simple SQLite database with a table called "employees" that contains three columns: id, name, and age. You can create a new database file using a SQLite client or run the following code in Python:

import sqlite3

conn = sqlite3.connect('employees.db')
c = conn.cursor()

c.execute('''CREATE TABLE employees
             (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

conn.commit()
conn.close()

Step 3: Populate the Database
Next, we will populate the "employees" table with some sample data. You can insert data using a SQLite client or run the following code in Python:

conn = sqlite3.connect('employees.db')
c = conn.cursor()

c.execute("INSERT INTO employees (name, age) VALUES ('Alice', 25)")
c.execute("INSERT INTO employees (name, age) VALUES ('Bob', 30)")
c.execute("INSERT INTO employees (name, age) VALUES ('Charlie', 35)")

conn.commit()
conn.close()

Step 4: Create a PyQt Application
Now, let’s create a PyQt application that fetches data from the database and displays it in a QTableWidget. Here’s the code:

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

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

        self.setWindowTitle("Employee Data")
        self.setGeometry(100, 100, 600, 400)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setGeometry(50, 50, 500, 300)
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setHorizontalHeaderLabels(['ID', 'Name', 'Age'])

        conn = sqlite3.connect('employees.db')
        c = conn.cursor()
        c.execute("SELECT * FROM employees")
        data = c.fetchall()

        for row_num, row_data in enumerate(data):
            self.tableWidget.insertRow(row_num)
            for col_num, col_data in enumerate(row_data):
                self.tableWidget.setItem(row_num, col_num, QTableWidgetItem(str(col_data)))

        conn.close()

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

Step 5: Run the Application
Save the code in a file (e.g., main.py) and run it using Python. You should see a window with a table displaying the employee data fetched from the database.

That’s it! You have successfully displayed data in a QTableWidget from a database using PyQt. Feel free to customize the application further to meet your specific requirements.

0 0 votes
Article Rating
45 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@selinavc-
30 days ago

CAN WE TAKE THE DATA FROM POSTGRESQL WİTH THİS WAY

@Thoreller
30 days ago

Well Done!!!

@Heron31415
30 days ago

Thank you for your lesson! Can I make dynamic Tableview using as source pivot table aggregated by pandas?

@alexgutz5450
30 days ago

I cannot try the program since the database file is SETUP.EXE and the antivirus is saying there is a trojan horse. I have you can just attach the database file.

@emrekucuk172
30 days ago

thanks for sharing dude. You're the best ! you helped me very much. Thank you again.

@codewithelyanan6536
30 days ago

Great Tutorial but, the file like have expired.

@neo92vip
30 days ago

Warning: All changes made in this file will be lost….

Never edit that file. You need to create separate class and promote the object to that class… You are giving bad design practises.

@cindyyeon489
30 days ago

Thank you! Great help for me !!

@lavizlay
30 days ago

A problem I generally have; My 'connect' queries are not working. Neither 'sqlite connect' nor 'clicked connect'. Can you help me?

@Екатерина-б8р3м
30 days ago

Только начинаю работать с PyQt. Я просмотрела множество видео о работе с таблицами, но все так нудно рассказывают и растягивают время, я не могла понять принцип использования. Здесь я ни слова не поняла, но наглядная демонстрация настолько хороша, что я научилась работать с таблицами в PyQt. Потрясающе

@davidthompson3876
30 days ago

Excellent tutorial thank you.
Hope you do more.

@sanjaynt7434
30 days ago

Thanks mam for the explanation it helped me a lot

@nataliejanepacificar7068
30 days ago

Thanks for this!

@fatihislgan7437
30 days ago

thanks bro

@AbhishekSharma-uy1zv
30 days ago

I am confused in the above error what to do with that plzz help plzz

@AbhishekSharma-uy1zv
30 days ago

Error-'Ui_MainWindow' object has no attribute 'tabelWidget'
Plzz sir reply for my error

@Knowledge_Hub5000
30 days ago

Dear sir, do you have any video or codings regarding uploading map with coordinates reading over it,
email: prasad.aasp@gmail.com

@arpitagec9
30 days ago

How can we add the column names (I dont want the nos. to appear as heading)? Also, if we want to load all the records (without restricting to a few records)?

@piyushranjansahoo9830
30 days ago

File is not available in that link. Please send me

@maximilian4618
30 days ago

That moment when you forget to insert 'd'
Jokes aside, thank you very much for sharing this little bit of information, it is very helpful!