First programs in PyQt5

First programs in PyQt5

In this part of the PyQt5 tutorial we learn some basic functionality. The examples show a tooltip and an icon, close a window, show a message box and center a window on the desktop.
在 PyQt5 教程的这一部分中,我们学习一些基本功能。这些示例显示工具提示和图标、关闭窗口、显示消息框并在桌面上居中显示窗口。

tooltip ['tuːltɪp]:n. 工具提示,提示信息,提示框,提示文本
icon ['aɪkɒn; -k(ə)n]:n. 图标,偶像,肖像,画像,圣像

1. Simple example

This is a simple example showing a small window. Yet we can do a lot with this window. We can resize it, maximise it or minimise it. This requires a lot of coding. Someone already coded this functionality. Because it is repeated in most applications, there is no need to code it over again. PyQt5 is a high level toolkit. If we would code in a lower level toolkit, the following code example could easily have hundreds of lines.
这是一个显示小窗口的简单示例。然而,我们可以用这个窗口做很多事情。我们可以调整它,最大化它或最小化它。这需要大量编码。有人已编码此功能。因为它在大多数应用程序中重复,所以不需要再次编码。PyQt5 是一个高级工具包。如果我们要在较低级别的工具包中编写代码,则以下代码示例可以轻松地拥有数百行。

maximise ['mæksɪmaɪz]:vt. 把...增加到最大限度,尽量增大 (等于 maximize)
minimise ['minimaiz]:vt. 使缩到最小,成极小,求最小值

simple.py

#!/usr/bin/python3
# Character Encoding: UTF-8

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

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_())

The above code example shows a small window on the screen.

import sys
from PyQt5.QtWidgets import QApplication, QWidget

Here we provide the necessary imports. The basic widgets are located in PyQt5.QtWidgets module.

app = QApplication(sys.argv)

Every PyQt5 application must create an application object. The sys.argv parameter is a list of arguments from a command line. Python scripts can be run from the shell. It is a way how we can control the startup of our scripts.

w = QWidget()

The QWidget widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget. The default constructor has no parent. A widget with no parent is called a window.
QWidget 小部件是 PyQt5 中所有用户界面对象的基类。我们为 QWidget 提供默认构造函数。默认构造函数没有父级。没有父项的窗口小部件称为窗口。

w.resize(250, 150)

The resize() method resizes the widget. It is 250px wide and 150px high.

w.move(300, 300)

The move() method moves the widget to a position on the screen at x=300, y=300 coordinates.

w.setWindowTitle('Simple')

We set the title of the window with setWindowTitle(). The title is shown in the titlebar.

w.show()

The show() method displays the widget on the screen. A widget is first created in memory and later shown on the screen.

sys.exit(app.exec_())

Finally, we enter the mainloop of the application. The event handling starts from this point. The mainloop receives events from the window system and dispatches them to the application widgets. The mainloop ends if we call the exit() method or the main widget is destroyed. The sys.exit() method ensures a clean exit. The environment will be informed how the application ended.
最后,我们进入应用程序的主循环。事件处理从这一点开始。mainloop 从窗口系统接收事件并将它们分派给应用程序小部件。如果我们调用 exit() 方法或主窗口小部件被销毁,则 mainloop 结束。sys.exit() 方法确保了一个干净的退出。将通知环境应用程序如何结束。

The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.

在这里插入图片描述
Figure: Simple

2. An application icon

The application icon is a small image which is usually displayed in the top left corner of the titlebar. In the following example we will show how we do it in PyQt5. We will also introduce some new methods.
应用程序图标是一个小图像,通常显示在标题栏的左上角。

Some environments do not display icons in the titlebars. We need to enable them. See my answer on Stackoverflow for a solution, if you are seeing no icons.
某些环境不在标题栏中显示图标。

icon.py

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

"""
ZetCode PyQt5 tutorial
This example shows an icon in the titlebar of the window.
"""

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 was coded in a procedural style. Python programming language supports both procedural and object oriented programming styles. Programming in PyQt5 means programming in OOP.
前面的示例是以程序样式编写的。Python 编程语言支持过程和面向对象的编程风格。PyQt5 中的编程意味着在 OOP 中编程。

procedural [prə'siːdʒərəl]:adj. 程序上的
object-oriented programming,OOP:面向对象编程
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        ...

Three important things in object oriented programming are classes, data, and methods. Here we create a new class called Example. The Example class inherits from the QWidget class. This means that we call two constructors: the first one for the Example class and the second one for the inherited class. The super() method returns the parent object of the Example class and we call its constructor. The __init__() method is a constructor method in Python language.
面向对象编程中的三个重要事项是类、数据和方法。这里我们创建一个名为 Example 的新类。Example 类继承自 QWidget 类。这意味着我们调用两个构造函数:第一个用于 Example 类,第二个用于继承的类。super() 方法返回 Example 类的父对象,我们调用它的构造函数。__init__() 方法是 Python 语言中的构造函数方法。

self.initUI() 

The creation of the GUI is delegated to the initUI() method.

delegate [ˈdɛlɪˌɡeɪt; -ɡɪt; (for v.,) ˈdɛlɪˌɡeɪt]:vt. 委派...为代表 n. 代表
inherit [ɪn'herɪt]:vt. 继承,遗传而得 vi. 成为继承人
constructor [kənˈstrʌktə(r)]:n. 构造函数,构造器,建造者
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png')) 

All three methods have been inherited from the QWidget class. The setGeometry() does two things: it locates the window on the screen and sets it size. The first two parameters are the x and y positions of the window. The third is the width and the fourth is the height of the window. In fact, it combines the resize() and move() methods in one method. The last method sets the application icon. To do this, we have created a QIcon object. The QIcon receives the path to our icon to be displayed.
这三个方法都是从 QWidget 类继承而来的。setGeometry() 做了两件事:它在屏幕上定位窗口并设置它的大小。前两个参数是窗口的 x 和 y 位置。第三个是宽度,第四个是窗口的高度。实际上,它在一个方法中结合了 resize() and move() 方法。最后一个方法设置应用程序图标。为此,我们创建了一个 QIcon 对象。QIcon 接收要显示的图标的路径。

if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())  

The application and example objects are created. The main loop is started.

在这里插入图片描述
Figure: Icon

图标无法显示,尚未找到解决方案。
Xfce Desktop Environment -> xfce4-settings-editor tool -> Settings/Settings Editor -> xfwm4 -> show_app_icon
在这里插入图片描述

3. Showing a tooltip

We can provide a balloon help for any of our widgets.

balloon [bə'luːn]:vi. 激增,膨胀如气球 n. 气球 vt. 使像气球般鼓起,使激增 adj. 像气球般鼓起的
tooltip ['tuːltɪp]:n. 工具提示,提示信息,提示框,提示文本

tooltip.py

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

"""
ZetCode PyQt5 tutorial
This example shows a tooltip on a window and a button.
"""

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 show a tooltip for two PyQt5 widgets.

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

This static method sets a font used to render tooltips. We use a 10pt SansSerif font.

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

To create a tooltip, we call the setTooltip() method. We can use rich text formatting.

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

We create a push button widget and set a tooltip for it.

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

The button is being resized and moved on the window. The sizeHint() method gives a recommended size for the button.

render ['rendə]:vt. 致使,提出,实施,着色,以...回报 vi. 给予补偿 n. 打底,交纳,粉刷

在这里插入图片描述

在这里插入图片描述
Figure: Tooltips

4. Closing a window

The obvious way to close a window is to click on the x mark on the titlebar. In the next example, we show how we can programatically close our window. We will briefly touch signals and slots.

obvious ['ɒbvɪəs]:adj. 明显的,显著的,平淡无奇的
programmable ['prəugræməbl];adj. 可编程的,可设计的
briefly ['briːflɪ]:adv. 短暂地,简略地,暂时地
slot [slɒt]:n. 位置,狭槽,水沟,硬币投币口 vt. 跟踪,开槽于

The following is the constructor of a QPushButton widget that we use in our example.

QPushButton(string text, QWidget parent = None)

The text parameter is a text that will be displayed on the button. The parent is a widget on which we place our button. In our case it will be a QWidget. Widgets of an application form a hierarchy. In this hierarchy, most widgets have their parents. Widgets without parents are toplevel windows.
text 参数是将显示在按钮上的文本。父级是我们放置按钮的小部件。在我们的例子中,它将是一个 QWidget。应用程序的小部件形成层次结构。在此层次结构中,大多数小部件都有其父级。没有父母的小工具是顶窗。

constructor [kənˈstrʌktə(r)];n. 构造函数,构造器,建造者
hierarchy ['haɪərɑːkɪ];n. 层级,等级制度
toplevel:adj. 顶层的,最高级的

quitbutton.py

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

"""
ZetCode PyQt5 tutorial

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

import sys
from PyQt5.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, 250, 150)
        self.setWindowTitle('Quit button')
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

In this example, we create a quit button. Upon clicking on the button, the application terminates.

qbtn = QPushButton('Quit', self)

We create a push button. The button is an instance of the QPushButton class. The first parameter of the constructor is the label of the button. The second parameter is the parent widget. The parent widget is the Example widget, which is a QWidget by inheritance.
我们创建一个按钮。该按钮是 QPushButton 类的一个实例。构造函数的第一个参数是按钮的标签。第二个参数是父窗口小部件。父窗口小部件是示例窗口小部件,它是继承的 QWidget

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

The event processing system in PyQt5 is built with the signal & slot mechanism. If we click on the button, the signal clicked is emitted. The slot can be a Qt slot or any Python callable.
PyQt5 中的事件处理系统是使用信号和插槽机制构建的。如果我们点击按钮,则会发出点击的信号。插槽可以是 Qt 插槽或任何 Python 可调用。

QCoreApplication, which is retrieved with QApplication.instance(), contains the main event loop - it processes and dispatches all events. The clicked signal is connected to the quit() method which terminates the application. The communication is done between two objects: the sender and the receiver. The sender is the push button, the receiver is the application object.
QCoreApplication is retrieved with QApplication.instance(),QCoreApplication 包含主事件循环 - 它处理和分派所有事件。单击的信号连接到 quit() 方法,该方法终止应用程序。通信在两个对象之间完成:发送方和接收方。发送者是按钮,接收者是应用程序对象。

inheritance [ɪn'herɪt(ə)ns]:n. 继承,遗传,遗产
mechanism ['mek(ə)nɪz(ə)m]:n. 机制,原理,途径,进程,机械装置,技巧
emit [ɪ'mɪt]:vt. 发出,放射,发行,发表
retrieve [rɪ'triːv]:vt. 检索,恢复,重新得到 vi. 找回猎物 n. 检索,恢复,取回
dispatch [dɪˈspætʃ]:n. 派遣,急件 vt. 派遣,分派

在这里插入图片描述
Figure: Quit button

5. Message Box

By default, if we click on the x button on the titlebar, the QWidget is closed. Sometimes we want to modify this default behaviour. For example, if we have a file opened in an editor to which we did some changes. We show a message box to confirm the action.

message box:消息框,信息框
modify ['mɒdɪfaɪ]:vt. 修改,修饰,更改 vi. 修改
confirm [kən'fɜːm]:vt. 确认,确定,证实,批准,使巩固

messagebox.py

#!/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.
"""

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 we close a QWidget, the QCloseEvent is generated. To modify the widget behaviour we need to reimplement the closeEvent() event handler.

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

We show a message box with two buttons: Yes and No. The first string appears on the titlebar. The second string is the message text displayed by the dialog. The third argument specifies the combination of buttons appearing in the dialog. The last parameter is the default button. It is the button which has initially the keyboard focus. The return value is stored in the reply variable.
我们显示一个带有两个按钮的消息框:Yes and No。第一个字符串出现在标题栏上。第二个字符串是对话框显示的消息文本。第三个参数指定出现在对话框中的按钮组合。最后一个参数是默认按钮。它是最初具有键盘焦点的按钮。返回值存储在 reply 变量中。

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

Here we test the return value. If we click the Yes button, we accept the event which leads to the closure of the widget and to the termination of the application. Otherwise we ignore the close event.

handler ['hændlə]:n. 处理者,管理者,拳击教练,训练者,句柄
closure ['kləʊʒə]:n. 关闭,终止,结束 vt. 使终止

在这里插入图片描述

在这里插入图片描述
Figure: Message box

6. Centering window on the screen

The following script shows how we can center a window on the desktop screen.

center.py

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

"""
ZetCode PyQt5 tutorial
This program centers a window on the screen.
"""

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_())

The QDesktopWidget class provides information about the user’s desktop, including the screen size.

self.center()

The code that will center the window is placed in the custom center() method.

qr = self.frameGeometry()

We get a rectangle specifying the geometry of the main window. This includes any window frame.
我们得到一个矩形,指定主窗口的几何形状。这包括任何窗框。

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

We figure out the screen resolution of our monitor. And from this resolution, we get the center point.
我们弄清楚我们的显示器的屏幕分辨率。从这个屏幕分辨率,我们得到了中心点。

qr.moveCenter(cp)

Our rectangle has already its width and height. Now we set the center of the rectangle to the center of the screen. The rectangle’s size is unchanged.

self.move(qr.topLeft())

We move the top-left point of the application window to the top-left point of the qr rectangle, thus centering the window on our screen.

在这里插入图片描述

custom ['kʌstəm]:n. 习惯,惯例,风俗,海关,关税,经常光顾,顾客 adj. 定做的,定制的

In this part of the PyQt5 tutorial, we have created simple code examples in PyQt5.

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读