Search code examples
c++qtsignals-slotsqwidget

Passing custom arguments to a slot in Qt/C++


I'm having some troubles trying to pass a custom widget to a custom slot inside my Qt App.

Here an example of what I need: (Note the slots)

void MainWindow::HttpRequest(const QString & URL, QCustomWidget *Feed) {
    manager = new QNetworkAccessManager(this);
    reply = manager->get(QNetworkRequest(QUrl(URL)));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(HttpImageError(Feed)));
    connect(reply, SIGNAL(finished()), this, SLOT(HttpImageFinished(Feed)));
}

I've already searched on Google and I've found that QSignalMapper is used to pass arguments to slots, but QSignalMapper is usable only to pass integers, QStrings, QObjects and QWidgets. I need to pass a custom widget. I've also read that there are tricks to wrap the custom widget inside a struct or something like that, but I'm very confused on how to do that.

Does anybody can help me?


Solution

  • With Qt 5 and C++11 you can use a new lambda syntax:

    connect(reply, &QNetworkReply::NetworkError, [this, Feed]() {
        this->HttpImageError(Feed);
    });
    

    Here an additional Feed parameter to the slot function is added to lambda capture block.