0

I've been looking for a way of subclassing QPushButton, so I can connect 'clicked' signal when constructing new button, like:

Btn = CustomButtonClass('Text', clicked='lambda: self.func(par)')

So far - without any success.

I guess the thing is to pass correct parameters to init() of CustomButtonClass, but have no idea what, and why.

What I've got:

class CustomButtonClass(QtGui.QPushButton):
    def __init__(self, text, parent=None):
        super().__init__()

I also noticed that:

Btn.clicked.connect(lambda: self.func(par))

Also doesn't work.

Do I have to override QPushButton's mouseReleaseEvent or construct custom signal to be able to complete my task?

1 Answers1

1

You don't need to create a sub-class, because both PyQt and PySide already have this feature (see Connecting Signals Using Keyword Arguments in the PyQt docs).

Demo:

>>> from PyQt4 import QtGui
>>> app = QtGui.QApplication([])
>>> btn = QtGui.QPushButton('Test', clicked=lambda: print('Hello World!'))
>>> btn.click()
Hello World!

If you still need to subclass, then of course you can simply do:

class CustomButtonClass(QtGui.QPushButton):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Maybe my question was not specific enough... Well, I really need custom subclass, because I need extra formatting and functionality for my buttons. But with your answer there is an idea comming to my mind, that I can override QPushButton mouseReleaseEvent with my app-specific instructions... Thank you very much! :) –  Mar 28 '16 at 08:04
  • @KrzysiekŁuczak. There's no need to do anything like that - my answer will still work. I've added some more code to show what I mean. – ekhumoro Mar 28 '16 at 15:48
  • Late answer, but... In my case the thing was, that I missed *args and **kwargs in __init__() arguments –  Nov 04 '16 at 09:13