简体   繁体   中英

How do I get a signal to call a function with certain arguments?

I want to get a signal to call a function with certain arguments, like the example below.


QPushButton *yes = new QPushButton("Yes");
yes->connect(yes, SIGNAL(clicked()), NULL, SLOT(printf("You pressed a button")));

How do I accomplish this?

An often overlooked way to reverse signal/slot relationships is QObject::sender . You can call it in the receiving slot to get a handle on the QPushButton (using qobject_cast ) and get the text from there. Alternatively you can use QSignalMapper to augment signals.

It seems very inefficient but you could create a new signal with a QString argument, which you connect to your pushbutton. The text contained will be defined on your emit call.

eg.

connect(yes, SIGNAL(clicked()), this, SLOT(emitHelloWorldText());
connect(this, SIGNAL(emitText(QString)), receiver, SLOT(dostuffWithText(QString)));

then your emitHelloWorldText method can be something like

void emitHelloWorldText() {
    emit emitText("Hello world");
}

Then this can be picked up by your receiver class

void doStuffWithText(const QString &text) {

Unfortunately, the slot and the signal must have matching arguments. If you really need to stick with this interface, you could create an intermediary slot to propagate the received signal, but there's no real way around.

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