我应该怎么做才能使用自定义类对象的 QVector 将信号发送到插槽

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

本文关键字:QVector 信号 插槽 对象 自定义 我应该      更新时间:2023-10-16

我应该怎么做才能将信号发送到带有QVector自定义类对象作为参数的插槽?

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

用法

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

可以执行以下操作吗?

#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();
}

在这种情况下,我应该同时使用Q_DECLARE_METATYPE宏和qRegisterMetaType函数吗?

当尝试传递对象的Qt容器时,我最担心的事情是确保容器中的对象不会超出范围。 如果内容是简单或简单的类型,则不需要这样做。

我更喜欢在堆上制作项目(使用 new (,并传递指针容器。 然后我确保在其生命周期结束时正确清理它们......经常使用qDeleteAll(). 它需要预先进行更多的计划,但以后会减少很多错误。

我也喜欢确保我为工作使用正确的容器。 就像使用 QSet 而不是 QVector 一样,甚至只是使用 QList 可能是有意义的。 但是,您可能需要实现一个比较运算符来使其可以比较和排序对象。

另一条建议是,小心在你的qRegisterMetaType或任何声明中>>。 在中间添加一个空格,这样就不会模棱两可。 qRegisterMetaType< QVector<LicenseInfo> >();(注意夸张的空格(。

希望有帮助。