convert function return from ‘std::vector<QString>’ to ‘QVariant’

纵饮孤独 提交于 2019-12-08 07:04:29

问题


I am working on a QT based application.One of of my class is a child class of QAbstractTableModel. The data function has a return type of QVariant(Union).But i want to return a custom type std::vector<QString>

Came to know about Q_DECLARE_METATYPE(); It makes new types available to QVariant.

-Test Case Code-

#include <QApplication>
#include <QMetaType>
#include <vector>
#include<QVariant>


Q_DECLARE_METATYPE(std::vector<QString>);

QVariant data(int role)
{
    std::vector<QString> test1;   
    test1.push_back("Dtd");
    test1.push_back("Dtd"); 
    return test1;
}

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

    QApplication app(argc, argv);
     data(1);    
    return app.exec();
}

I am getting this error

error: could not convert ‘test1’ from ‘std::vector< QString >’ to ‘QVariant’

I am missing out something.Please Help


回答1:


Even if you've declared a new metatype, the compiler still sees you're trying to return a std::vector where you've declared returning a QVariant. Try this:

QVariant data(int role)
{
    std::vector<QString> test1;   
    test1.push_back("Dtd");
    test1.push_back("Dtd");
    QVariant var;
    var.setValue(test1); 
    return var;
}


来源:https://stackoverflow.com/questions/9805023/convert-function-return-from-stdvectorqstring-to-qvariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!