前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python pyqt5 事件过滤器

python pyqt5 事件过滤器

作者头像
用户5760343
发布2019-07-22 11:18:35
1.4K0
发布2019-07-22 11:18:35
举报
文章被收录于专栏:sktj

-- coding: utf-8 --

from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys

class EventFilter(QDialog): def init(self, parent=None): super(EventFilter, self).init(parent) self.setWindowTitle("事件过滤器")

代码语言:javascript
复制
    self.label1 = QLabel("请点击")
    self.label2 = QLabel("请点击")
    self.label3 = QLabel("请点击")
    self.LabelState = QLabel("test")

    self.image1 = QImage("images/cartoon1.ico")
    self.image2 = QImage("images/cartoon1.ico")
    self.image3 = QImage("images/cartoon1.ico")

    self.width = 600
    self.height = 300

    self.resize(self.width, self.height)

    self.label1.installEventFilter(self)
    self.label2.installEventFilter(self)
    self.label3.installEventFilter(self)

    mainLayout = QGridLayout(self)
    mainLayout.addWidget(self.label1, 500, 0)
    mainLayout.addWidget(self.label2, 500, 1)
    mainLayout.addWidget(self.label3, 500, 2)
    mainLayout.addWidget(self.LabelState, 600, 1)
    self.setLayout(mainLayout)

def eventFilter(self, watched, event):
    if watched == self.label1: # 只对label1的点击事件进行过滤,重写其行为,其他的事件会被忽略
        if event.type() == QEvent.MouseButtonPress: # 这里对鼠标按下事件进行过滤,重写其行为
            mouseEvent = QMouseEvent(event)
            if mouseEvent.buttons() == Qt.LeftButton:
                self.LabelState.setText("按下鼠标左键")
            elif mouseEvent.buttons() == Qt.MidButton:
                self.LabelState.setText("按下鼠标中间键")
            elif mouseEvent.buttons() == Qt.RightButton:
                self.LabelState.setText("按下鼠标右键")

            '''转换图片大小'''
            transform = QTransform()
            transform.scale(0.5, 0.5)
            tmp = self.image1.transformed(transform)
            self.label1.setPixmap(QPixmap.fromImage(tmp))
        if event.type() == QEvent.MouseButtonRelease: # 这里对鼠标释放事件进行过滤,重写其行为
            self.LabelState.setText("释放鼠标按钮")
            self.label1.setPixmap(QPixmap.fromImage(self.image1))
    return QDialog.eventFilter(self, watched, event) # 其他情况会返回系统默认的事件处理方法。

if name == 'main': app = QApplication(sys.argv) dialog = EventFilter() dialog.show() sys.exit(app.exec_())

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.07.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • -- coding: utf-8 --
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档