凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

15. PyQt6 事件对象

2023-10-17 python 202
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QGridLayout, QLabel, QWidget
from PyQt6.QtGui import QGuiApplication
from PyQt6.QtCore import Qt


class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.label = None
        self.text = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle("PyQt6 事件对象")

        grid = QGridLayout()
        x = 0
        y = 0

        self.text = f"x:{x}, y:{y}"
        self.label = QLabel(self.text, self)

        grid.addWidget(self.label, 0, 0, Qt.AlignmentFlag.AlignTop)

        self.setMouseTracking(True)
        w = QWidget()
        w.setLayout(grid)
        self.setCentralWidget(w)

        self.setGeometry(100, 100, 400, 300)
        self.center()

    def mouseMoveEvent(self, e):
        x = int(e.position().x())
        y = int(e.position().y())

        text = f"x:{x}, y:{y}"
        self.label.setText(text)

    def center(self):
        qr = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    cls_app = App()
    cls_app.show()
    sys.exit(app.exec())

image.png

文章评论

0条评论