Reputation: 933
So I have the following function:
void parseData()
{
// DownloadManager and Post subclass QObject
DownloadManager* downloadManager = new DownloadManager();
Post* post = new Post(mPostsModel);
// using qt signal and slots I would like to retrieve the Post in the onFileDownloaded slot
connect(downloadManager, &DownloadManager::allDownloadsFinished, this, &MediaFetcher::onFileDownloaded);
}
Now I would like to get to my Post* post
in my MediaFetcher::onFileDownloaded
slot, something like this:
void MediaFetcher::onFileDownloaded()
{
qDebug() << "files downloaded";
DownloadManager* downloadManager = qobject_cast<DownloadManager*>(sender());
Post* post = getPost(); // how do I get this???
mPostsModel->append(post);
downloadManager->deleteLater();
}
One solution that I think is very ugly (also I think it causes a memory leak) was to use QObject::setProperty and then add my Post*
to the downloadManager
and then get that in the slot (I had use qvariant_cast
). In parseData()
QVariant postVariant = QVariant::fromValue(post);
downloadManager->setProperty("post", postVariant);
Then in onFilesDownloaded()
:
Post* post = qvariant_cast<Post*>(downloadManager->property("post"));
Does anyone know how can this be done in a more elegant way?
Upvotes: 0
Views: 2384
Reputation: 1935
The way I would do this requires either to change the signature of your allDownloadsFinished
signal to pass a Post
:
class downloadManager : public QWidget
{
// Normal constructors and destructor and macros
signals:
void allDownloadsFinished(Post* post);
};
or to add a new signal to downloadManager
to be able to send Post*
. In any case, you'll have to register the Post
meta-type:
qRegisterMetaType<Post*>("Post*");
Obviously, this requires your slot to accept the Post*
type.
Upvotes: 2