PyQT basic function introduction, Hello World

Hello World

This chapter learns the basic functions of Qt

Example 1, simple window

This simple little example shows a small window. But we can do many things on this small window, change size, maximize, minimize, etc., which requires a lot of code to achieve. This is very common in many applications, there is no need to rewrite this part of the code every time, Qt already provides these functions. PyQt5 is a collection of high-level tools, which can save hundreds of lines of code compared to using low-level tools.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

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

author: Jan Bodnar
website: zetcode.com 
Last edited: August 2017
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget


if __name__ == '__main__':

    app = QApplication(sys.argv)

    w = QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec_())

Running the above code will display a small window.

import sys
from PyQt5.QtWidgets import QApplication, QWidget

The PyQt5.QtWidgets module is introduced here, which contains basic components.

app = QApplication(sys.argv)

Every PyQt5 application must create an application object. sys.argv is a list of command-line arguments. Python can run in the shell, this parameter provides the function of controlling the script.

w = QWidget()

The QWidge control is a basic control of the user interface, which provides basic application constructors. By default, constructors are parentless, and constructors without parents are called windows.

w.resize(250, 150)

resize()The method can change the size of the control, which means that the window is 250px wide and 150px high.

w.move(300, 300)

move()Is the method to modify the position of the control. It places the control at (300, 300) screen coordinates. Note: The origin of the screen coordinate system is the upper left corner of the screen.

w.setWindowTitle('Simple')

We added a title to this window, and the title is displayed in the title bar (although this seems to be a nonsense, but there are various columns behind it, you should pay attention to it, if there are too many, it will be confused).

w.show()

show()Allows controls to be displayed on the desktop. Widgets are created in memory before they can be displayed on the display.

sys.exit(app.exec_())

Finally, we enter the main loop of the application, and the event handlers start working at this time. The main loop receives events from the window and dispatches the events to the application controls. exit()The main loop ends when a method is called or when the main control is destroyed directly. sys.exit()method to ensure that the main loop exits safely. The external environment receives information about how the main control ends.

exec_()The reason why there is an underscore is because execit is a Python keyword.

Example 2, with window icon

The window icon is usually displayed in the upper left corner of the window, on the far left of the title bar. The following example is how to create such a window with PyQt5.

In some circumstances, the icons do not appear. If you encounter this problem, see my answer on Stackoverfolw

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

This example shows an icon
in the titlebar of the window.

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon


class Example(QWidget):

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

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('web.png'))        

        self.show()


if __name__ == '__main__':

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

The previous example used procedural programming . Python also supports object-oriented programming:

class Example(QWidget):

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

The three most important parts of object-oriented programming are classes, data, and methods. We create a call to a class that this class inherits from QWidget. This means that we call two constructors, one for the class itself and one inherited by the class. super()The constructor method returns the parent's object. __init__()method is a method of the constructor.

self.initUI()

Use initUI()method to create a GUI.

# 自己准备一个web.png
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))

The above three methods are all inherited from the QWidgetclass. setGeometry()Has two functions: put the window on the screen and set the window size. The parameters represent the x, y of the screen coordinates and the width and height of the window size, respectively. That is to say, this method is a combination of resize()and move(). The last method is to add icons. First create a QIcon object, and then accept a path as a parameter to display the icon.

if __name__ == '__main__':

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

The application and example objects are created and the main loop begins.

Example 3, prompt box

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

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

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, 
    QPushButton, QApplication)
from PyQt5.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()


if __name__ == '__main__':

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

In this example, we create a tooltip for the application.

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

setFont()This static method sets the font of the tooltip, we use a 10px SansSerif font.

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

The call to setToolTip()create a tooltip can use content in rich text format.

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

Create a button and add a tooltip to the button.

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

Adjust the size of the button and make the button appear on the screen. sizeHint()The method provides a default button size.

Example 4, close the window

The most intuitive way to close a window is to click the cross in the title bar. In this example, we show how to close a window with a program. Here we will come into contact with a little knowledge of signals (signal) and slots (groove).

This example uses the QPushButton component class.

QPushButton(string text, QWidget parent = None)

textThe parameter is the name of the button you want to display, and parentthe parameter is the component to put on the button, in our case, this parameter is QWidget. The components in the application are layer by layer (inherited?), in this layer, most of the components have their own parents, and the components without parents are the top-level windows.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

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

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication


class Example(QWidget):

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

        self.initUI()


    def initUI(self):               

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

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


if __name__ == '__main__':

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

Here a button is created that exits the window when clicked.

from PyQt5.QtCore import QCoreApplication

Programs need QtCoreobjects.

qbtn = QPushButton('Quit', self)

Create a QPushButtonbutton that inherits from. The first parameter is the text of the button, and the second parameter is the parent component of the button. In this example, the parent component is the class we created and inherited QWidgetfrom Example.

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

The event delivery system is in the signals and slots mechanism built into PyQt5. After the button is clicked, the signal is caught and given the desired response. QCoreApplicationThe main loop that contains events, which adds and removes all events, instance()creates an instance of it. QCoreApplicationwas QApplicationcreated in . The click event is bound to the quit function that terminates the process and exits the application. Communication is established between the sender and the receiver, the sender is the button, and the receiver is the application object.

Example 5, message box

By default, when we click the × button in the title bar, QWidget will be closed. But sometimes, we modify the default behavior. For example, if we opened a text editor and made some changes, we would like to ask the user to confirm the operation when the close button.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 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 
Last edited: August 2017
"""

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


class Example(QWidget):

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

        self.initUI()


    def initUI(self):               

        self.setGeometry(300, 300, 250, 150)        
        self.setWindowTitle('Message box')    
        self.show()


    def closeEvent(self, event):

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

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


if __name__ == '__main__':

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

If the QWidget is closed, a QCloseEvent will be generated and passed into the event parameter of the closeEvent function. To change the default behavior of a control is to replace the default event handling.

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

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

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

The return value is judged here. If the Yes button is clicked, we will close the component and application, otherwise, we will ignore the close event.

Example 6, centering the window

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

This program centers a window 
on the screen. 

Author: Jan Bodnar
Website: zetcode.com 
Last edited: August 2017
"""

import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication


class Example(QWidget):

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

        self.initUI()


    def initUI(self):               

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

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


    def center(self):

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == '__main__':

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

QtGui.QDesktopWidgetProvides information about the user's desktop, including the size of the screen.

self.center()

This method is to call the method we wrote below to realize the centering of the dialog box.

qr = self.frameGeometry()

Get the frame where the main window is located.

cp = QDesktopWidget().availableGeometry().center()

Get the resolution of the display, and then get the position of the middle point of the screen.

qr.moveCenter(cp)

Then place the center point of the main window frame at the center of the screen.

self.move(qr.topLeft())

Then use the move function to move the upper left corner of the main window to the upper left corner of its frame, thus centering the window.

Guess you like

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