我不知道是否可以將QVariant轉換爲自定義(非QObject)類const指針;例如使用value()
函數。無法從QCombobox檢索值 - 將QVariant轉換爲const指針
的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的頭
。在輸出中,我得到"Conversion possible"
在創建QComboBox,那麼"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();
}
我不知道是否能解決你的問題,但我不得不打電話'qRegisterMetaType(「MyClass的*」);'另外(之前的QApplication) –
nidomiro
qRegisterMetaType是值得嘗試,但Q_DECLARE_METATYPE應的QVariant是不夠的。你是如何將數據添加到組合框的? – wasthishelpful
謝謝你的回答。不幸的是,qRegisterMetaType不會改進輸出。我通過在'std :: map'上迭代來添加QComboBox中的元素。它們被正確添加(我可以打印鍵和值)。像這樣:'comboBox-> addItem(icon,myObject.getName(),QVariant :: fromValue(&myObject));' –
Ety