Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top