《开始使用PyQT》 第01章 PyQT入门 04 创建第一个桌面应用
A GUI application generally consists of a main window and possibly one or more dialog boxes. The main window is where the user will spend most of their time when using your application and can consist of a menu bar, a status bar, and other widgets. Dialog boxes typically are made up of text, maybe one or more widgets for collecting information, and buttons. They appear to the user when necessary to communicate information and prompt them for input. An alert window that pops up asking you if you want to save changes to your document is an example of a dialog. Dialog boxes will be covered further in Chapter 3.
图形用户界面应用程序一般由一个主窗口和一个或多个对话框组成。主窗口是用户使用应用程序时花费最多时间的地方,可以由菜单栏、状态栏和其他部件组成。对话框通常由文本、一个或多个用于收集信息的部件以及按钮组成。必要时,对话框会出现在用户面前,以传递信息并提示用户输入。对话框的一个例子就是弹出一个提示窗口,询问你是否要保存对文档的修改。对话框将在第 3 章中进一步介绍。
For your first project, seen in Figure 1-1, we’ll consider
对于图 1-1 所示的第一个项目,我们将考虑
This application will serve as the foundation for all other programs found in this book.
此应用程序将作为本书中所有其他程序的基础。
The code found in Listing 1-1 is all you need to create a window in PyQt6. Examples throughout this book will take advantage of object-oriented programming (OOP), a programming paradigm that focuses on using classes to create instances of those classes, or objects, with their own properties and behaviors and modeling the relationships between other objects.
清单 1-1 中的代码就是在 PyQt6 中创建一个窗口所需的全部内容。本书中的示例将利用面向对象编程 (OOP) 的优势,OOP 是一种编程范式,其重点是使用类来创建这些类的实例或对象,这些实例或对象具有自己的属性和行为,并对其他对象之间的关系进行建模。
import sys
from PyQt6.QtWidgets import QApplication, QWidget
class EmptyWindow(QWidget):
def __init__(self):
super().__init__()
self.initializeUI()
def initializeUI(self):
# 设置坐标
self.setGeometry(200, 100, 400, 300)
# 设置窗口标题
self.setWindowTitle("RestClient")
# 显示窗口
self.show()
if __name__ == '__main__':
# 创建应用
app = QApplication(sys.argv)
# 创建空窗口
window = EmptyWindow()
# 启动
sys.exit(app.exec())
Your initial window should look similar to the one in Figure 1-1 depending upon your operating system.
根据操作系统的不同,初始窗口应与图 1-1 中的窗口相似。
Walking through the code, we first start by importing the sys and PyQt6 modules that we need to create a window. The sys module can be used in PyQt to pass command line arguments to our applications and to close them.
浏览代码时,我们首先导入创建窗口所需的 sys 和 PyQt6 模块。在 PyQt 中,sys 模块可用于向我们的应用程序传递命令行参数并关闭它们。
The QtWidgets module provides the widget classes that you will need to create desktop-style GUIs. From the QtWidgets module, we import two classes: QApplication and QWidget. You only need to create a single instance of the QApplication class, no matter how many windows or dialog boxes exist in an application. QApplication is responsible for managing the application’s main event loop and widget initialization and finalization. The main event loop is where user interactions in the GUI window, such as clicking on a button, are managed. Take a quick look at
QtWidgets 模块提供了创建桌面风格图形用户界面所需的部件类。我们从 QtWidgets 模块导入两个类: QApplication 和 QWidget。无论应用程序中有多少窗口或对话框,您只需创建一个 QApplication 类实例。QApplication 负责管理应用程序的主事件循环以及部件的初始化和最终确定。主事件循环是管理 GUI 窗口中用户交互(如点击按钮)的地方。快速查看
app = QApplication(sys.argv)
QApplication takes as an argument sys.argv. You can also pass in an empty list if you know that your program will not be taking any command line arguments using
QApplication 将 sys.argv 作为参数。如果您知道您的程序不会使用任何命令行参数,也可以使用
app = QApplication([])
Tip always create your GUi’s QApplication object before any other object belonging to the GUi, including the main window. this concept is demonstrated in Listing 1-2.
提示 始终先创建 GUi 的 QApplication 对象,然后再创建属于 GUi 的任何其他对象,包括主窗口。清单 1-2 演示了这一概念。
Next, we create a window object that inherits from the class we created, EmptyWindow. Our class actually inherits from QWidget, which is the base class for which all other user interface objects, such as widgets and windows, are derived.
接下来,我们创建一个窗口对象,它继承自我们创建的类 EmptyWindow。我们的类实际上继承自 QWidget,它是所有其他用户界面对象(如 widget 和窗口)的基类。
Tip when creating windows in pyQt, you will generally create a main class that inherits from either QMainWindow, QWidget, or QDialog. you’ll find out more about each of these classes and when to use them to create windows and dialog boxes in later chapters.
小提示 在 pyQt 中创建窗口时,通常会创建一个继承自 QMainWindow、QWidget 或 QDialog 的主类,您将在后面的章节中了解到更多有关这些类的信息,以及何时使用它们创建窗口和对话框。
We need to call the show() method on the window object to display it to the screen. This is located inside the initializeUI() function in our EmptyWindow class. You can see app.exec() being passed as an argument to sys.exit() in the final line of Listing 1-1. The method exec() starts the application’s event loop and will remain here until you quit the application. The function sys.exit() ensures a clean exit.
我们需要调用窗口对象的 show() 方法将其显示到屏幕上。该方法位于 EmptyWindow 类的 initializeUI() 函数中。在清单 1-1 的最后一行,我们可以看到 app.exec() 作为参数传递给 sys.exit()。方法 exec() 启动了应用程序的事件循环,并将一直保持到退出应用程序为止。函数 sys.exit() 可确保干净利落地退出。
The steps for creating a window are better illustrated in Listing 1-2 using procedural programming, a programming paradigm where the computer follows a set of sequential commands to perform a task.
程序编程是一种编程范式,计算机按照一系列顺序命令执行任务,清单 1-2 使用程序编程更好地说明了创建窗口的步骤。
Listing 1-2. Minimum code needed for creating an empty window in PyQt without OOP
清单 1-2. 不使用 OOP 在 PyQt 中创建空窗口所需的最少代码
import sys
from PyQt6.QtWidgets import QApplication, QWidget
# 创建应用
app = QApplication(sys.argv)
# 创建组件
window = QWidget()
# 显示组件
window.show()
# 退出服务
sys.exit(app.exec())
The next section demonstrates how to use built-in PyQt methods to change the main window’s size and set the window’s title.
下一节将演示如何使用 PyQt 内置方法改变主窗口大小和设置窗口标题。
The EmptyWindow class in Listing 1-1 contains a method, initializeUI(), that creates the window based upon the parameters we specify. The initializeUI() function is reproduced in the following code snippet:
清单 1-1 中的 EmptyWindow 类包含一个方法 initializeUI(),可根据我们指定的参数创建窗口。initializeUI() 函数在以下代码片段中重现:
def initializeUI(self):
# 设置坐标
self.setGeometry(200, 100, 400, 300)
# 设置窗口标题
self.setWindowTitle("RestClient")
# 显示窗口
self.show()
The method setGeometry() defines the location of the window on your computer screen and its dimensions, width and height. So the window we just created is located at x=200, y=100 in the window and has width=400 and height=300. The setWindowTitle() method is used to set the title of the window. Take a moment to modify the geometry values or title text and see how your changes affect the window. You could also comment out the two methods and see how PyQt uses default parameter settings for both the size and window title.
方法 setGeometry() 定义了窗口在电脑屏幕上的位置及其尺寸(宽和高)。因此,我们刚刚创建的窗口在窗口中的位置是 x=200,y=100,宽度=400,高度=300。setWindowTitle() 方法用于设置窗口的标题。请花点时间修改几何值或标题文本,看看您的修改对窗口有何影响。您也可以注释掉这两个方法,看看 PyQt 是如何使用默认参数设置大小和窗口标题的。
We will look at further customization of the window’s layout in Chapter 4 and appearance in Chapter 6.
我们将在第 4 章和第 6 章进一步介绍窗口布局和外观的自定义。