简体   繁体   中英

Qt SLOT macro used as function argument

I'm going through the calculator example that was installed with Qt 5.1.1 and there is a private function used to create button widgets (Button inherits QToolButton):

Button *Calculator::createButton(const QString &text, const char *member)
{
    Button *button = new Button(text);
    connect(button, SIGNAL(clicked()), this, member);
    return button;
}

The example calls the above function to create several different buttons eg:

createButton(tr("Clear"), SLOT(clear()));

Where void clear() was declared as a private slot. I understand what the code is trying to do but I want to know why does passing SLOT(clear()) as the const char *member work. I can't seem to find much online that would explain using SLOT like that.

As you can see in the documentation of the connect method , the function signature expects the const char* type. These are the corresponding defines from QtCore:

Q_CORE_EXPORT const char *qFlagLocation(const char *method);
...
# define SLOT(a) qFlagLocation("1"#a QLOCATION)
# define SIGNAL(a) qFlagLocation("2"#a QLOCATION)

It is a bit more complex and you can see the details in here , but I simplified it for the sake of the explanation and understanding.

This "old" signal-slot syntax is basically "string" based, and that is also the fundamental flaw with it. This was fixed in Qt 5, however. It is now closer what you seem to imply with your question so that you would rather expect it to be function or method pointers since you eventually pass such an element to the SLOT and SIGNAL moc tokens.

For completeness, the corresponding SIGNAL and SLOT tokens (ie Q_SLOTS, Q_SIGNALS, etc) are processed by the meta object compiler, aka. moc, the way that it puts those into the ".moc" files. You can see it yourself if you open those files up. For further details, look into the moc source code which can be found in here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM