[PyQt] creating a variable number of widget

Matt Newell newellm at blur.com
Mon Jul 2 17:21:15 BST 2012

On Sunday, July 01, 2012 04:09:31 PM David Beck wrote:
> I am trying to create a GUI for managing a multilingual lexical database.
> Every word in the database can have 1 to n meanings or senses, each of
> which has to have several types of information associated with it. This
> corresponds to a (simplified) XML structure as follows
> <Lex>
> 	<Word>word</word>
> 	<Def>
> 		<L1>English definition</L1>
> 		<L2>Spanish definition</L2>
> 		<EG>example sentences</EG>
> 	</Def>
> 	<Def> … etc., may be iterated many times
> </Lex>
> What I would like to do is write a script that reads from the XML, counts
> the number of iterations of <Def>, and if there is more than one creates a
> QTabWidget for each <Def> element with QGroupBoxes and QTextEdits to
> display the contents of each of the subelements. It doesn't seem possible
> to completely automate this process using some sort of loop (repeat for
> the number of <Def> elements in <Lex>) because the constructors for the
> widgets are like this
>         Fieldbook.ui.tab = QtGui.QWidget()
>         Fieldbook.ui.lL1Box = QtGui.QGroupBox(Fieldbook.ui.tab)
>         Fieldbook.ui.lL1Definition = QtGui.QTextEdit(Fieldbook.ui.lL1Box)
>         Fieldbook.ui.lL2Box = QtGui.QGroupBox(Fieldbook.ui.tab)
>         Fieldbook.ui.lL2Definition = QtGui.QTextEdit(Fieldbook.ui.lL2Box)
>         Fieldbook.ui.lExampleBox = QtGui.QGroupBox(Fieldbook.ui.tab)
>         Fieldbook.ui.lExamples = QtGui.QTextEdit(Fieldbook.ui.lExampleBox)
> On the first iteration this is fine, but the second iteration of the loop
> is going to create widgets with exactly the same names. Is there someway
> to replace something like the ".tab" in Fieldbook.ui.tab = QtGui.QWidget()
> with a variable that changes with every iteration of the loop?
There's many ways to do this in python.  You could store each set of widgets 
in a tuple, and have a list of tuples, one for each Def.

widgetGroups = []
for def in defs:
    tab = QtGui.QWidget()
    IL1Box = QtGui.QGroupBox(tab)
    widgetGroups.append( (tab,IL1Box,...) )

If you want to be able to reference the individual widgets by name instead of 
their index in the tuple, you could instead use a dict, or go one step further 
and use a class.

If for some reason you really wanted to store each widget individually in 
Fieldbook.ui's class dict, you could do

for def, i in enumerate(defs):
    Fieldbook.ui.setattr( 'tab%i' % i, QtGui.QWidget() )


More information about the PyQt mailing list