First program for PyQt6

First program for PyQt6

In this part of the PyQt6 tutorial, we will learn some basic functions. These examples display tooltips and icons, close windows, display message boxes, and center windows on the desktop.

PyQt6 simple example

Here's a simple example that displays a small window. But we can do a lot with this window. We can resize it, maximize or minimize it. Implementing these functions usually requires writing a lot of code, but these functions are very common, so this part of the functions has been encapsulated, and we can use them directly. PyQt6 is a high-level toolkit, and the code examples below would likely take hundreds of lines to implement with a low-level toolkit.

# file: simple.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

In this example, we create a simple
window in PyQt6.

Author: Jan Bodnar
Website: zetcode.com
"""


import sys
from PyQt6.QtWidgets import QApplication, QWidget


def main():

    app = QApplication(sys.argv)

    w = QWidget()
    w.resize(250, 200)
    w.move(300, 300)

    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec())


if __name__ == '__main__':
    main()

The above code will display a small window on the screen.

import sys
from PyQt6.QtWidgets import QApplication, QWidget

The necessary packages are imported here, and the base widgets are located in PyQt6.QtWidgetsthe module.

app = QApplication(sys.argv)

Every PyQt6 application must create an application object. sys.argvarguments is a list of arguments from the command line. Python scripts can be run from the shell, which is one way the application starts.

w = QWidget()

The QWidget widget is the base class for all user interface objects in PyQt6. We provide a default constructor for QWidget. The default constructor has no parent. A widget without a parent is called a window.

w.resize(250, 150)

resizemethod changes the dimensions of the widget, now it is 250 pixels wide and 150 pixels high.

w.move(300, 300)

movemethod to move the widget to the specified coordinates (300, 300) on the screen.

w.setWindowTitle('Simple')

Use setWindowTitleto set the title of the window, which is displayed in the title bar.

w.show()

showMethods are methods that display widgets on the screen. The steps to display a widget are first created in memory and then displayed on the screen.

sys.exit(app.exec())

Finally, we enter the main loop of the application. Event handling starts here. The main loop receives events from the window system and dispatches them to application widgets. The main loop ends if we call the exit method or the main widget is destroyed. sys.exitmethod to ensure a clean exit. The environment will be told how the application ends.

PyQt6 tooltip

We can create a bubble tip for the program.

# file: tooltip.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This example shows a tooltip on
a window and a button.

Author: Jan Bodnar
Website: zetcode.com
"""

import sys
from PyQt6.QtWidgets import (QWidget, QToolTip,
    QPushButton, QApplication)
from PyQt6.QtGui import QFont


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        self.setToolTip('This is a <b>QWidget</b> widget')

        btn = QPushButton('Button', self)
        btn.setToolTip('This is a <b>QPushButton</b> widget')
        btn.resize(btn.sizeHint())
        btn.move(50, 50)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Tooltips')
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

In this example, we create a balloon tooltip for two widgets.

QToolTip.setFont(QFont('SansSerif', 10))

This static method sets the font for the bubble tooltip, here the 10pt SansSerif font is used.

self.setToolTip('This is a <b>QWidget</b> widget')

Call setTooltipthe method to create a bubble prompt box, which can use rich text content.

btn = QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')

Added a button widget to the bubble tooltip.

btn.resize(btn.sizeHint())
btn.move(50, 50)

sizeHintThe method is to give the button a size suggested by the system, and then use movethe method to move the button's position.

PyQt6 exit button

The obvious way to close a window is to click the x mark on the title bar. In the next example, we'll show how to programmatically close a window. We will briefly introduce signals and slots.

In this example, QPushButtonthe component is used to accomplish this function.

QPushButton(string text, QWidget parent = None)

The parameter textis the text that will be displayed on the button. parentis the widget where we place the button. In our example, it will be one QWidget. The app's widgets form a hierarchy, and in this hierarchy, most widgets have a parent. The parent of widgets without a parent is the top-level window.

