[Qt-interest] Question SLOT Macro & messing with the QObject::connect method

kent williams nkwmailinglists at gmail.com
Thu Feb 4 21:07:56 CET 2010


So I think in the end the best way to do this would be something like
this: Instead of the 'evil hacking' below, I'd change the way the
string constants were set up.  So my call would be something like
this:

const char *items[] = { "item 1", "item 2", "item 3", 0 };
this->MakeMenu(menu,SLOT(handleMenuItem()),items);

On Thu, Feb 4, 2010 at 11:05 AM, kent williams
<nkwmailinglists at gmail.com> wrote:
> I wanted to use a private method in my MainWindow class to encapsulate
> some of the Qt boilerplate with respect to building menus.
>
> After fiddling about I ended up with this:
>
> // theMenu -- menu to add actions to
> // theAction -- function to connect to triggered
> //
> void
> BTMainWindow::
> MakeMenu(QMenu *theMenu,const char *theAction,const char **labels)
> {
>  std::string _action("1"); // EVIL HACKING -- fake the SLOT macro
>  _action += theAction;   //
>  for(unsigned i = 0; labels[i] != 0; i++)
>    {
>    QAction *tempAction = new QAction(tr(labels[i]),this);
>    theMenu->addAction(tempAction);
>    connect(tempAction,SIGNAL(triggered()),this,
>            _action.c_str());
>    }
> }
>
> Now because I'm a new Qt users, when I looked at the QObject
> documentation, I originally thought I could just pass in a string
> literal to QObject::connect to specify the slot.  Turns out that
> really doesn't work -- I kept getting warnings saying stuff like this:
>
> Object::connect: Use the SLOT or SIGNAL macro to connect
> BTMainWindow::loadTrace()
>
> So I went looking in the Qt Headers and found this in qobjectdefs.h:
> #ifndef QT_NO_DEBUG
> # define QLOCATION "\0"__FILE__":"QTOSTRING(__LINE__)
> # define METHOD(a)   qFlagLocation("0"#a QLOCATION)
> # define SLOT(a)     qFlagLocation("1"#a QLOCATION)
> # define SIGNAL(a)   qFlagLocation("2"#a QLOCATION)
> #else
> # define METHOD(a)   "0"#a
> # define SLOT(a)     "1"#a
> # define SIGNAL(a)   "2"#a
> #endif
>
> So in order to fake the SLOT macro, just prepend "1" to your string
> and pass it to QObject::connect.
>
> Now to my way of thinking, this is an evil peeking-behind-the-curtain
> sort of thing to do -- what if some future version of Qt needs to
> change the SLOT macro?Any code faking SLOT will stop working.
>
> So my question is this: is there a non-evil way to get around SLOT()
> requiring a string literal instead of a char * variable?
>




More information about the Qt-interest-old mailing list