Reputation: 117
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?
Upvotes: 2
Views: 3747
Reputation: 117
Just for further information... I found another solution to the problem, in fact to pass a custom widget I've subclassed the QSignalMapper class (I haven't studied OOP at the University yet, so be patient with me! :P), here some code:
QCustomMapper.h
#ifndef QCUSTOMMAPPER_H
#define QCUSTOMMAPPER_H
#include <QSignalMapper>
#include <QHash>
#include "customwidget.h"
class QCustomMapper : public QSignalMapper
{
Q_OBJECT
public:
explicit QCustomMapper(QObject *parent = 0);
void setMapping(QObject *sender, CustomWidget *customWidget);
void removeMappings(QObject *sender);
QHash<QObject *, CustomWidget *> customHash;
Q_SIGNALS:
void mapped(CustomWidget *);
public slots:
void senderDestroyed() {
removeMappings(sender());
}
void map(QObject *sender);
void map();
};
#endif // QCUSTOMMAPPER_H
QCustomMapper.cpp
#include "qcustommapper.h"
QCustomMapper::QCustomMapper(QObject *parent) : QSignalMapper(parent) {
}
void QCustomMapper::setMapping(QObject *sender, CustomWidget *customWidget) {
customHash.insert(sender, customWidget);
connect(sender, SIGNAL(destroyed()), this, SLOT(senderDestroyed()));
}
void QCustomMapper::removeMappings(QObject *sender) {
customHash.remove(sender);
}
void QCustomMapper::map(QObject *sender) {
if (customHash.contains(sender)) {
emit mapped(customHash.value(sender));
}
}
void QCustomMapper::map() {
map(sender());
}
NOTE: I don't know if this is an "elegant" method or if the subclassing is done correctly.. (I've done it without the right knoledgments) anyway it's working fine for me! (miracles happen :D) I hope that this post will help someone that has the same problem!
Bye, Matteo.
Upvotes: 2
Reputation: 11880
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.
Upvotes: 5