How to implement MousePressEvent for a Qt-Designer Widget in PyQt

你。 提交于 2019-12-01 08:46:47

问题


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'

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.


回答1:


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

  1. Use single inheritance and make the form a member variable
  2. Use multiple inheritance
  3. Dynamically generate the members directly from the UI file

Single Inheritance:

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

Multiple Inheritance:

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

Dynamically Generated:

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

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.

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



来源:https://stackoverflow.com/questions/3539095/how-to-implement-mousepressevent-for-a-qt-designer-widget-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!