我不知道是否可以将QVariant转换为自定义(非QObject)类const指针;例如使用value()
函数。
调用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!!"
,然后,当我实际调用代码片段中的函数时,我得到的是:
"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();
}
答案 0 :(得分:0)
问题是,与我的想法不同,在QComboBox初始化(带有相应代码的编辑问题)。第一段代码(QVariant cast)工作正常。
从地图向QComboBox添加项目的正确方法是:
void MainWindow::prepareObjects()
{
comboBox = new MyComboBox(this);
ObjectList ol;
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; // SAME TYPE AS IN THE MAP AND COMBOBOX
QIcon icon(QPixmap(":/images/objects/" + it->first + ".png"));
comboBox->addItem(icon, myObject->getName(), QVariant::fromValue(myObject)); // no '&'
}
comboBox->show();
}
我的地图和QComboBox存储MyClass*
个项目。我基本上有一个MyClass
类型的中间变量(没有指针),我将对象的值存储在地图中,然后我将其地址用于QComboBox。这在组合框中创建了一个Wild指针,0或随机(巨大)数字作为对象的Integer成员变量,以及QString变量的Segmentation Fault。
我还是不明白,当我尝试在插入它们后直接访问它们时,QComboBox中的值仍然是正确的。问题发生在初始化方法之外的MyComboBox插槽中;这是问题中第一段代码的来源。
所以我仍然没有准确的答案:
如果可以进行转换,那么为什么指针创建指向 到默认构造的值?
除了我认为默认构造的值是狂野或悬空指针。