pythonQt4 label点击,触发响应

我们都知道button点击,可以触发响应事件,其实label也有点击事件,pyqt4的api帮助文档并没有给出,下面我们通过重载label的mousePressEvent事件来实现


下面是完整的实例代码:

#-*- coding:utf-8 -*-
#pyqt4 label 控件设置label图标,获取点击事件
####label本身是没有点击功能的,因此我们需要将其重载,重载,我们也可以给他加上别的功能
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

try:
    _encoding = QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QApplication.translate(context, text, disambig)

class myLabel(QLabel):
    def __init__(self,parent = None):
        super(myLabel,self).__init__(parent)

    def mousePressEvent(self, e):##重载一下鼠标点击事件
        print "you clicked the label"

    def mouseReleaseEvent(self, QMouseEvent):
        print 'you have release the mouse'

class MyWindow(QDialog,QWidget):
    def __init__(self,parent = None):
        super(MyWindow,self).__init__(parent)
        self.resize(400,400)
        self.mainlayout = QGridLayout(self)
        self.myLabelEx = myLabel()
        self.myLabelEx.setText(_translate("Form", "点我试试", None))

        self.mainlayout.addWidget(self.myLabelEx)

        self.myLabelEx.setToolTip(_translate("MainWindow", "", None))



app=QApplication(sys.argv)
window=MyWindow()
window.show()
app.exec_()


参考自:点击打开链接


你可能感兴趣的:(Python,GUI编程)