之前在网上看到别人写的桌面程序非常漂亮
很想自己也写出像 huhumhire-hosts 那样漂亮的桌面应用程序
仔细一查,原来是用 PyQt 写的,于是自己也下定了决心来学学这个
目前国内好像没有多少关于这方面的比较系统的入门教程
于是只好自己摸索。
一次偶然的机会,在油土鳖上看到了一个比较不错的视频
https://www.youtube.com/watch?v=DF_44sWnAsk&list=PLQVvvaa0QuDdVpDFNq4FwY9APZPGSUyR4
听了下这个大神讲的课,感觉非常不错,虽然可能需要点英语水平,不过不是什么大问题
这里就把他所讲到的这些例子给列出来吧
1、Hello World 程序(QMainWindow)
一个最简单的 PyQt4 窗口程序:1
2
3
4
5
6
7
8
9
10
11
12
13
14# -*- coding: utf-8 -*-
from PyQt4 import QtGui # 导入 PyQt4 包
import sys
class Window(QtGui.QMainWindow):
"""docstring for ClassName"""
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 500) # 设置窗体大小
self.show() # 显示窗体
app = QtGui.QApplication(sys.argv)
GUI = Window() # 将 Window 实例化并写入全局变量 GUI
sys.exit(app.exec_()) # 设置程序出口
2、按钮控件 Buttons(QPushButton)
在上例的基础上添加代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore # 导入 PyQt4 包
import sys
class Window(QtGui.QMainWindow):
"""docstring for ClassName"""
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 500) # 设置窗体大小
self.setWindowTitle(u"PyQt4 按钮演示") # 设置窗体标题
self.home() # 调用按钮初始化方法
def home(self):
btn = QtGui.QPushButton(u"退出程序", self) # 实例化一个按钮
btn.clicked.connect(QtCore.QCoreApplication.instance().quit) # 给按钮绑定事件,当点击按钮时,触发 quit 方法
btn.resize(100, 100) # 设置按钮大小
btn.move(100, 100) # 设置按钮所在位置
self.show() # 显示窗体
app = QtGui.QApplication(sys.argv)
GUI = Window() # 将 Window 实例化并写入全局变量 GUI
sys.exit(app.exec_()) # 设置程序出口
3、按钮事件控制 Button Functions
在上例的基础上添加代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore # 导入 PyQt4 包
import sys
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 500)
self.setWindowTitle(u"PyQt4 按钮演示")
self.home()
def home(self):
btn = QtGui.QPushButton(u"退出程序", self)
btn.clicked.connect(self.close_application) # 连接自身的方法
#btn.resize(100, 100)
#btn.move(100, 100)
btn.resize(btn.minimumSizeHint()) # 自动决定按钮大小
btn.move(0, 0)
self.show()
def close_application(self):
sys.exit()
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
4、菜单栏 menubar(QMenuBar)
1 | # -*- coding: utf-8 -*- |
效果图:
5、工具栏 toolbar(QToolBar)
1 | import sys |
效果图
6、弹出消息窗口 pop up message(QMessageBox)
1 | # coding: utf-8 |
效果图
7、复选框 check box(QCheckBox)
1 | # coding: utf-8 |
效果图
8、进度条 progress bar(QProgressBar)
1 | # coding: utf-8 |
效果图
9、下拉菜单 drop down combobox(QComboBox)
1 | # coding: utf-8 |
效果图
10、字体选择器 font widget(QFontDialog)
1 | # coding: utf-8 |
效果图
11、颜色选择器与日历控件 color pickup widget and calendar(QColorDialog, QCalendarWidget)
1 | # coding: utf-8 |
效果图
12、文本编辑器 editor textedit(QTextEdit)
1 | # coding: utf-8 |
效果图
13、文件选择器 file picker(QFileDialog)
1 | # coding: utf-8 |
效果图