- PyQt5 教程
- PyQt5 - 主页
- PyQt5 - 简介
- PyQt5 - 新增功能
- PyQt5 - 你好世界
- PyQt5 - 主要类
- PyQt5 - 使用 Qt 设计器
- PyQt5 - 信号和槽
- PyQt5 - 布局管理
- PyQt5 - 基本小部件
- PyQt5 - QDialog 类
- PyQt5 - QMessageBox
- PyQt5 - 多文档界面
- PyQt5 - 拖放
- PyQt5 - 数据库处理
- PyQt5 - 绘图 API
- PyQt5 - BrushStyle 常量
- PyQt5 - QClipboard
- PyQt5 - QPixmap 类
- PyQt5 有用资源
- PyQt5 - 快速指南
- PyQt5 - 有用的资源
- PyQt5 - 讨论
PyQt5 - 你好世界
使用 PyQt 创建一个简单的 GUI 应用程序涉及以下步骤 -
从 PyQt5 包导入 QtCore、QtGui 和 QtWidgets 模块。
创建 QApplication 类的应用程序对象。
QWidget 对象创建顶级窗口。在其中添加 QLabel 对象。
将标签的标题设置为“hello world”。
通过setGeometry()方法定义窗口的大小和位置。
通过app.exec_()方法进入应用程序的主循环。
以下是在 PyQt 中执行 Hello World 程序的代码 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b = QLabel(w)
b.setText("Hello World!")
w.setGeometry(100,100,200,50)
b.move(50,20)
w.setWindowTitle("PyQt5")
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
上面的代码产生以下输出 -
还可以开发上述代码的面向对象的解决方案。
从 PyQt5 包导入 QtCore、QtGui 和 QtWidgets 模块。
创建 QApplication 类的应用程序对象。
基于QWidget类声明窗口类
添加一个 QLabel 对象并将标签的标题设置为“hello world”。
通过setGeometry()方法定义窗口的大小和位置。
通过app.exec_()方法进入应用程序的主循环。
以下是面向对象解决方案的完整代码 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class window(QWidget):
def __init__(self, parent = None):
super(window, self).__init__(parent)
self.resize(200,50)
self.setWindowTitle("PyQt5")
self.label = QLabel(self)
self.label.setText("Hello World")
font = QFont()
font.setFamily("Arial")
font.setPointSize(16)
self.label.setFont(font)
self.label.move(50,20)
def main():
app = QApplication(sys.argv)
ex = window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
