python PyQt,Qwidget 上的点击动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1996511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PyQt, click action on Qwidget
提问by Lopoc
I've this simple problem, I can grab the event of a click on button, but now I need to handle a click over a widget, here is part of the code:
我有这个简单的问题,我可以抓住点击按钮的事件,但现在我需要处理对小部件的点击,这是代码的一部分:
self.widget = QtGui.QWidget(self)
self.widget.setStyleSheet("QWidget { background-color: %s }" % color.name())
self.widget.setGeometry(150, 22, 50, 50)
self.connect(???)
well, what should i put in the ??? to grab a click action over the created widget? thank in advanced
好吧,我应该在里面放什么???在创建的小部件上抓取点击动作?提前致谢
回答by Ja8zyjits
you can try this i found this from this blog site's comment box from Jared GlassIt was working fine for me
你可以试试这个我是从这个博客网站的评论框中找到的,来自 Jared Glass这对我来说很好用
self.widget.mouseReleaseEvent=self.myfunction
or
或者
self.widget.mouseReleaseEvent=lambda event:print 'working'
or
或者
self.widget.mouseReleaseEvent=lambda event,my_variable:self.myfunction(event,my_variable)
only the last example is what i have written on my own rest all have been mentioned in http://popdevelop.com/2010/05/an-example-on-how-to-make-qlabel-clickable/. The last code helps you to pass any variables eg:widget name or widget number if multiple widgets exists.
只有最后一个例子是我自己写的,所有都在http://popdevelop.com/2010/05/an-example-on-how-to-make-qlabel-clickable/ 中提到。如果存在多个小部件,最后一个代码可帮助您传递任何变量,例如:小部件名称或小部件编号。
回答by Jesse Aldridge
Use mousePressEvent instead.
请改用 mousePressEvent。
import sys
from PyQt4.QtGui import QWidget, QApplication
class MyWidget(QWidget):
def mousePressEvent(self, event):
print "clicked"
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
app.exec_()