2014-12-25 5 views
4

사용자가 입력 한 value은 문자열 또는 정수일 수 있습니다.QVariant에서 정수 및 문자열로

어떻게 수신 QVariant이 문자열이나 정수의 경우 구분하기 setData()의 내부 if/elif/else을 구현하기 :

QAbstractTableModelsetData() 방법은 항상이 value 질문

QtCore.QVariant으로 얻는다? (따라서 QVariant 변환 방법 (예 : .toString() 또는 toint())이 사용됩니다.

P.s. (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 :

) 시도가 QVariant toInt을 (변환 할 수 있다는 흥미로운 같은 조의 결과
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

관련 문제