【发布时间】:2016-07-27 12:49:42
【问题描述】:
我不知道是否可以将 QVariant 转换为自定义(非 QObject)类 const 指针;例如value() 函数。
official documentation 表示以下内容:
调用 canConvert() 来判断一个类型是否可以转换。如果 值无法转换,默认构造的值将是 返回。
这是我的代码;它位于 QComboBox 的子类中,我正在尝试检索当前数据并将其转换为 const MyClass*:
QVariant var = currentData(); // of the QComboBox
const MyClass* myObject = NULL;
if(var.canConvert<const MyClass *>())
{
cout << "Conversion possible" << endl;
myObject = var.value<const MyClass*>();
}
else
cout << "Conversion impossible!!" << endl;
if(f == NULL)
cout << "null pointer!!" << endl;
else if(myObject->getMyProperty() == 0)
cout << "MyProperty is zero!" << endl;
我已经声明:
Q_DECLARE_METATYPE(const MyClass*)
在 MyClass 标头中。在输出中,我在创建 QComboBox 时得到 "Conversion possible",然后是 "Conversion impossible!!" "null pointer!!",然后,当我实际调用代码 sn-p 中的函数时,我得到的只是:
"Conversion possible"
"MyProperty is zero!"
MyProperty = 0 在 MyClass 的默认构造函数中设置。 QComboBox 中的所有 MyClass 值都将 myProperty 设置为不同于 0 的值。
我的问题是:如果转换是可能的,那么为什么创建的指针指向一个默认构造的值?
编辑:这里是一些额外的重要代码要求; QComboBox 初始化。
void MainWindow::prepareObjects()
{
comboBox = new MyComboBox(this); // this is a member variable and MyComboBox inherits from QComboBox
ObjectList ol; // contains a map of objects already defined
map<QString, const MyClass*> themap = ol.getObjects();
for(map<QString, const MyClass*>::iterator it = themap.begin(); it != themap.end(); ++it)
{
const MyClass myObject = *it->second;
QIcon icon(QPixmap(":/images/objects/" + it->first + ".png"));
comboBox->addItem(icon, myObject.getName(), QVariant::fromValue(&myObject));
}
comboBox->show();
}
【问题讨论】:
-
我不知道这是否能解决您的问题,但我必须另外致电
qRegisterMetaType<MyClass *>("MyClass *");(在 QApplication 之前) -
qRegisterMetaType 值得一试,但 Q_DECLARE_METATYPE 对于 QVariant 来说应该足够了。您是如何将数据添加到组合框的?
-
感谢您的回答。不幸的是,qRegisterMetaType 并没有改善输出。我通过迭代
std::map<QString, const MyClass*>在 QComboBox 中添加了元素。它们已正确添加(我可以打印键和值)。像这样:comboBox->addItem(icon, myObject.getName(), QVariant::fromValue(&myObject)); -
这些代码中存在不连贯性。您应该将您的问题编辑为MCVE
标签: c++ qt pointers casting qt5