如何解决MousePressEvent在QPushbutton上不起作用
所以在我的qtgui中,我想知道何时有人单击(在任何QObject或窗口上), 因此,我正在使用MousePressEvent。 但是,当我单击QPushbuttons时,该事件无法识别
我的代码有一个简单的版本
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import os
from PyQt5.QtWidgets import QMainWindow
class Ui_MainWindow(QMainWindow):
def __init__(self):
super(Ui_MainWindow,self).__init__()
def setupUi(self):
self.setObjectName("MainWindow")
self.resize(1920,1080)
self.setStyleSheet("\n"
"")
self.centralwidget = QtWidgets.QWidget(self)
#self.centralwidget.setStyleSheet("#centralwidget{background-image: url(:/images/assets/back1.jpg);}")
self.centralwidget.setObjectName("centralwidget")
self.timer = 5000
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.but1 = QtWidgets.QPushButton(self.centralwidget)
self.but1.setGeometry(QtCore.QRect(1500,500,301,51))
self.but1.setMouseTracking(True)
self.but1.setStyleSheet("QPushButton{\n"
"border-style: outset;""\n"
" border-radius: 10px;"
"border-width: 2px;"
"border-color: gray;"
"font: 18pt \"Adobe Pi Std\";\n"
"color: rgb(255,255,255);}\n"
"QPushButton:pressed { border-style : inset; border-color:black}")
self.but1.setObjectName("but1")
self.but1.clicked.connect(lambda : self.addtimer())
self.setCentralWidget(self.centralwidget)
self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self)
def mousePressEvent(self,event):
#super(Ui_MainWindow,self).mousePressEvent(event) i tried this but change nothing
print("Clicked")
def addtimer(self):
self.timer+=5000
print(self.timer)
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate("MainWindow","MainWindow"))
self.but1.setText(_translate("MainWindow","Explore!"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_MainWindow()
ui.setupUi()
ui.show()
sys.exit(app.exec_())
我坚信此问题是由继承力不佳引起的,但我不知道该如何解决。
如果您想知道为什么我想知道何时有人单击,那么主要目的是设置一个Qtimer,如果在x时间后没有单击发生,它将关闭窗口
预先感谢
解决方法
您需要做的是确定您要检查的鼠标事件类型,然后转到pyqt5文档并搜索执行该操作的事件(这就是我所做的),这只是对检测该事件的逻辑进行编码。
#Below your other self.but1... u add this one to call the function each time u click
self.but1.clicked.connect(lambda: self.mousePressEvent(QMouseEvent.MouseButtonPress))
def mousePressEvent(self,event):
#Here you check if the event u receive its the one you want to track
if event == QMouseEvent.MouseButtonPress:
print("Clicked")
希望此解决方案对您有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。