2014-12-25 26 views
4

用戶輸入的value可以是:字符串或整數。從QVariant到整數和字符串

QAbstractTableModelsetData()方法總是得到這個valueQtCore.QVariant

問題

如何實現if/elif/elsesetData()裏面來區分,如果接收到的QVariant是字符串或整數? (所以使用適當的QVariant轉換方法(例如.toString()或toInt()))

P.有趣的是,試圖轉換QVariant toInt()的結果,以一元組,例如:(0, False)(123, True)

回答

6

You can check against the type

if myVariant.type == QVariant.Int: 
    value = myVariant.toInt() 
elif myVariant.type == QVariant.QString: 
    value = myVariant.toString() 

鑑於上面的形式現在已經過時,則建議to check it this way

if myVariant.canConvert(QMetaType.Int): 
    value = myVariant.toInt() 
elif myVariant.cannConvert(QMetaType.QString) 
    value = myVariant.toString() 
+0

謝謝!簡單,它的作品! :) – alphanumeric

+0

我試圖編輯帖子,但我的修改將少於6個字符,所以我不能。 'QVariant.type'實際上是一種方法,所以第一個例子應該是'if myVariant.type()== QVariant.Int'而不是'if myVariant.type == QVariant.Int' – arainone