首页 PyQt5教程 PyQt5自定义窗口演练鼠标和窗口事件
pay pay
教程目录

PyQt5自定义窗口演练鼠标和窗口事件

日期: 四月 24, 2023, 10:13 a.m.
栏目: PyQt5教程
阅读: 220
作者: Python自学网-村长

摘要: 让我们结合上面提到的鼠标事件和窗口事件,来演示如何自定义一个带有鼠标和窗口事件的窗口。

让我们结合上面提到的鼠标事件和窗口事件,来演示如何自定义一个带有鼠标和窗口事件的窗口。

一、首先,我们需要导入PyQt5库中的一些类和模块:

from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPainter, QBrush, QPen
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys

二、然后,我们定义一个自定义的QMainWindow类,并重写它的几个方法,以实现鼠标和窗口事件的响应:

class MyMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Custom Window')
        self.setFixedSize(400, 300)

        self.mouse_pos = None

        label = QLabel('Hello PyQt5', self)
        label.setAlignment(Qt.AlignCenter)
        label.setGeometry(100, 100, 200, 30)

    def mousePressEvent(self, event):
        self.mouse_pos = event.pos()

    def mouseReleaseEvent(self, event):
        self.mouse_pos = None

    def mouseMoveEvent(self, event):
        if self.mouse_pos:
            diff = event.pos() - self.mouse_pos
            new_pos = self.pos() + diff
            self.move(new_pos)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        brush = QBrush(Qt.SolidPattern)
        painter.setBrush(brush)

        pen = QPen(Qt.NoPen)
        painter.setPen(pen)

        painter.drawRect(100, 100, 200, 100)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()

在这个自定义的QMainWindow类中,我们添加了一个成员变量mouse_pos来记录鼠标的位置,在鼠标按下、松开和移动时更新它的值,并在鼠标移动时通过移动窗口实现拖拽功能。

此外,我们还重写了paintEvent方法来绘制一个矩形,并通过keyPressEvent方法响应ESC键的按下事件,关闭窗口。

三、最后,我们创建一个QApplication实例,并显示自定义的QMainWindow窗口:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyMainWindow()
    window.show()
    sys.exit(app.exec_())

现在,我们可以运行程序,点击矩形,拖动窗口,按下ESC键,观察窗口的行为。

通过这个演示,我们可以看到,在PyQt5中,通过重写窗口事件和鼠标事件的方法,可以实现自定义窗口的各种交互响应行为。

部分文字内容为【Python自学网】原创作品,转载请注明出处!视频内容已申请版权,切勿转载!
回顶部