python

python qpushbutton的鼠标事件处理

小樊
83
2024-09-06 16:02:20
栏目: 编程语言

在 PyQt5 中,要处理 QPushButton 的鼠标事件,你需要创建一个自定义按钮类并重写相应的事件处理方法

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtCore import Qt

class CustomButton(QPushButton):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            print("左键点击")
        elif event.button() == Qt.RightButton:
            print("右键点击")
        super().mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            print("左键释放")
        elif event.button() == Qt.RightButton:
            print("右键释放")
        super().mouseReleaseEvent(event)

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.LeftButton:
            print("左键双击")
        elif event.button() == Qt.RightButton:
            print("右键双击")
        super().mouseDoubleClickEvent(event)

app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout(window)

custom_button = CustomButton("点击我")
layout.addWidget(custom_button)

window.setLayout(layout)
window.show()
sys.exit(app.exec_())

在这个示例中,我们创建了一个名为 CustomButton 的自定义按钮类,它继承自 QPushButton。然后,我们重写了 mousePressEventmouseReleaseEventmouseDoubleClickEvent 方法,以便在不同的鼠标事件发生时打印相应的信息。最后,我们将自定义按钮添加到主窗口中并显示它。

0
看了该问题的人还看了