简体   繁体   中英

What should I do to be able to send signals to slots with QVector of my custom class objects

What should I do to be able to send signals to slots with QVector of my custom class objects as an argument?

struct LicenseInfo
{
    QString company_name;
    QString server_name;
    QString product_name;
    int product_version;
    QString license_end;
    QString last_update;
    QString comment;
};

Usage

connect(_worker, SIGNAL(newLicensesActivated(QVector<LicenseInfo>)),
                 this, SLOT(newLicensesActivated(QVector<LicenseInfo>)));

It is ok to do the following?

#include "licenseinfo.h"

Q_DECLARE_METATYPE(LicenseInfo)

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    qRegisterMetaType<QVector<LicenseInfo>>();

    MainWindow w;
    w.show();

    return a.exec();
}

Should I use both Q_DECLARE_METATYPE macro and qRegisterMetaType function in this case?

The biggest thing I would worry about when trying to pass Qt Containers of objects is to make sure that the objects in the containers don't go out of scope. If the contents are trivial or simple types, this is not necessary.

I prefer to make the items on the heap (using new ), and pass around containers of pointers. Then I make sure I clean them up properly at the end of its lifecycle... often using qDeleteAll() . It requires a little more planning up front, but it reduces a lot of bugs later.

Also I like making sure I am using the right container for the job. Like it might make sense to use a QSet instead of a QVector, or even just use a QList instead. But then you may need to implement a comparison operator to make it so that the objects can be compared and sorted.

Another piece of advice, be careful about having >> in your qRegisterMetaType or in any declaration for that matter. Add a space inbetween so it isn't ambiguous. qRegisterMetaType< QVector<LicenseInfo> >(); (note the exaggerated space).

Hope that helps.

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