Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
547 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Should you be using QT for Python as a GUI? Part eight of an eight-part series of blogs |
---|
If you need to build a GUI system in Python, PyQt5 is probably the best choice, but don't take our word for it - read this blog and see what you think.
|
To attach data to a widget, create a model and then attach the model to the widget. For our example, we'll do this with a combo box:
When we run our form, the combo box will list out the Wise Owls.
Assuming that the combo box above is called cmbOwl, here's a way to populate it:
from PyQt5.QtWidgets import *
from PyQt5 import uic, QtSql # type: ignore
class MainWindow(QMainWindow):
# called when create new instance of our class based on a QT main window
def __init__(self):
# calls constructor for base class
super().__init__()
# get Python for form from QT Designer generated UI file
uic.loadUi("owl_form.ui", self)
# set this combo box
self.cmbOwl: QComboBox = self.findChild(QComboBox,"cmbOwl")
# open a database
self.db = QtSql.QSqlDatabase.addDatabase("QODBC3")
self.db.setDatabaseName(
"DRIVER={SQL Server};SERVER=.<<Server name here>>;DATABASE=<<Database name here>>;Trusted_Connection=yes;")
self.db.open()
# create a new model upon which to base combo box
self.model1 = QtSql.QSqlQueryModel()
# set the query to run against the database
sql_query = "SELECT PersonId, PersonName FROM vwTempOwl"
# apply this query
self.model1.setQuery(sql_query, self.db)
self.cmbOwl.setModel(self.model1)
self.cmbOwl.setModelColumn(1)
# set width to longest entry
width = self.cmbOwl.minimumSizeHint().width()
self.cmbOwl.view().setMinimumWidth(width)
# create a QT5 app, add a visible window to it and start event loop
app = QApplication([])
window = MainWindow()
window.show()
What this shows is the following instructions:
When you run this program you should see a list of the Wise Owls appearing:
The combo box is linked to the given query in the given database.
There's obviously a lot more to working with SQL Server data in QT, but this gives a flavour of how it works.
Parts of this blog |
---|
|
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.