学习PyQt
因为喜欢
内容参考自 ARCHi的博客
一.面向对象的创建GUI
1.根据如下格式即可创建图形化界面
class Example(QWidget):
# 上述可以继承自QWidget 与 QMainWindow,分别表示其是控件或者是主窗口
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Sample')
self.setWindowIcon(QIcon('icon.jpg')) #设置Icon
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_()) # 进入主循环
2.添加按钮以及连接槽与信号
btn = QPushButton('Quit', self)
btn.clicked.connect(QCoreApplication.instance().quit)
# clicked信号发出后由 QCoreApplication的一个实例接受,退出
# 经测试这里面可以使用 qApp.quit() 替换 QCoreApplication.instance().quit
# 上述现象的原因:QApplication对象是可以通过全局变量qApp访问
btn.resize(btn.sizeHint()) #sizeHint()用于获取一个合适的大小
btn.move(0,0)
3.移动窗口使其居中
def __init__:
...
self.center() #调用center以居中
...
def center(self):
# 居中
qr = self.frameGeometry() # 获得与主窗口的特定矩形,含框架
cp = QDesktopWidget().availableGeometry().center() # 计算屏幕中心位置
qr.moveCenter(cp) # 获得的矩形的中心移动到屏幕中心位置
self.move(qr.topLeft()) # 将应用窗口的左上方移动到qr矩形的左上方
4.重载closeEvent() 以实现复杂退出动作
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message', "Are you sure to quit?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)