Quote:
Originally Posted by jackie_w
I'm trying to tidy up the widget creating/layout code in a rather large QDialog which contains many QGroupBox widgets each of which contains a list of buttons. For each groupbox the buttons will all be QPushButton or all QCheckBox.
- I've managed to code a working method which successfully creates the groupbox/buttonlist pairs but I need a bit of help. The code currently is something like this:
Code:
def create_groupbox(self, lvalues, widget='QPushButton'):
... ...
buttonlist = []
for val in lvalues:
... ...
if widget == 'QPushButton':
button = QPushButton()
elif widget == 'QCheckBox':
button = QCheckBox()
button.setText(val)
... ...
buttonlist.append(button)
... ...
return buttonlist, groupbox
Is there better 1-line code for the red bit?
|
- I am not sure about "better", but there is a one-line way to do it.
Code:
getattr(getattr(__import__('PyQt4'), 'Qt'), widget)()
This gets the class object for the class named by 'widget', then instantiates it. Be sure to use the right PyQt for the version of calibre you are running.
You can of course get the Qt module outside the loop, then use it inside the loop. Something like:
Code:
def create_groupbox(self, lvalues, widget='QPushButton'):
... ...
buttonlist = []
module_ = getattr(__import__('PyQt4'), 'Qt')
for val in lvalues:
... ...
button = getattr(module_, widget)()
button.setText(val)
... ...
buttonlist.append(button)
... ...
return buttonlist, groupbox
EDIT: Kovid's solution is clearly better if there is only one class involved.
Quote:
- A follow-up question. If I've previously created a groupbox/buttonlist pair using the above method,
e.g. self.blist, gbox = self.create_groupbox(['1em', '2em', '3em'])
and elsewhere in the code I need to know whether self.blist was created using QPushButton or QCheckBox, is there a test I could use on self.blist[0] to answer that question?
|
I think you are looking for isinstance, as in
Code:
if isinstance(self.blist[0], QPushButton):