溫馨提示×

python qpushbutton的鼠標事件處理

小樊
83
2024-09-06 16:02:20
欄目: 編程語言

在 PyQt5 中,要處理 QPushButton 的鼠標事件,你需要創(chuàng)建一個自定義按鈕類并重寫相應的事件處理方法

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_())

在這個示例中,我們創(chuàng)建了一個名為 CustomButton 的自定義按鈕類,它繼承自 QPushButton。然后,我們重寫了 mousePressEvent、mouseReleaseEventmouseDoubleClickEvent 方法,以便在不同的鼠標事件發(fā)生時打印相應的信息。最后,我們將自定義按鈕添加到主窗口中并顯示它。

0