1. 程式人生 > >pythonQt4 label點選,觸發響應 ——轉載

pythonQt4 label點選,觸發響應 ——轉載

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