zetcode :: First programs in PyQt5

时间:2023-02-05 12:34:06

练习代码,详见网站 http://zetcode.com/gui/pyqt5/firstprograms/

import sys
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore class TooltipExample(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()     def initUI(self):
        # 静态方法,设置Tooltip字体
        QtWidgets.QToolTip.setFont(QtGui.QFont("SansSerif", 15))
        self.setToolTip("This is a <b>QWidget</b> widget")
        # tooltip持续1000毫秒
        self.setToolTipDuration(1000)         btn = QtWidgets.QPushButton('Quit', self)
        # QCoreApplication.instance 返回当前实例
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        btn.resize(btn.sizeHint())
        btn.move(50, 50)
        btn.setToolTip("This is a <b>QPushButton</b> widget")
        btn.setToolTipDuration(1000)         # x,y,width,height
        #self.setGeometry(300, 300, 300, 150)
        self.resize(300,150)
        self.center()
        self.setWindowTitle("Tooltips")     def center(self):
        wr = self.frameGeometry()
        # QDesktopWidget::availableGeometry 返回屏幕rect
        qr = QtWidgets.QDesktopWidget().availableGeometry().center()
        # QRect:moveCenter 中心对齐
        wr.moveCenter(qr)
        # 实际调节窗口位置
        self.move(wr.topLeft())     def closeEvent(self, event):
        # 静态方法生成MessageBox,返回StandardButton
        reply = QtWidgets.QMessageBox.question(self, 'Message', 'Are you sure to quit ?',
                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                               QtWidgets.QMessageBox.No)         if reply == QtWidgets.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore() if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    example = TooltipExample()
    example.show()
    sys.exit(app.exec_())