pythonqt编写窗口示例
范例程序1
from PyQt5.QtWidgets import QWidget, QApplication, QLabel
import sys
class MyWindow(QWidget):
def __init__(self):
super().__init__()
def show_mywindow():
app = QApplication(sys.argv)
mywindows = MyWindow()
QLabel(mywindows).setText("<p style='color: red; margin-left: 20px'><b>hell world</b></p>")
mywindows.show()
# app.exec_()
sys.exit(app.exec_())
show_mywindow()
关于代码的解释:
1.QtWidget是通用窗口类
2.super(mywindow,self).init() : 这里我们要重载一下,mywindows同时也包含了QtWidgets.QWidget的预加载项 ;init其实是构造函数,也就是类被创建后就会预先加载的项目, (self)是pyqt类方法必须要有的,代表自己,相当于java,c++中的this
3.app = QtWidgets.QApplication(sys.argv) #pyqt窗口必须在QApplication方法中使用, #要不然会报错 QWidget: Must construct a QApplication before a QWidget或者Process finished with exit code 1. 类中init函数作用Initializes the window system and constructs an application object with argc command line arguments in argv.
4.QLabel(mywindows)在窗口中绑定label; setText:设置label显示的内容,并且qt支持html标签。注意label也可以这样使用:label=QtWidgets.QLabel(“hell world”); label.show()
5.show()是QWidget的方法,用来显示窗口的!
6.app.exec_()启动事件循环,否则窗口只会一闪而过。 sys.exit([arg])程序中间的退出,arg=0为正常退出。exit退出条件(参数)是app.exec_()也就是整个窗口关闭。消息结束的时候,进程结束,并返回0,接着调用sys.exit(0)退出程序。
7.可以将显示mywindows的方法show_mywindow写在第二个文件中,达到逻辑与界面分离的效果。
范例程序2
from PyQt5.QtWidgets import QApplication, QWidget
import sys
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
w.resize(250, 150)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()
sys.exit(app.exec_())