In this posting, we will learn how to create the desktop application using PyQt6.
Installation
$ pip install pyqt6
Now, we prepared for using PyQt6.
Create Application
Using Function
import sys
from PyQt6.QtWidgets import QApplication, QWidget
def main():
w = QWidget()
w.resize(320, 240)
w.setWindowTitle('PyQt6 Example')
w.show()
sys.exit(app.exec())
if __name__ == '__main__':
app = QApplication(sys.argv)
main()
This is the simplest way to create windows
Using Class with QWidget
import sys
from PyQt6.QtWidgets import QApplication, QWidget
class Example(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.setGeometry(300, 300, 320, 240)
self.setWindowTitle('PyQt6 Example')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
The result is not different from the previous code.
However, this code is more scalable and maintainable using the class.
Using Class with QMainWindow
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.statusBar().showMessage('Ready')
self.setGeometry(300, 300, 320, 240)
self.setWindowTitle('PyQt6 Example')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
If you using QMainWindow, you can add menubar, toolbar, and statusbar.
But unfortunately, PyQt6 seems that is not fully supported menubar yet.
I couldn't find the way that menubar is visible.
Add Layout and Widget
import sys
from PyQt6.QtWidgets import QApplication, QGridLayout, QLabel, QWidget
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
label = QLabel('Hello PyQt6')
layout = QGridLayout()
layout.addWidget(label)
self.setLayout(layout)
self.setGeometry(300, 300, 320, 240)
self.setWindowTitle('PyQt6 Example')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
We added a label widget into the grid layout.
And we set the grid layout to the main layout of our application.
Conclusion
We learned the method of how to create a desktop application using PyQt6.
But, I recommend you to use PyQt5.
I don't think PyQt6 is stable so far.
In addition, it does not seem to fully support features than PyQt5.
Reference
'Python' 카테고리의 다른 글
[Python] Docstring (0) | 2021.10.18 |
---|---|
[Python] Running Python with Docker (0) | 2021.08.28 |
[Python3] typing module (0) | 2021.07.03 |
[Python] Decorator (0) | 2021.06.29 |
[Python] Draw shapes using tkinter (0) | 2021.05.29 |
댓글