如何在 PyQt 中为 Qt-Designer 小部件实现 MousePressEvent [英] How to implement MousePressEvent for a Qt-Designer Widget in PyQt

查看:75
本文介绍了如何在 PyQt 中为 Qt-Designer 小部件实现 MousePressEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小部件(QTabeleWidget、QLabels 和一些 QButton).它是在 Qt-Designer 中构建的,现在我必须实现一些东西.为此,我需要 mousePressEvent.通常我会写一个子类并写这样的东西:

I've got a Widget (QTabeleWidget, QLabels and some QButtons). It was built in Qt-Designer, and now I have to implement some things. For that I need the mousePressEvent. Usually I would write a subclass and write something like this:

def mousePressEvent(self, event):
    if event.button() == Qt.LeftButton:
        print "left"
    else:
        print 'right'

但我不知道如何为设计器中创建的小部件执行此操作.我需要它用于 QTableeWidget.希望可以有人帮帮我.我试图在谷歌的帮助下解决问题,但没有成功.这个网站帮助了我很多次,所以我想我会试一试并询问.

But I don't know how to do that for a Widget created in the Designer. I need it for the QTabeleWidget. Hope someone can help me. I tried to solve the problem with the help of google, but without success. This site helped me many times, so I thought I'll give it a shot and ask.

推荐答案

使用 PyQt,可以通过三种不同的方式处理在设计器中创建的表单:

With PyQt there are three different ways to work with forms created in designer:

  1. 使用单继承并使表单成为成员变量
  2. 使用多重继承
  3. 直接从 UI 文件动态生成成员

单一继承:

class MyTableWidget(QTableWidget):
    def __init__(self, parent, *args):
        super(MyTableWidget, self).__init__(parent, args)
        self.ui = YourFormName()
        self.ui.setupUi(self)
        # all gui elements are now accessed through self.ui
    def mousePressEvent(self, event):
        pass # do something useful

多重继承:

class MyTableWidget(QTableWidget, YourFormName):
    def __init__(self, parent, *args):
        super(MyTableWidget, self).__init__(parent, args)
        self.setupUi(self)
        # self now has all members you defined in the form
    def mousePressEvent(self, event):
        pass # do something useful

动态生成:

from PyQt4 import uic
yourFormTypeInstance = uic.loadUi('/path/to/your/file.ui')

对于上面的 (3),您最终会得到一个您为表单指定的任何基本类型的实例.然后,您可以根据需要覆盖 mousePressEvent.

For (3) above, you'll end up with an instance of whatever base type you specified for your form. You can then override your mousePressEvent as desired.

我建议你看看 第 13.1 节PyQt4 参考手册.13.2 节讨论了 uic 模块.

I'd recommend you take a look at section 13.1 in the PyQt4 reference manual. Section 13.2 talks about the uic module.

这篇关于如何在 PyQt 中为 Qt-Designer 小部件实现 MousePressEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