KEMBAR78
Qt for Python | PDF
Integrated Computer Solutions Inc. www.ics.com
Qt for Python
March 21, 2019
Copyright 2019, Integrated Computers Solutions, Inc.
This work may not be reproduced in whole or in part without the express written consent of Integrated Computer Solutions, Inc.
1
Integrated Computer Solutions Inc. www.ics.com
What is Qt for Python?
• Also known as PySide 2
• Qt for Python are the Python v2 and v3 bindings for Qt
• Qt for Python gives the Python programmer access to the full Qt API
• API is the same from C++
• Qt for Python is available under the LGPL v3 and the Qt Commercial License.
• Owned and distributed by The Qt Company
2
Integrated Computer Solutions Inc. www.ics.com
Other Features
• The APIs are almost identical to C++, so experienced Qt users can quickly get
up to speed and leverage their Qt knowledge.
• You can continue to use Qt Designer .ui files and resources.
• If you are porting a C++ application, you can mostly one for one port much of
the code.
• Run time errors are usually straightforward.
• A developer can be very productive due to not needing a compile/build cycle.
https://www.ics.com/blog/we-ported-qt-app-c-python-heres-what-happened
3
Integrated Computer Solutions Inc. www.ics.com
Confusion with PyQt
• PyQt is another product that provides Python bindings to Qt (and is mostly
compatible with PySide)
• PyQt is dual licensed on all supported platforms under the GNU GPL v3 and
the Riverbank Commercial License (LGPL not available)
• PyQt is owned and distributed by Riverbank
• Differences between Python for Qt and PyQt are discussed here:
https://machinekoder.com/pyqt-vs-qt-for-python-pyside2-pyside/
4
Integrated Computer Solutions Inc. www.ics.com
What is Qt?
• Cross-Platform C++ class library
• Encompasses some 1,500 C++ classes
• Started as a Graphics User Interface (GUI) toolkit
• Is much more today: Threads, XML/JSON parsing, Regular Expressions, Sockets, HTML parsing
• Development for Desktop and Embedded Devices
• Qt is available under commercial and open source licenses
• In addition to class libraries, Qt framework contains several tools, like Qt Creator (IDE), Qt Designer,
qmake, Qt Linguist
• Owned and distributed by The Qt Company
5
Integrated Computer Solutions Inc. www.ics.com
How to Install
• After you have installed Python,
• Python install is in your path
• Other ways to install (including building):
https://wiki.qt.io/Qt_for_Python/GettingStarted
pip install PySide2
6
Integrated Computer Solutions Inc. www.ics.com
“Hello World” in Pyside 2 — Widget-Based
#!/usr/bin/env python3
import sys
from PySide2.QtWidgets import QApplication, QPushButton
if __name__ == '__main__':
app = QApplication(sys.argv)
button = QPushButton(None) #Creates a widget
button.setText("Hello world")
button.show()
sys.exit(app.exec_()) #Starts the event loop
Program consists of:
• py_qtsimple.py
7
Integrated Computer Solutions Inc. www.ics.com
A First Example with Widgets
class customWidget(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle(self.tr("My First Example"))
self.label = QtWidgets.QLabel("Note:", self)
self.edit = QtWidgets.QTextEdit(self)
self.clear = QtWidgets.QPushButton("Clear", self)
self.save = QtWidgets.QPushButton("Save", self)
# Widget layout
self.outer = QtWidgets.QVBoxLayout()
self.outer.addWidget(self.label)
self.outer.addWidget(self.edit)
self.inner = QtWidgets.QHBoxLayout()
self.inner.addWidget(self.clear)
self.inner.addWidget(self.save)
self.setLayout(self.outer)
# Nesting layouts
self.outer.addLayout(self.inner)
8
Integrated Computer Solutions Inc. www.ics.com
“Hello World” in Pyside2 — Qt Quick-Based
9
#!/usr/bin/env python3
import sys
from PySide2.QtCore import QUrl
from PySide2.QtQuick import QQuickView
from PySide2.QtWidgets import QApplication
if __name__ == '__main__':
app = QApplication(sys.argv)
view = QQuickView()
view.setSource(QUrl('main.qml'))
view.show() # window created in QML
sys.exit(app.exec_())
Program consists of
• HelloWorldQML.py – creation and startup of the QML engine (with executable
permissions)
• main.qml – application code
Integrated Computer Solutions Inc. www.ics.com
Qt Creator IDE
● Advanced C++, QML and Python code
editor
● 100% open source, written in Qt 5
● Integrated GUI layout and form designer
● Rapid code
navigation tools
● Supports multiple
Platforms
● Downloadable here
https://www.qt.io/offline-installers
10
Integrated Computer Solutions Inc. www.ics.com
Qt Components
List of available Qt modules are here:
https://doc.qt.io/qtforpython/?hsCtaTracking=fab9e910-0b90-4caa-b6d0-e202692b6f13%7Cb9e0be8d-1
d85-4644-aaa2-41de4e6d37e3#qt-modules
11
Integrated Computer Solutions Inc. www.ics.com
Use of Qt Designer
12
import sys
from PySide2 import QtWidgets
from form import Ui_Form
class MyForm(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = MyForm()
myapp.ui.pushButton.clicked.connect(app.quit)
myapp.show()
sys.exit(app.exec_())
• Requires the compilation of a form:
pyside2-uic.exe form.ui > form.py
Integrated Computer Solutions Inc. www.ics.com
Use of Qt Designer with UILoader
from PySide2.QtUiTools import QUiLoader
from PySide2 import QtWidgets
from PySide2.QtCore import QFile
class MyForm(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
file = QFile("form.ui")
file.open(QFile.ReadOnly)
self.loader = QUiLoader()
self.myWidget = self.loader.load(file, self)
file.close()
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.myWidget)
self.setLayout(layout)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
13
Integrated Computer Solutions Inc. www.ics.com
Signals and Slots
from PySide2.QtCore import SIGNAL, QObject
# define a new slot that receives a string and has
# 'saySomeWords' as its name
@Slot(str)
def say_some_words(words):
print(words)
class Communicate(QObject):
# create a new signal on the fly and name it 'speak'
speak = Signal(str)
someone = Communicate()
# connect signal and slot
someone.speak.connect(say_some_words)
# emit 'speak' signal
someone.speak.emit("Hello everybody!")
See https://wiki.qt.io/Qt_for_Python_Signals_and_Slots
14
Integrated Computer Solutions Inc. www.ics.com
Reimplementing Events
from PySide2.QtWidgets import QWidget
from PySide2.QtCore import Qt, Signal
class MainWidget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.resize(400, 300)
self.setWindowTitle("Widget Event Example")
self.setFocusPolicy(Qt.StrongFocus)
def mousePressEvent(self, event):
if self.m_logAll:
self.notifyEvent['QString', 'QEvent'].emit("mousePressEvent", event)
super(MainWidget, self).mousePressEvent(event)
15
Integrated Computer Solutions Inc. www.ics.com
The Property System
from PySide2.QtCore import QObject, Signal, Property
class Person(QObject):
def __init__(self, name):
QObject.__init__(self)
self._person_name = name
def _name(self):
return self._person_name
@Signal
def name_changed(self):
pass
name = Property(str, _name, notify=name_changed)
• Useful in QML
16
Integrated Computer Solutions Inc. www.ics.com
Some Notes to Keep in Mind
• No QString, use Python string (str)
• The Qt container classes are not available, use the ones provided by Python
• Some Qt method names Qt names have had an underscore appended to
resolve this conflict (i.e. QTextStream methods bin_(), hex_(), oct_() and
QDialog exec_())
• No QVariants! Any Qt function expecting or returning a QVariant can receive
or return any Python object
17
Integrated Computer Solutions Inc. www.ics.com
Business Logic/UI Paradigm
18
Business Logic
Python
UI in Python
(Widgets)
Or QML
Integrated Computer Solutions Inc. www.ics.com
When to Use Non-GUI PySide 2
• Dealing with not blocking your GUI (QProcess, networking, QSerial vs.
PySerial, etc.)
• QSqlDatabase because you want to show it in a QTableView
• Better integration with Qt in general (e.g. QThread)
19
Integrated Computer Solutions Inc. www.ics.com
Where to Get Help
• https://qmlbook.github.io/ch18-python/python.html
• PySide2 Mailing List https://lists.qt-project.org/mailman/listinfo/pyside
• AppDataLocalProgramsPythonPython37-32Libsite-packagesPySide2
examples
• Tutorial: https://build-system.fman.io/python-qt-tutorial
20
Integrated Computer Solutions Inc. www.ics.com
Programming with Qt for Python Training Course
● New 5-day hands-on introduction to developing desktop applications using
the official set of Python bindings covering:
● GUI programming
● GraphicsView
● Model/View
● Challenges inherent to mixing the Qt API with Python
● May 13 - 17 - Waltham, MA
● June 24 - 28, Sunnyvale, CA
● https://www.ics.com/learning/training/programming-qt-python
21

Qt for Python

  • 1.
    Integrated Computer SolutionsInc. www.ics.com Qt for Python March 21, 2019 Copyright 2019, Integrated Computers Solutions, Inc. This work may not be reproduced in whole or in part without the express written consent of Integrated Computer Solutions, Inc. 1
  • 2.
    Integrated Computer SolutionsInc. www.ics.com What is Qt for Python? • Also known as PySide 2 • Qt for Python are the Python v2 and v3 bindings for Qt • Qt for Python gives the Python programmer access to the full Qt API • API is the same from C++ • Qt for Python is available under the LGPL v3 and the Qt Commercial License. • Owned and distributed by The Qt Company 2
  • 3.
    Integrated Computer SolutionsInc. www.ics.com Other Features • The APIs are almost identical to C++, so experienced Qt users can quickly get up to speed and leverage their Qt knowledge. • You can continue to use Qt Designer .ui files and resources. • If you are porting a C++ application, you can mostly one for one port much of the code. • Run time errors are usually straightforward. • A developer can be very productive due to not needing a compile/build cycle. https://www.ics.com/blog/we-ported-qt-app-c-python-heres-what-happened 3
  • 4.
    Integrated Computer SolutionsInc. www.ics.com Confusion with PyQt • PyQt is another product that provides Python bindings to Qt (and is mostly compatible with PySide) • PyQt is dual licensed on all supported platforms under the GNU GPL v3 and the Riverbank Commercial License (LGPL not available) • PyQt is owned and distributed by Riverbank • Differences between Python for Qt and PyQt are discussed here: https://machinekoder.com/pyqt-vs-qt-for-python-pyside2-pyside/ 4
  • 5.
    Integrated Computer SolutionsInc. www.ics.com What is Qt? • Cross-Platform C++ class library • Encompasses some 1,500 C++ classes • Started as a Graphics User Interface (GUI) toolkit • Is much more today: Threads, XML/JSON parsing, Regular Expressions, Sockets, HTML parsing • Development for Desktop and Embedded Devices • Qt is available under commercial and open source licenses • In addition to class libraries, Qt framework contains several tools, like Qt Creator (IDE), Qt Designer, qmake, Qt Linguist • Owned and distributed by The Qt Company 5
  • 6.
    Integrated Computer SolutionsInc. www.ics.com How to Install • After you have installed Python, • Python install is in your path • Other ways to install (including building): https://wiki.qt.io/Qt_for_Python/GettingStarted pip install PySide2 6
  • 7.
    Integrated Computer SolutionsInc. www.ics.com “Hello World” in Pyside 2 — Widget-Based #!/usr/bin/env python3 import sys from PySide2.QtWidgets import QApplication, QPushButton if __name__ == '__main__': app = QApplication(sys.argv) button = QPushButton(None) #Creates a widget button.setText("Hello world") button.show() sys.exit(app.exec_()) #Starts the event loop Program consists of: • py_qtsimple.py 7
  • 8.
    Integrated Computer SolutionsInc. www.ics.com A First Example with Widgets class customWidget(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(self) self.setWindowTitle(self.tr("My First Example")) self.label = QtWidgets.QLabel("Note:", self) self.edit = QtWidgets.QTextEdit(self) self.clear = QtWidgets.QPushButton("Clear", self) self.save = QtWidgets.QPushButton("Save", self) # Widget layout self.outer = QtWidgets.QVBoxLayout() self.outer.addWidget(self.label) self.outer.addWidget(self.edit) self.inner = QtWidgets.QHBoxLayout() self.inner.addWidget(self.clear) self.inner.addWidget(self.save) self.setLayout(self.outer) # Nesting layouts self.outer.addLayout(self.inner) 8
  • 9.
    Integrated Computer SolutionsInc. www.ics.com “Hello World” in Pyside2 — Qt Quick-Based 9 #!/usr/bin/env python3 import sys from PySide2.QtCore import QUrl from PySide2.QtQuick import QQuickView from PySide2.QtWidgets import QApplication if __name__ == '__main__': app = QApplication(sys.argv) view = QQuickView() view.setSource(QUrl('main.qml')) view.show() # window created in QML sys.exit(app.exec_()) Program consists of • HelloWorldQML.py – creation and startup of the QML engine (with executable permissions) • main.qml – application code
  • 10.
    Integrated Computer SolutionsInc. www.ics.com Qt Creator IDE ● Advanced C++, QML and Python code editor ● 100% open source, written in Qt 5 ● Integrated GUI layout and form designer ● Rapid code navigation tools ● Supports multiple Platforms ● Downloadable here https://www.qt.io/offline-installers 10
  • 11.
    Integrated Computer SolutionsInc. www.ics.com Qt Components List of available Qt modules are here: https://doc.qt.io/qtforpython/?hsCtaTracking=fab9e910-0b90-4caa-b6d0-e202692b6f13%7Cb9e0be8d-1 d85-4644-aaa2-41de4e6d37e3#qt-modules 11
  • 12.
    Integrated Computer SolutionsInc. www.ics.com Use of Qt Designer 12 import sys from PySide2 import QtWidgets from form import Ui_Form class MyForm(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) myapp = MyForm() myapp.ui.pushButton.clicked.connect(app.quit) myapp.show() sys.exit(app.exec_()) • Requires the compilation of a form: pyside2-uic.exe form.ui > form.py
  • 13.
    Integrated Computer SolutionsInc. www.ics.com Use of Qt Designer with UILoader from PySide2.QtUiTools import QUiLoader from PySide2 import QtWidgets from PySide2.QtCore import QFile class MyForm(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) file = QFile("form.ui") file.open(QFile.ReadOnly) self.loader = QUiLoader() self.myWidget = self.loader.load(file, self) file.close() layout = QtWidgets.QVBoxLayout() layout.addWidget(self.myWidget) self.setLayout(layout) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_()) 13
  • 14.
    Integrated Computer SolutionsInc. www.ics.com Signals and Slots from PySide2.QtCore import SIGNAL, QObject # define a new slot that receives a string and has # 'saySomeWords' as its name @Slot(str) def say_some_words(words): print(words) class Communicate(QObject): # create a new signal on the fly and name it 'speak' speak = Signal(str) someone = Communicate() # connect signal and slot someone.speak.connect(say_some_words) # emit 'speak' signal someone.speak.emit("Hello everybody!") See https://wiki.qt.io/Qt_for_Python_Signals_and_Slots 14
  • 15.
    Integrated Computer SolutionsInc. www.ics.com Reimplementing Events from PySide2.QtWidgets import QWidget from PySide2.QtCore import Qt, Signal class MainWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.resize(400, 300) self.setWindowTitle("Widget Event Example") self.setFocusPolicy(Qt.StrongFocus) def mousePressEvent(self, event): if self.m_logAll: self.notifyEvent['QString', 'QEvent'].emit("mousePressEvent", event) super(MainWidget, self).mousePressEvent(event) 15
  • 16.
    Integrated Computer SolutionsInc. www.ics.com The Property System from PySide2.QtCore import QObject, Signal, Property class Person(QObject): def __init__(self, name): QObject.__init__(self) self._person_name = name def _name(self): return self._person_name @Signal def name_changed(self): pass name = Property(str, _name, notify=name_changed) • Useful in QML 16
  • 17.
    Integrated Computer SolutionsInc. www.ics.com Some Notes to Keep in Mind • No QString, use Python string (str) • The Qt container classes are not available, use the ones provided by Python • Some Qt method names Qt names have had an underscore appended to resolve this conflict (i.e. QTextStream methods bin_(), hex_(), oct_() and QDialog exec_()) • No QVariants! Any Qt function expecting or returning a QVariant can receive or return any Python object 17
  • 18.
    Integrated Computer SolutionsInc. www.ics.com Business Logic/UI Paradigm 18 Business Logic Python UI in Python (Widgets) Or QML
  • 19.
    Integrated Computer SolutionsInc. www.ics.com When to Use Non-GUI PySide 2 • Dealing with not blocking your GUI (QProcess, networking, QSerial vs. PySerial, etc.) • QSqlDatabase because you want to show it in a QTableView • Better integration with Qt in general (e.g. QThread) 19
  • 20.
    Integrated Computer SolutionsInc. www.ics.com Where to Get Help • https://qmlbook.github.io/ch18-python/python.html • PySide2 Mailing List https://lists.qt-project.org/mailman/listinfo/pyside • AppDataLocalProgramsPythonPython37-32Libsite-packagesPySide2 examples • Tutorial: https://build-system.fman.io/python-qt-tutorial 20
  • 21.
    Integrated Computer SolutionsInc. www.ics.com Programming with Qt for Python Training Course ● New 5-day hands-on introduction to developing desktop applications using the official set of Python bindings covering: ● GUI programming ● GraphicsView ● Model/View ● Challenges inherent to mixing the Qt API with Python ● May 13 - 17 - Waltham, MA ● June 24 - 28, Sunnyvale, CA ● https://www.ics.com/learning/training/programming-qt-python 21