# file: quit_button.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This program creates a quit
button. When we press the button,
the application terminates.

Author: Jan Bodnar
Website: zetcode.com
"""

import sys
from PyQt6.QtWidgets import QWidget, QPushButton, QApplication

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        qbtn = QPushButton('Quit', self)
        qbtn.clicked.connect(QApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Quit button')
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

This example creates an exit button, click this button to exit the program.

qbtn = QPushButton('Quit', self)

We create a button, which is QPushButtonan instance of the class. The first parameter of the constructor is the button's label. The second parameter is the parent widget. The parent widget is Examplethe widget it inherits from QWidget.

qbtn.clicked.connect(QApplication.instance().quit)

The event processing system of PyQt6 is composed of signal and slot mechanism. Clicking the button (event) will send a click signal. Event processing slots can be Qt's own slots or ordinary Python functions

QApplication.instanceThe object obtained using QCoreApplicationcontains the main event loop -- it handles and dispatches all events. The clicked signal is connected to the exit method that terminates the application. Communication is done between two objects: a sender and a receiver. The sender is the button and the receiver is the application object.

PyQt6 popup

By default, if we click the x button on the title bar, QWidgetit will be closed. Sometimes we want to modify this default behavior. For example, if a file is opened in an editor and some content is modified, we need to display a message box to confirm the action of exiting the program.

# file: messagebox.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This program shows a confirmation
message box when we click on the close
button of the application window.

Author: Jan Bodnar
Website: zetcode.com
"""

import sys
from PyQt6.QtWidgets import QWidget, QMessageBox, QApplication


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.setGeometry(300, 300, 350, 200)
        self.setWindowTitle('Message box')
        self.show()

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Message',
                    "Are you sure to quit?", QMessageBox.StandardButton.Yes |
                    QMessageBox.StandardButton.No, QMessageBox.StandardButton.No)

        if reply == QMessageBox.StandardButton.Yes:

            event.accept()
        else:

            event.ignore()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

The close QWidgetoperation generates QCloseEventa event. Reimplement closeEventevent handling to replace the widget's default behavior.

reply = QMessageBox.question(self, 'Message',
                             "Are you sure to quit?", QMessageBox.Yes |
                             QMessageBox.No, QMessageBox.No)

Here a message box with two buttons is created: Yes and No. The first parameter is the title bar, the second parameter is the message text displayed by the dialog box, the third parameter is the combination of buttons in the dialog box, and the last parameter is the button that is selected by default. The return value is stored in a variable reply.

if reply == QtGui.QMessageBox.Yes:
    event.accept()
else:
    event.ignore()

Judging the return value, if the Yes button is clicked, the widget is closed and the application is terminated, otherwise we ignore the close event.

PyQt6 window centered

The following script will display a centered window on the screen.

# file: center.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This program centers a window
on the screen.

Author: Jan Bodnar
Website: zetcode.com
"""

import sys
from PyQt6.QtWidgets import QWidget, QApplication


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.resize(350, 250)
        self.center()

        self.setWindowTitle('Center')
        self.show()

    def center(self):

        qr = self.frameGeometry()
        cp = self.screen().availableGeometry().center()

        qr.moveCenter(cp)
        self.move(qr.topLeft())


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

QScreenClass can query screen properties.

self.center()

Use the custom centermethod to center the window.

qr = self.frameGeometry()

This results in a rectangular window where all types of windows can be placed.

cp = self.screen().availableGeometry().center()

Calculate the resolution from the screen properties, and then calculate the center point position.

qr.moveCenter(cp)

We already know the width and height of the rectangular window, we only need to place the center point of the rectangular window to the center point of the screen window. This does not modify the size of the rectangular window.

self.move(qr.topLeft())

Move the coordinates of the upper left point of the application window to the upper left of the rectangular window, so that it can be displayed in the center.

In this tutorial, we created a simple PyQt6 application.

Guess you like

Origin blog.csdn.net/zy_dreamer/article/details/132701137