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.
CAN WE TAKE THE DATA FROM POSTGRESQL WİTH THİS WAY
Well Done!!!
Thank you for your lesson! Can I make dynamic Tableview using as source pivot table aggregated by pandas?
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.
thanks for sharing dude. You're the best ! you helped me very much. Thank you again.
Great Tutorial but, the file like have expired.
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.
Thank you! Great help for me !!
A problem I generally have; My 'connect' queries are not working. Neither 'sqlite connect' nor 'clicked connect'. Can you help me?
Только начинаю работать с PyQt. Я просмотрела множество видео о работе с таблицами, но все так нудно рассказывают и растягивают время, я не могла понять принцип использования. Здесь я ни слова не поняла, но наглядная демонстрация настолько хороша, что я научилась работать с таблицами в PyQt. Потрясающе
Excellent tutorial thank you.
Hope you do more.
Thanks mam for the explanation it helped me a lot
Thanks for this!
thanks bro
I am confused in the above error what to do with that plzz help plzz
Error-'Ui_MainWindow' object has no attribute 'tabelWidget'
Plzz sir reply for my error
Dear sir, do you have any video or codings regarding uploading map with coordinates reading over it,
email: prasad.aasp@gmail.com
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)?
File is not available in that link. Please send me
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!