python - PyQt5 PushButton Hover 函数调用
问题描述
当鼠标悬停在按钮上时,我想调用一个函数。基本上我无法使用 QPushButton:hover 因为我要调用的函数非常复杂并且与按钮没有太大关系。这是一个示例代码。
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QWidget
# ----------------------------------------------------
def firstText(myLabel):
myLabel.setText("Wassup yall?")
def secondText(myLabel):
myLabel.setText("Initial Text")
# ----------------------------------------------------
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("Wassup?")
window.setFixedWidth(1000)
window.setFixedHeight(600)
window.move(100, 50)
window.setStyleSheet(
"background-color: rgb(208, 208, 208);"
)
button = QtWidgets.QPushButton(window)
button.setGeometry(100, 50, 120, 60)
button.setStyleSheet(
"QPushButton {"
"border: 0px solid;"
"background-color: rgb(255, 50, 50);"
"}"
)
label = QtWidgets.QLabel(window)
label.setGeometry(100, 120, 120, 60)
label.setStyleSheet(
"background-color: rgb(128, 255, 64);"
)
label.setText("Initial Text")
window.show()
sys.exit(app.exec())
因此,我希望在将鼠标悬停在按钮上时调用函数“firstText”,并在离开悬停时调用函数“secondText”。
解决方案
一种可能的解决方案是覆盖 enterEvent 和 leaveEvent 方法:
import sys
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QWidget
class Button(QPushButton):
entered = pyqtSignal()
leaved = pyqtSignal()
def enterEvent(self, event):
super().enterEvent(event)
self.entered.emit()
def leaveEvent(self, event):
super().leaveEvent(event)
self.leaved.emit()
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__()
self.setWindowTitle("Wassup?")
self.setFixedSize(1000, 600)
self.move(100, 50)
self.setStyleSheet("background-color: rgb(208, 208, 208);")
button = Button(self)
button.setGeometry(100, 50, 120, 60)
button.setStyleSheet(
"QPushButton {"
"border: 0px solid;"
"background-color: rgb(255, 50, 50);"
"}"
)
self.label = QLabel(self)
self.label.setGeometry(100, 120, 120, 60)
self.label.setStyleSheet("background-color: rgb(128, 255, 64);")
self.label.setText("Initial Text")
button.entered.connect(self.handle_entered)
button.leaved.connect(self.handle_leaved)
def handle_entered(self):
self.label.setText("Wassup yall?")
def handle_leaved(self):
self.label.setText("Initial Text")
app = QApplication(sys.argv)
window = Widget()
window.show()
sys.exit(app.exec())
推荐阅读
- android - 使用 Saved State 模块在 Android 中为 ViewModel 保存 Arraylist 以处理进程死亡
- python - 如何修复 Heroku 上 django 频道 3 中的 websocket 连接失败
- python - pandas groupby 过滤和采样
- r - 如何解决错误消息“data.frame”并非都是 TRUE”
- azure - Azure 介绍问题
- sql - BigQuery:当没有什么可以加入时进行昂贵的全表扫描
- vue.js - Vue3,VeeValidate4 - 未捕获(承诺中)TypeError:无法读取未定义的属性“firstName”
- android - 无法从当前目的地找到导航操作/目的地
- laravel - Laravel Livewire 处理数据但不重新渲染
- javascript - 根据环境从 HTML 更改 URL