[Qt-interest] Dynamic QMenuBar - passing a value to the slot in connect( )?

Andre Somers andre at familiesomers.nl
Thu Mar 24 19:19:34 CET 2011


Op 24-3-2011 19:03, Robert Wood schreef:
> I have successfully created a QMenuBar on the fly according to the
> number of com ports in my /dev directory. I have then managed to have
> each entry in the menu call a routine. However, I cannot work out how to
> pass the string of the selected item to the routine called. The code is
> as below:
>
>
> // In the routine that detects the VCPs:
> // numberOfEntries is how many VCPs in the /dev directory
> // results is  a QStringList of the directory entires
> QAction *exitAction[numberOfEntries];
>
> for (i=0;i<numberOfEntries;i++)
> 	{
> 	exitAction[i] =  ui->menuSelectPort->addAction(results.at(i));
> 	connect(exitAction[i], SIGNAL(triggered()), this, SLOT(openPort()));
> 	}
>
>
> This works in that any item elected in the menuSelectPort of the
> QMenuBar calls the openPort routine.
>
> I have tried various things such as:
>
> connect(exitAction[i], SIGNAL(triggered()), this,
> SLOT(openPort(results.at(i))));
>
> or even:
>
> connect(exitAction[i], SIGNAL(triggered()), this, SLOT(openPort(i)));
>
> (The latter just to try and prove a point.)
>
> And then having openPort setup so it expects a string or a number passed
> to it, but this just doesn't work.
>
> So how can I make it so my dynamically created menu passes its string
> from the menu item selected by the user to the slot it calls? The
> obvious method doesn't work and in fact as soon as I try and pass
> anything at all to openPort() it doesn't call the openPort routine at all!
You can't. But there are ways to work around it. The easiest is probably 
to use QSignalMapper. You can use that class to attach a value (an 
integer, a string or a QWidget*) to an otherwise argument-less signal.

André




More information about the Qt-interest-old mailing list