Pyqt 简明教程
PyQt - Introduction
PyQt 是一个 GUI 小部件工具包。它是 Qt 的 Python 接口,这是功能最强大的跨平台 GUI 库之一。PyQt 由 RiverBank Computing Ltd. 开发。可以从其官方网站 riverbankcomputing.com 下载最新版本的 PyQt
PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com
PyQt API 是一套包含大量类和函数的模块。其中 QtCore 模块包含用于处理文件、目录等的非 GUI 功能, QtGui 模块包含所有图形控制。此外,还有用于处理 XML (QtXml) 、SVG (QtSvg) 和 SQL (QtSql) 等的模块。
PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc., QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc.
Supporting Environments
PyQt 与所有流行的操作系统兼容,包括 Windows、Linux 和 Mac OS。它具有双重许可证,既可以获得 GPL 也可以通过商业许可证使用。
PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS. It is dual licensed, available under GPL as well as commercial license.
Windows
您可以从上面与 Python 版本(2.7 或 3.4)和硬件架构(32 位或 64 位)相对应的下载链接下载并安装合适的安装程序。请注意,有两种可用的 PyQt 版本,即 PyQt 4.8 和 PyQt 5.5 。
You can download and install an appropriate installer from the above download link corresponding to Python version (2.7 or 3.4) and hardware architecture (32 bit or 64 bit). Note that there are two versions of PyQt that are available namely, PyQt 4.8 and PyQt 5.5.
PyQt4 适用于 Python 2 和 Python 3,而 PyQt5 只能与 Python 3.* 结合使用。
While PyQt4 is available for Python 2 as well as Python 3, PyQt5 can be used along with Python 3.* only.
PyQt4 Windows Binaries
PyQt4 Windows Binaries
PyQt4-4.11.4-gpl-Py3.4-Qt4.8.7-x64.exe |
Windows 64 bit installer |
PyQt4-4.11.4-gpl-Py3.4-Qt4.8.7-x32.exe |
Windows 32 bit installer |
PyQt4-4.11.4-gpl-Py3.4-Qt5.5.0-x64.exe |
Windows 64 bit installer |
PyQt4-4.11.4-gpl-Py3.4-Qt5.5.0-x32.exe |
Windows 32 bit installer |
PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x64.exe |
Windows 64 bit installer |
PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.exe |
Windows 32 bit installer |
PyQt5 Windows Binaries
PyQt5 Windows Binaries
PyQt5-5.5-gpl-Py3.4-Qt5.5.0-x64.exe |
Windows 64 bit installer |
PyQt5-5.5-gpl-Py3.4-Qt5.5.0-x32.exe |
Windows 32 bit installer |
Linux
对于 Ubuntu 或其他 debian Linux 发行版,使用以下命令安装 PyQt −
For Ubuntu or any other debian Linux distribution, use the following command to install PyQt −
sudo apt-get install python-qt4
or
sudo apt-get install pyqt5-dev-tools
您还可以在“下载”页面上获得的源代码中进行构建。
You can also build from the source code available on the ‘download’ page.
PyQt-x11-gpl-4.11.4.tar.gz |
Linux, UNIX source for PyQt4 |
PyQt-gpl-5.5.tar.gz |
Linux, UNIX, MacOS/X source for PyQt5 |
Mac OS
PyQtX 项目 ( http://sourceforge.net/projects/pyqtx/ ) 托管用于 Mac 的 PyQt 二进制文件。使用 Homebrew 安装程序,按以下命令执行操作 −
PyQtX project (http://sourceforge.net/projects/pyqtx/) hosts binaries of PyQt for Mac. Use Homebrew installer as per the following command −
brew install pyqt
PyQt - Hello World
使用 PyQt 创建简单的 GUI 应用程序涉及以下步骤 −
Creating a simple GUI application using PyQt involves the following steps −
-
Import QtGui module.
-
Create an application object.
-
A QWidget object creates top level window. Add QLabel object in it.
-
Set the caption of label as “hello world”.
-
Define the size and position of window by setGeometry() method.
-
Enter the mainloop of application by app.exec_() method.
import sys
from PyQt4 import QtGui
def window():
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
b = QtGui.QLabel(w)
b.setText("Hello World!")
w.setGeometry(100,100,200,50)
b.move(50,20)
w.setWindowTitle(“PyQt”)
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - Major Classes
PyQt API 是大量类和方法的集合。这些类在 20 多个模块中定义。以下是一些常用模块 −
PyQt API is a large collection of classes and methods. These classes are defined in more than 20 modules. Following are some of the frequently used modules −
Sr.No. |
Modules & Description |
1 |
QtCore Core non-GUI classes used by other modules |
2 |
QtGui Graphical user interface components |
3 |
QtMultimedia Classes for low-level multimedia programming |
4 |
QtNetwork Classes for network programming |
5 |
QtOpenGL OpenGL support classes |
6 |
QtScript Classes for evaluating Qt Scripts |
7 |
QtSql Classes for database integration using SQL |
8 |
QtSvg Classes for displaying the contents of SVG files |
9 |
QtWebKit Classes for rendering and editing HTML |
10 |
QtXml Classes for handling XML |
11 |
QtAssistant Support for online help |
12 |
QtDesigner Classes for extending Qt Designer |
PyQt API 包含 400 多个类。 QObject 类位于类层次结构的顶部。它是所有 Qt 对象的基类。此外, QPaintDevice 类是所有可绘制对象的基类。
PyQt API contains more than 400 classes. The QObject class is at the top of class hierarchy. It is the base class of all Qt objects. Additionally, QPaintDevice class is the base class for all objects that can be painted.
QApplication 类管理 GUI 应用程序的主设置和控制流。它包含主事件循环,在该循环中处理和分派由窗口元素和其他源生成的事件。它还处理系统范围和应用程序范围的设置。
QApplication class manages the main settings and control flow of a GUI application. It contains main event loop inside which events generated by window elements and other sources are processed and dispatched. It also handles system-wide and application-wide settings.
QWidget 类派生自 QObject 和 QPaintDevice 类,是所有用户界面对象的基类。 QDialog 和 QFrame 类也派生自 QWidget 类。它们有自己的子类系统。
QWidget class, derived from QObject and QPaintDevice classes is the base class for all user interface objects. QDialog and QFrame classes are also derived from QWidget class. They have their own sub-class system.
以下图表描绘了它们在层次结构中的某些重要类。
Following diagrams depict some important classes in their hierarchy.
以下是常用的部件精简列表 −
Here is a select list of frequently used widgets −
以下是常用的部件。
Given below are the commonly used Widgets.
Sr.No. |
Widgets & Description |
1 |
QLabel Used to display text or image |
2 |
QLineEdit Allows the user to enter one line of text |
3 |
QTextEdit Allows the user to enter multi-line text |
4 |
QPushButton A command button to invoke action |
5 |
QRadioButton Enables to choose one from multiple options |
6 |
QCheckBox Enables choice of more than one options |
7 |
QSpinBox Enables to increase/decrease an integer value |
8 |
QScrollBar Enables to access contents of a widget beyond display aperture |
9 |
QSlider Enables to change the bound value linearly. |
10 |
QComboBox Provides a dropdown list of items to select from |
11 |
QMenuBar Horizontal bar holding QMenu objects |
12 |
QStatusBar Usually at bottom of QMainWindow, provides status information. |
13 |
QToolBar Usually at top of QMainWindow or floating. Contains action buttons |
14 |
QListView Provides a selectable list of items in ListMode or IconMode |
15 |
QPixmap Off-screen image representation for display on QLabel or QPushButton object |
16 |
QDialog Modal or modeless window which can return information to parent window |
典型的基于 GUI 的应用程序的顶级窗口由 QMainWindow 小部件对象创建。上面列出的一些小部件在这个主窗口中占据各自指定的位置,而其他一些小部件则使用各种布局管理器放置在中央小部件区域中。
A typical GUI based application’s top level window is created by QMainWindow widget object. Some widgets as listed above take their appointed place in this main window, while others are placed in the central widget area using various layout managers.
下图显示了 QMainWindow 框架 -
The following diagram shows the QMainWindow framework −
PyQt - Using Qt Designer
PyQt 安装程序附带了一个名为 Qt Designer 的 GUI 构建工具。利用其简单的拖放界面,可以快速构建 GUI 界面而无需编写代码。然而,它不是像 Visual Studio 这样的 IDE。因此,Qt Designer 没有调试和构建应用程序的功能。
The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application.
使用 Qt Designer 创建 GUI 界面始于为应用程序选择一个顶级窗口。
Creation of a GUI interface using Qt Designer starts with choosing a top level window for the application.
然后,您可以从左侧窗格中的小部件框中拖放所需の小部件。您还可以将值分配给布置在窗体上的小部件的属性。
You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form.
设计好的窗体将另存为 demo.ui。此 ui 文件包含设计中对应小部件及其属性的 XML 表示。使用 pyuic4 命令行实用程序将此设计转换为 Python 等效项。此实用程序是 uic 模块的包装器。pyuic4 的用法如下 −
The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic4 command line utility. This utility is a wrapper for uic module. The usage of pyuic4 is as follows −
pyuic4 –x demo.ui –o demo.py
在上文中,-x 开关向生成的 XML 中添加少量附加代码,以便使其成为一个可独立自执行的应用程序。
In the above command, -x switch adds a small amount of additional code to the generated XML so that it becomes a self-executable standalone application.
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
执行结果 Python 脚本以显示以下对话框 −
The resultant python script is executed to show the following dialog box −
用户可以在输入字段中输入数据,但单击“添加”按钮不会生成任何操作,因为它不与任何函数关联。对用户生成的响应作出反应被称为 event handling 。
The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling.
PyQt - Signals & Slots
与按顺序执行的控制台模式应用程序不同,基于 GUI 的应用程序是事件驱动的。函数或方法会执行响应用户的操作,例如单击按钮、从集合中选择一个项目,或鼠标单击等,称为 events 。
Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking on a button, selecting an item from a collection or a mouse click etc., called events.
用于构建 GUI 界面的小组件充当此类事件的源。PyQt 中的每个小组件(派生自 QObject 类)都设计为针对一个或多个事件发出“ signal ”。信号本身不执行任何操作。相反,信号被“连接”到“ slot ”。槽可以是任何 callable Python function 。
Widgets used to build the GUI interface act as the source of such events. Each PyQt widget, which is derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable Python function.
在 PyQt 中,信号与槽之间的连接可以通过多种方式实现。以下是最常用的技术 −
In PyQt, connection between a signal and a slot can be achieved in different ways. Following are most commonly used techniques −
QtCore.QObject.connect(widget, QtCore.SIGNAL(‘signalname’), slot_function)
在小组件发出信号时调用 slot_function 的更便捷的方式如下 −
A more convenient way to call a slot_function, when a signal is emitted by a widget is as follows −
widget.signal.connect(slot_function)
假设在单击按钮时调用某个函数。此处,clicked 信号应连接到可调用函数。可以通过以下两种技术中的任何一种来实现:
Suppose if a function is to be called when a button is clicked. Here, the clicked signal is to be connected to a callable function. It can be achieved in any of the following two techniques −
QtCore.QObject.connect(button, QtCore.SIGNAL(“clicked()”), slot_function)
或
or
button.clicked.connect(slot_function)
Example
在以下示例中,两个 QPushButton 对象(b1 和 b2)添加到 QDialog 窗口中。我们希望分别在单击 b1 和 b2 时调用函数 b1_clicked() 和 b2_clicked()。
In the following example, two QPushButton objects (b1 and b2) are added in QDialog window. We want to call functions b1_clicked() and b2_clicked() on clicking b1 and b2 respectively.
当单击 b1 时,clicked() 信号连接到 b1_clicked() 函数
When b1 is clicked, the clicked() signal is connected to b1_clicked() function
b1.clicked.connect(b1_clicked())
当单击 b2 时,clicked() 信号连接到 b2_clicked() 函数
When b2 is clicked, the clicked() signal is connected to b2_clicked() function
QObject.connect(b2, SIGNAL("clicked()"), b2_clicked)
Example
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
app = QApplication(sys.argv)
win = QDialog()
b1 = QPushButton(win)
b1.setText("Button1")
b1.move(50,20)
b1.clicked.connect(b1_clicked)
b2 = QPushButton(win)
b2.setText("Button2")
b2.move(50,50)
QObject.connect(b2,SIGNAL("clicked()"),b2_clicked)
win.setGeometry(100,100,200,100)
win.setWindowTitle("PyQt")
win.show()
sys.exit(app.exec_())
def b1_clicked():
print "Button 1 clicked"
def b2_clicked():
print "Button 2 clicked"
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - Layout Management
可以通过指定 GUI 小组件绝对坐标来将其放置在容器窗口中,坐标以像素为单位进行测量。坐标相对于 setGeometry() 方法定义的窗口维度。
A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by setGeometry() method.
setGeometry() syntax
QWidget.setGeometry(xpos, ypos, width, height)
在下面的代码片段中,300 乘以 200 像素维度的主窗口显示在监视器上的位置 (10, 10)。
In the following code snippet, the top level window of 300 by 200 pixels dimensions is displayed at position (10, 10) on the monitor.
import sys
from PyQt4 import QtGui
def window():
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
b = QtGui.QPushButton(w)
b.setText("Hello World!")
b.move(50,20)
w.setGeometry(10,10,300,200)
w.setWindowTitle(“PyQt”)
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
在窗口中添加了一个 PushButton 小组件,并将其放置在距离窗口左上角 50 像素的右侧和 20 像素的下方。
A PushButton widget is added in the window and placed at a position 50 pixels towards right and 20 pixels below the top left position of the window.
然而,这个 Absolute Positioning 不合适,原因如下 -
This Absolute Positioning, however, is not suitable because of following reasons −
-
The position of the widget does not change even if the window is resized.
-
The appearance may not be uniform on different display devices with different resolutions.
-
Modification in the layout is difficult as it may need redesigning the entire form.
PyQt API 提供布局类,可以更优雅地管理容器内小组件的位置。相对于绝对定位,布局管理器的优点是 -
PyQt API provides layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −
-
Widgets inside the window are automatically resized.
-
Ensures uniform appearance on display devices with different resolutions.
-
Adding or removing widget dynamically is possible without having to redesign.
以下是我们将在本章中依次讨论的类列表。
Here is the list of Classes which we will discuss one by one in this chapter.
Sr.No. |
Classes & Description |
1 |
QBoxLayoutQBoxLayout class lines up the widgets vertically or horizontally. Its derived classes are QVBoxLayout (for arranging widgets vertically) and QHBoxLayout (for arranging widgets horizontally). |
2 |
QGridLayoutA GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. |
3 |
QFormLayoutQFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field. |
PyQt - Basic Widgets
以下是我们将在本章中依次讨论的小组件列表。
Here is the list of Widgets which we will discuss one by one in this chapter.
Sr.No |
Widgets & Description |
1 |
QLabelA QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. |
2 |
QLineEditQLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required. |
3 |
QPushButtonIn PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function. |
4 |
QRadioButtonA QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class. |
5 |
QCheckBoxA rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button. |
6 |
QComboBoxA QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item. |
7 |
QSpinBoxA QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right. |
8 |
QSlider Widget & SignalQSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. |
9 |
QMenuBar, QMenu & QActionA horizontal QMenuBar just below the title bar of a QMainWindow object is reserved for displaying QMenu objects. |
10 |
QToolBarA QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets. |
11 |
QInputDialogThis is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter. |
12 |
QFontDialogAnother commonly used dialog, a font selector widget is the visual appearance of QDialog class. Result of this dialog is a Qfont object, which can be consumed by the parent window. |
13 |
QFileDialogThis widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object. |
14 |
QTabIf a form has too many fields to be displayed simultaneously, they can be arranged in different pages placed under each tab of a Tabbed Widget. The QTabWidget provides a tab bar and a page area. |
15 |
QStackedFunctioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area. |
16 |
QSplitterIf a form has too many fields to be displayed simultaneously, they can be arranged in different pages placed under each tab of a Tabbed Widget. The QTabWidget provides a tab bar and a page area. |
17 |
QDockA dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. |
18 |
QStatusBarQMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information. |
19 |
QListQListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable. |
20 |
QScrollBarA scrollbar control enables the user to access parts of the document that is outside the viewable area. It provides visual indicator to the current position. |
21 |
QCalendarQCalendar widget is a useful date picker control. It provides a month-based view. The user can select the date by the use of the mouse or the keyboard, the default being today’s date. |
PyQt - QDialog Class
QDialog 小部件提供顶层窗口,主要用于收集用户的响应。可以将其配置为 Modal (它会阻止其父窗口)或 Modeless (可以绕过该对话框窗口)。
A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed).
PyQt API 具有许多预配置的 Dialog 小部件,例如 InputDialog、FileDialog、FontDialog 等。
PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc.
Example
在以下示例中,Dialog 窗口的 WindowModality 特性决定它是否是模式对话框还是非模式对话框。可以将对话框上的任意一个按钮设置为默认按钮。当用户按下 Escape 键时,通过 QDialog.reject() 方法放弃该对话框。
In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key.
当顶层 QWidget 窗口上的 PushButton 被单击时,会生成一个 Dialog 窗口。Dialog 框的标题栏上没有最小化和最大化控件。
A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar.
用户无法将此对话框窗口置于后台,因为其 WindowModality 已设为 ApplicationModal。
The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal.
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b = QPushButton(w)
b.setText("Hello World!")
b.move(50,50)
b.clicked.connect(showdialog)
w.setWindowTitle("PyQt Dialog demo")
w.show()
sys.exit(app.exec_())
def showdialog():
d = QDialog()
b1 = QPushButton("ok",d)
b1.move(50,50)
d.setWindowTitle("Dialog")
d.setWindowModality(Qt.ApplicationModal)
d.exec_()
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - QMessageBox
QMessageBox 是一个常用的模态对话框,用于显示一些信息消息,还可以让用户通过点击其上的任意一个标准按钮进行响应。每个标准按钮都有一个预定义的标题、一个角色,并返回一个预定义的十六进制数。
QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number.
与 QMessageBox 类相关的重要方法和枚举在下表中给出−
Important methods and enumerations associated with QMessageBox class are given in the following table −
Sr.No. |
Methods & Description |
1 |
setIcon() Displays predefined icon corresponding to severity of the message Question Information Warning Critical |
2 |
setText() Sets the text of the main message to be displayed |
3 |
setInformativeText() Displays additional information |
4 |
setDetailText() Dialog shows a Details button. This text appears on clicking it |
5 |
setTitle() Displays the custom title of dialog |
6 |
setStandardButtons() List of standard buttons to be displayed. Each button is associated with QMessageBox.Ok 0x00000400 QMessageBox.Open 0x00002000 QMessageBox.Save 0x00000800 QMessageBox.Cancel 0x00400000 QMessageBox.Close 0x00200000 QMessageBox.Yes 0x00004000 QMessageBox.No 0x00010000 QMessageBox.Abort 0x00040000 QMessageBox.Retry 0x00080000 QMessageBox.Ignore 0x00100000 |
7 |
setDefaultButton() Sets the button as default. It emits the clicked signal if Enter is pressed |
8 |
setEscapeButton() Sets the button to be treated as clicked if the escape key is pressed |
Example
在以下示例中,点击顶层窗口上的按钮信号,连接的函数将显示消息框对话框。
In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog.
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")
setStandardButton() 函数将显示所需的按钮。
setStandardButton() function displays desired buttons.
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
buttonClicked() 信号连接到槽函数,该函数标识信号源的标题。
buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal.
msg.buttonClicked.connect(msgbtn)
示例的完整代码如下 −
The complete code for the example is as follows −
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b = QPushButton(w)
b.setText("Show message!")
b.move(50,50)
b.clicked.connect(showdialog)
w.setWindowTitle("PyQt Dialog demo")
w.show()
sys.exit(app.exec_())
def showdialog():
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msg.buttonClicked.connect(msgbtn)
retval = msg.exec_()
print "value of pressed message box button:", retval
def msgbtn(i):
print "Button pressed is:",i.text()
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - Multiple Document Interface
典型的 GUI 应用程序可能有多个窗口。标签式和小部件可随时激活一个这样的窗口。但是,很多时候此方法可能没有用,因为其他窗口的视图被隐藏了。
A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden.
同时显示多个窗口的一种方法是将它们创建为独立窗口。这称为 SDI(单文档界面)。这需要更多的内存资源,因为每个窗口可能都有自己的菜单系统、工具栏等。
One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc.
MDI(多文档界面)应用程序消耗更少的内存资源。子窗口相对于彼此放置在主容器中。容器小部件称为 QMdiArea 。
MDI (Multiple Document Interface) applications consume lesser memory resources. The sub windows are laid down inside main container with relation to each other. The container widget is called QMdiArea.
QMdiArea 小部件通常占据 QMainWondow 对象的中央小部件。此区域中的子窗口是 QMdiSubWindow 类的实例。可以将任何 QWidget 设置为子窗口对象的内部小部件。MDI 区域中的子窗口可以以层叠或平铺方式排列。
QMdiArea widget generally occupies the central widget of QMainWondow object. Child windows in this area are instances of QMdiSubWindow class. It is possible to set any QWidget as the internal widget of subWindow object. Sub-windows in the MDI area can be arranged in cascaded or tile fashion.
下表列出了 QMdiArea 类和 QMdiSubWindow 类的重要方法 -
The following table lists important methods of QMdiArea class and QMdiSubWindow class −
Sr.No. |
Methods & Description |
1 |
addSubWindow() Adds a widget as a new subwindow in MDI area |
2 |
removeSubWindow() Removes a widget that is internal widget of a subwindow |
3 |
setActiveSubWindow() Activates a subwindow |
4 |
cascadeSubWindows() Arranges subwindows in MDiArea in a cascaded fashion |
5 |
tileSubWindows() Arranges subwindows in MDiArea in a tiled fashion |
6 |
closeActiveSubWindow() Closes the active subwindow |
7 |
subWindowList() Returns the list of subwindows in MDI Area |
8 |
setWidget() Sets a QWidget as an internal widget of a QMdiSubwindow instance |
QMdiArea 对象发出 subWindowActivated() 信号,而 QMdisubWindow 对象发出 windowStateChanged() 信号。
QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object.
Example
在以下示例中,包含 QMainWindow 的顶级窗口有一个菜单和 MdiArea。
In the following example, top level window comprising of QMainWindow has a menu and MdiArea.
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("New")
file.addAction("cascade")
file.addAction("Tiled")
菜单的 Triggered() 信号连接到 windowaction() 函数。
Triggered() signal of the menu is connected to windowaction() function.
file.triggered[QAction].connect(self.windowaction)
菜单的新操作向 MDI 区域中添加子窗口,其标题有一个递增的数字。
The new action of menu adds a subwindow in MDI area with a title having an incremental number to it.
MainWindow.count = MainWindow.count+1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("subwindow"+str(MainWindow.count))
self.mdi.addSubWindow(sub)
sub.show()
菜单的级联和平铺按钮分别以级联和平铺方式排列当前显示的子窗口。
Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively.
完整代码如下所示:
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainWindow(QMainWindow):
count = 0
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("New")
file.addAction("cascade")
file.addAction("Tiled")
file.triggered[QAction].connect(self.windowaction)
self.setWindowTitle("MDI demo")
def windowaction(self, q):
print "triggered"
if q.text() == "New":
MainWindow.count = MainWindow.count+1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("subwindow"+str(MainWindow.count))
self.mdi.addSubWindow(sub)
sub.show()
if q.text() == "cascade":
self.mdi.cascadeSubWindows()
if q.text() == "Tiled":
self.mdi.tileSubWindows()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - Drag & Drop
提供 drag and drop 对用户来说非常直观。它存在于许多桌面应用程序中,用户可以在其中将对象从一个窗口复制或移动到另一个窗口。
The provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another.
基于 MIME 的拖放数据传输基于 QDrag 类。 QMimeData 对象将数据与其对应的 MIME 类型相关联。它存储在剪贴板上,然后用于拖放过程。
MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process.
以下 QMimeData 类函数允许方便地检测和使用 MIME 类型。
The following QMimeData class functions allow the MIME type to be detected and used conveniently.
Tester |
Getter |
Setter |
MIME Types |
hasText() |
text() |
setText() |
text/plain |
hasHtml() |
html() |
setHtml() |
text/html |
hasUrls() |
urls() |
setUrls() |
text/uri-list |
hasImage() |
imageData() |
setImageData() |
image/ * |
hasColor() |
colorData() |
setColorData() |
application/x-color |
许多 QWidget 对象支持拖放活动。允许拖拽其数据的对象已设置 setDragEnabled(),它必须设置为 true。另一方面,部件应响应拖放事件,以存储拖到其中的数据。
Many QWidget objects support the drag and drop activity. Those that allow their data to be dragged have setDragEnabled() which must be set to true. On the other hand, the widgets should respond to the drag and drop events in order to store the data dragged into them.
-
DragEnterEvent provides an event which is sent to the target widget as dragging action enters it.
-
DragMoveEvent is used when the drag and drop action is in progress.
-
DragLeaveEvent is generated as the drag and drop action leaves the widget.
-
DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally.
Example
在以下代码中,DragEnterEvent 验证事件的 MIME 数据是否包含文本。如果包含,则接受事件的提议操作,并将文本作为一个新项目添加到 ComboBox 中。
In the following code, the DragEnterEvent verifies whether the MIME data of the event contains text. If yes, the event’s proposed action is accepted and the text is added as a new item in the ComboBox.
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class combo(QComboBox):
def __init__(self, title, parent):
super(combo, self).__init__( parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
print e
if e.mimeData().hasText():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
self.addItem(e.mimeData().text())
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lo = QFormLayout()
lo.addRow(QLabel("Type some text in textbox and drag it into combo box"))
edit = QLineEdit()
edit.setDragEnabled(True)
com = combo("Button", self)
lo.addRow(edit,com)
self.setLayout(lo)
self.setWindowTitle('Simple drag & drop')
def main():
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
if __name__ == '__main__':
main()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - Database Handling
PyQt API 包含一个精密的类系统,用于与许多基于 SQL 的数据库通信。其 QSqlDatabase 通过连接对象提供访问权限。以下是当前可用的 SQL 驱动程序的列表:
PyQt API contains an elaborate class system to communicate with many SQL based databases. Its QSqlDatabase provides access through a Connection object. Following is the list of currently available SQL drivers −
Sr.No. |
Driver Type & Description |
1 |
QDB2 IBM DB2 |
2 |
QIBASE Borland InterBase Driver |
3 |
QMYSQL MySQL Driver |
4 |
QOCI Oracle Call Interface Driver |
5 |
QODBC ODBC Driver (includes Microsoft SQL Server) |
6 |
QPSQL PostgreSQL Driver |
7 |
QSQLITE SQLite version 3 or above |
8 |
QSQLITE2 SQLite version 2 |
Example
与 SQLite 数据库的连接是使用静态方法建立的:
A connection with a SQLite database is established using the static method −
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sports.db')
QSqlDatabase 类的其他方法如下:
Other methods of QSqlDatabase class are as follows −
Sr.No. |
Methods & Description |
1 |
setDatabaseName() Sets the name of the database with which connection is sought |
2 |
setHostName() Sets the name of the host on which the database is installed |
3 |
setUserName() Specifies the user name for connection |
4 |
setPassword() Sets the connection object’s password if any |
5 |
commit() Commits the transactions and returns true if successful |
6 |
rollback() Rolls back the database transaction |
7 |
close() Closes the connection |
QSqlQuery 类具有执行和处理 SQL 命令的功能。可以执行 DDL 和 DML 两种类型的 SQL 查询。类中最重要的一个方法是 exec_(), 它将一个包含要执行的 SQL 语句的字符串作为参数。
QSqlQuery class has the functionality to execute and manipulate SQL commands. Both DDL and DML type of SQL queries can be executed. The most important method in the class is exec_(), which takes as an argument a string containing SQL statement to be executed.
query = QtSql.QSqlQuery()
query.exec_("create table sportsmen(id int primary key,
" "firstname varchar(20), lastname varchar(20))")
下面的脚本创建了一个 sports.db SQLite 数据库,其中包含一个有五条记录填充的 sportsperson 表。
The following script creates a SQLite database sports.db with a table of sportsperson populated with five records.
from PyQt4 import QtSql, QtGui
def createDB():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sports.db')
if not db.open():
QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"),
QtGui.qApp.tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information "
"how to build it.\n\n" "Click Cancel to exit."),
QtGui.QMessageBox.Cancel)
return False
query = QtSql.QSqlQuery()
query.exec_("create table sportsmen(id int primary key, "
"firstname varchar(20), lastname varchar(20))")
query.exec_("insert into sportsmen values(101, 'Roger', 'Federer')")
query.exec_("insert into sportsmen values(102, 'Christiano', 'Ronaldo')")
query.exec_("insert into sportsmen values(103, 'Ussain', 'Bolt')")
query.exec_("insert into sportsmen values(104, 'Sachin', 'Tendulkar')")
query.exec_("insert into sportsmen values(105, 'Saina', 'Nehwal')")
return True
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
createDB()
PyQt 中的 QSqlTableModel 类是一种高级接口,它为读取和写入一张表中的记录提供可编辑数据模型。此模型用于填充一个 QTableView 对象。它向用户展示一个可滚动的可编辑视图,该视图可以放在任何顶层窗口上。
QSqlTableModel class in PyQt is a high-level interface that provides editable data model for reading and writing records in a single table. This model is used to populate a QTableView object. It presents to the user a scrollable and editable view that can be put on any top level window.
一个 QTableModel 对象按如下方式声明 −
A QTableModel object is declared in the following manner −
model = QtSql.QSqlTableModel()
可以将其编辑策略设置为下列任意一项 −
Its editing strategy can be set to any of the following −
QSqlTableModel.OnFieldChange |
All changes will be applied immediately |
QSqlTableModel.OnRowChange |
Changes will be applied when the user selects a different row |
QSqlTableModel.OnManualSubmit |
All changes will be cached until either submitAll() or revertAll() is called |
Example
在以下示例中,sportsperson 表用作模型,并且策略设置为 −
In the following example, sportsperson table is used as a model and the strategy is set as −
model.setTable('sportsmen')
model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
model.select()
QTableView 类是 PyQt 中模型/视图框架的一部分。QTableView 对象创建如下 −
QTableView class is part of Model/View framework in PyQt. The QTableView object is created as follows −
view = QtGui.QTableView()
view.setModel(model)
view.setWindowTitle(title)
return view
该 QTableView 对象和两个 QPushButton 窗口小部件将被添加到顶层 QDialog 窗口。add 按钮的 clicked() 信号连接到 addrow(),后者对模型表格执行 insertRow()。
This QTableView object and two QPushButton widgets are added to the top level QDialog window. Clicked() signal of add button is connected to addrow() which performs insertRow() on the model table.
button.clicked.connect(addrow)
def addrow():
print model.rowCount()
ret = model.insertRows(model.rowCount(), 1)
print ret
与删除按钮相关联的槽执行一个删除行的 lambda 函数,该行由用户选择。
The Slot associated with the delete button executes a lambda function that deletes a row, which is selected by the user.
btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))
完整代码如下所示:
The complete code is as follows −
import sys
from PyQt4 import QtCore, QtGui, QtSql
import sportsconnection
def initializeModel(model):
model.setTable('sportsmen')
model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
model.select()
model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
model.setHeaderData(1, QtCore.Qt.Horizontal, "First name")
model.setHeaderData(2, QtCore.Qt.Horizontal, "Last name")
def createView(title, model):
view = QtGui.QTableView()
view.setModel(model)
view.setWindowTitle(title)
return view
def addrow():
print model.rowCount()
ret = model.insertRows(model.rowCount(), 1)
print ret
def findrow(i):
delrow = i.row()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sports.db')
model = QtSql.QSqlTableModel()
delrow = -1
initializeModel(model)
view1 = createView("Table Model (View 1)", model)
view1.clicked.connect(findrow)
dlg = QtGui.QDialog()
layout = QtGui.QVBoxLayout()
layout.addWidget(view1)
button = QtGui.QPushButton("Add a row")
button.clicked.connect(addrow)
layout.addWidget(button)
btn1 = QtGui.QPushButton("del a row")
btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))
layout.addWidget(btn1)
dlg.setLayout(layout)
dlg.setWindowTitle("Database Demo")
dlg.show()
sys.exit(app.exec_())
上述代码生成以下输出 -
The above code produces the following output −
PyQt - Drawing API
PyQt 中的所有 QWidget 类都是从 QPaintDevice 类派生的子类。 QPaintDevice 对可以通过 QPainter 绘图的二维空间进行抽象。画图设备的尺寸以从左上角开始的像素为单位进行测量。
All the QWidget classes in PyQt are sub classed from QPaintDevice class. A QPaintDevice is an abstraction of two dimensional space that can be drawn upon using a QPainter. Dimensions of paint device are measured in pixels starting from the top-left corner.
QPainter 类对窗口小部件和打印机等其他可画图设备执行低级绘图。通常,它在窗口小部件的绘制事件中使用。 QPaintEvent 每当窗口小部件的外观更新时就会发生。
QPainter class performs low level painting on widgets and other paintable devices such as printer. Normally, it is used in widget’s paint event. The QPaintEvent occurs whenever the widget’s appearance is updated.
通过调用 begin() 方法激活绘图器,而 end() 方法将其停用。在两者之间,使用下表中所列的适当方法绘制所需的图案。
The painter is activated by calling the begin() method, while the end() method deactivates it. In between, the desired pattern is painted by suitable methods as listed in the following table.
Sr.No. |
Methods & Description |
1 |
begin() Starts painting on the target device |
2 |
drawArc() Draws an arc between the starting and the end angle |
3 |
drawEllipse() Draws an ellipse inside a rectangle |
4 |
drawLine() Draws a line with endpoint coordinates specified |
5 |
drawPixmap() Extracts pixmap from the image file and displays it at the specified position |
6 |
drwaPolygon() Draws a polygon using an array of coordinates |
7 |
drawRect() Draws a rectangle starting at the top-left coordinate with the given width and height |
8 |
drawText() Displays the text at given coordinates |
9 |
fillRect() Fills the rectangle with the QColor parameter |
10 |
setBrush() Sets a brush style for painting |
11 |
setPen() Sets the color, size and style of pen to be used for drawing |
PyQt - BrushStyle Constants
Predefined QColor Styles
Qt.NoBrush |
No brush pattern |
Qt.SolidPattern |
Uniform color |
Qt.Dense1Pattern |
Extremely dense brush pattern |
Qt.HorPattern |
Horizontal lines |
Qt.VerPattern |
Vertical lines |
Qt.CrossPattern |
Crossing horizontal and vertical lines |
Qt.BDiagPattern |
Backward diagonal lines |
Qt.FDiagPattern |
Forward diagonal lines |
Qt.DiagCrossPattern |
Crossing diagonal lines |
Predefined QColor Objects
Qt.white |
Qt.black |
Qt.red |
Qt.darkRed |
Qt.green |
Qt.darkGreen |
Qt.blue |
Qt.cyan |
Qt.magenta |
Qt.yellow |
Qt.darkYellow |
Qt.gray |
可以通过指定 RGB、CMYK 或 HSV 值选择自定义颜色。
Custom color can be chosen by specifying RGB or CMYK or HSV values.
Example
以下示例实现了上述某些方法。
The following example implements some of these methods.
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.text = "hello world"
self.setGeometry(100,100, 400,300)
self.setWindowTitle('Draw Demo')
self.show()
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
qp.setPen(QColor(Qt.red))
qp.setFont(QFont('Arial', 20))
qp.drawText(10,50, "hello Pyth
on")
qp.setPen(QColor(Qt.blue))
qp.drawLine(10,100,100,100)
qp.drawRect(10,150,150,100)
qp.setPen(QColor(Qt.yellow))
qp.drawEllipse(100,50,100,50)
qp.drawPixmap(220,10,QPixmap("python.jpg"))
qp.fillRect(200,175,150,100,QBrush(Qt.SolidPattern))
qp.end()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
上述代码生成以下输出 -
The above code produces the following output −
PyQt - QClipboard
QClipboard 类提供对系统范围剪贴板的访问,提供在应用程序之间拷贝/粘贴数据的简洁机制。它的操作类似于 QDrag 类,使用类似的数据类型。
The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types.
QApplication 类有一个静态方法 clipboard(),它返回对剪贴板对象的引用。可以将任何类型的 MimeData 复制到剪贴板或从剪贴板粘贴。
QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard.
以下是一些常用的剪贴板类的方法: -
Following are the clipboard class methods that are commonly used −
Sr.No. |
Methods & Description |
1 |
clear() Clears clipboard contents |
2 |
setImage() Copies QImage into clipboard |
3 |
setMimeData() Sets MIME data into clipboard |
4 |
setPixmap() Copies Pixmap object in clipboard |
5 |
setText() Copies QString in clipboard |
6 |
text() Retrieves text from clipboard |
与剪贴板对象关联的信号是 -
Signal associated with clipboard object is −
Sr.No. |
Method & Description |
1 |
dataChanged() Whenever clipboard data changes |
Example
在以下示例中,两个 TextEdit 对象和两个 Pushbutton 被添加到一个顶级窗口。
In the following example, two TextEdit objects and two Pushbuttons are added to a top level window.
首先,实例化剪贴板对象。textedit 对象的 Copy() 方法将数据复制到系统剪贴板。当按下粘贴按钮时,它会获取剪贴板数据并将其粘贴到另一个 textedit 对象。
To begin with the clipboard object is instantiated. Copy() method of textedit object copies the data onto the system clipboard. When the Paste button is clicked, it fetches the clipboard data and pastes it in other textedit object.
PyQt - QPixmap Class
QPixmap 类提供图像的非屏幕表示。它可以用作 QPaintDevice 对象,也可以加载到另一个小部件,通常是标签或按钮。
QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button.
Qt API 还有另一个相似的类 QImage,针对 I/O 和其他像素操作进行了优化。另一方面,Pixmap 针对在屏幕上显示进行了优化。这两种格式可以互相转换。
Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible.
可以读入 QPixmap 中的图像文件类型如下 -
The types of image files that can be read into a QPixmap object are as follows −
BMP |
Windows Bitmap |
GIF |
Graphic Interchange Format (optional) |
JPG |
Joint Photographic Experts Group |
JPEG |
Joint Photographic Experts Group |
PNG |
Portable Network Graphics |
PBM |
Portable Bitmap |
PGM |
Portable Graymap |
PPM |
Portable Pixmap |
XBM |
X11 Bitmap |
XPM |
X11 Pixmap |
以下方法对于处理 QPixmap 对象很有用 -
Following methods are useful in handling QPixmap object −
Sr.No. |
Methods & Description |
1 |
copy() Copies pixmap data from a QRect object |
2 |
fromImage() Converts QImage object into QPixmap |
3 |
grabWidget() Creates a pixmap from the given widget |
4 |
grabWindow() Create pixmap of data in a window |
5 |
Load() Loads an image file as pixmap |
6 |
save() Saves the QPixmap object as a file |
7 |
toImage Converts a QPixmap to QImage |
QPixmap 最常见的用途是在标签/按钮上显示图像。
The most common use of QPixmap is to display image on a label/button.
Example
以下示例展示了使用 setPixmap() 方法在 QLabel 上显示图像。完整的代码如下 -
The following example shows an image displayed on a QLabel by using the setPixmap() method. The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
app = QApplication(sys.argv)
win = QWidget()
l1 = QLabel()
l1.setPixmap(QPixmap("python.jpg"))
vbox = QVBoxLayout()
vbox.addWidget(l1)
win.setLayout(vbox)
win.setWindowTitle("QPixmap Demo")
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −