最小的程序框架
设置模板
详细解释
最小的程序框架
code1
以下代码是一个基本的PyQt5窗口程序的模板,复制粘贴你就能得到一个弹框~本文最后有对每行代码详细的说明。
from PyQt5.Qt import *
import sys
app = QApplication(sys.argv)
window = QWidget() # 继承自QWidget
window.setWindowTitle('SNH48 team SII')
window.resize(400, 400)
label = QLabel(window) # window是他的父控件
label.setText('孙芮加油!')
window.show()
sys.exit(app.exec_())
code2
还有更小的
from PyQt5.QtWidgets import *
app = QApplication([])
label = QLabel('Hello World!')
label.show()
app.exec_()
通过这两个例子的对比,是否能想明白sys.argv这个参数的意义?argv这个变量可以捕获传递给python脚本的命令行参数,实际上就是一个列表。只有我们通过命令行传递参数的时候才有实际意义,不然他就是一个空的列表。argv也有索引,argv[0]就是脚本本身名称,argv[1]就是命令行中传递给脚本的第一个附加参数。
设置模板
我们知道在IDE有自动补全功能,我们可以把我们的程序框架保存成一个live template 活动模板,在我们输入一个缩写后自动补全。
我们把上面的程序改一下,用一种面向对象的形式,这样就可以使我们专注于修改setup_ui 部分,这方便和其他模块的交叉引用,需要大家翻一翻python class类的使用方法。这段代码是可以直接运行的。
其中super().__init__
是很必要的,因为window子类重写了Qwidget的初始化程序,创建类的时候记得把父类的init引用出来。
from PyQt5.Qt import *
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("XXXX") # change tittle
self.resize(500, 500)
self.setup_ui()
def setup_ui(self):
pass # code here
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
子控件的操作都放在setupUi里面就可以比如:
def setupUi(self):
lable = QLable(self)
lable.setText('ccccccc')
在setting里面的live Templates下 选择python 点加号添加活动模板,把缩写abbreviation 设置成qtt,把代码粘贴到template text框中,应用确认。
这样在我们输入qtt后,会给我们自动补全代码啦
代码详细说明
code1可以参考我之前写的一个简书。
【pyqt】3.模板文件www.jianshu.com
code2 可以参考如下说明:
The code works as follows: First, we import the necessary PyQt classes via the statement:
from PyQt5.QtWidgets import *
Next, we create a
app = QApplication([])
Then, we create the label with the text we want:
label = QLabel('Hello World!')
By calling .show() on a widget, we can spawn a window that displays it:
label.show()
Finally, we hand control over to Qt:
app.exec_()
This too is required in every Qt application. It gives Qt a chance to run and process user input, such as for instance when the user clicks the "Window close" button.
And that's it! Congratulations on your first PyQt app :-)
参考^《Python数据分析基础》Page36