Freiza
Freiza

Reputation: 77

Why is slot passed as string? Qt

 private:
     Button *createButton(const QString &text, const char *member);
     void abortOperation();
     bool calculate(double rightOperand, const QString &pendingOperator);

Button *pointButton = createButton(tr("."), SLOT(pointClicked()));

In qt's calculator example: http://qt-project.org/doc/qt-4.8/widgets-calculator.html

The createButton member function takes two constant string. Then why we are passing slots to them as a second argument?

Upvotes: 0

Views: 305

Answers (1)

David D
David D

Reputation: 1591

Simplest summary: The create button function allocates a new button, sets the text, and then connects that button's clicked signal to the slot represented with the string you sent in.

     Button *Calculator::createButton(const QString &text, const char *member)
     {
         Button *button = new Button(text);

//NOTE right here it uses the string you passed in - BEGIN
         connect(button, SIGNAL(clicked()), this, member);
//NOTE right here it uses the string you passed in - END
         return button;
     }

A little bit more detail as to why the signal and slot macros are compatable with strings like this (per this previous stack overflow post):

As Neil said, the SLOT and SIGNAL macros are defined as

> #define SLOT(a) "1"#a
> #define SIGNAL(a) "2"#a 

The #a (with # a stringizing operator) will simply turn whatever is put within the parentheses into a string literal, to create names from the signatures provided to the macros. The "1" and "2" are merely there to distinguish between slots and signals.

This earlier post should provide you some more insight.

If you wonder about the "why?" of all this macro stuff and preprocessing, I would suggest you read up on the "Meta-Object-Compiler" or MOC. And just for fun you could have a look at what MOC does to the code you provide it with. Look through its output and see what it contains. That should be quite informative.

In short, this preprocessing through MOC allows Qt to implement some features (like the signals and slots) which C++ does not provide as standard. (Although there are arguably some implementations of this concept, not related to Qt, which don't require a Meta Object Compiler)

Hope that helps.

Please note the post I linked has other links of value, that didn't come through with the copy and paste.

Upvotes: 2

Related Questions