2016-07-27 63 views
0

我不知道是否可以將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(); 
} 
+0

我不知道是否能解決你的問題,但我不得不打電話'qRegisterMetaType (「MyClass的*」);'另外(之前的QApplication) – nidomiro

+0

qRegisterMetaType是值得嘗試,但Q_DECLARE_METATYPE應的QVariant是不夠的。你是如何將數據添加到組合框的? – wasthishelpful

+0

謝謝你的回答。不幸的是,qRegisterMetaType不會改進輸出。我通過在'std :: map '上迭代來添加QComboBox中的元素。它們被正確添加(我可以打印鍵和值)。像這樣:'comboBox-> addItem(icon,myObject.getName(),QVariant :: fromValue(&myObject));' – Ety

回答

0

問題是,不像我以爲,在QComboBox初始化(編輯問題與相應的代碼)。第一部分代碼(QVariant演員)工作正常。

將項目添加到地圖中的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插槽中;這是問題中的第一部分代碼來自哪裏。

所以我仍然沒有對此有一個準確的答案:

如果轉換是可能的,那麼爲什麼指針創建點 的缺省構造值?

除了我認爲默認構造的值是一個狂放的或懸空的指針。

相關問題