I went one-by-one trying each of QVariant methods that starts with 'to':
'toBool', 'toByteArray', 'toChar', 'toDate', 'toDateTime', 'toDouble', 'toEasingCurve', 'toFloat', 'toHash', 'toInt', 'toLine', 'toLineF', 'toList', 'toLocale', 'toLongLong', 'toMap', 'toModelIndex', 'toPoint', 'toPointF', 'toPyObject', 'toReal', 'toRect', 'toRectF', 'toRegExp', 'toSize', 'toSizeF', 'toString', 'toStringList', 'toTime', 'toUInt', 'toULongLong', 'toUrl', 'toUuid'
and I found that toPyObject() returns exactly the same Object (in an example below it is MyClass() instance) stored in a List Item at the time it was created using:
myObject=MyClass()
my_item.setData(QtCore.Qt.UserRole, myObject)
Here is the code that works for me. Please correct me if I am wrong here.
from PyQt4 import QtGui, QtCore
import sys, os
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
def getTime(self):
import datetime
return datetime.datetime.now()
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidget = QtGui.QListWidget()
self.listWidget.currentItemChanged.connect(self.item_clicked)
for i in range(12):
name='Item '+str(i)
my_item=QtGui.QListWidgetItem()
my_item.setText('Item '+str(i))
self.listWidget.addItem(my_item)
myObject=MyClass()
my_item.setData(QtCore.Qt.UserRole, myObject)
myBoxLayout.addWidget(self.listWidget)
Button_01 = QtGui.QPushButton("Get Items")
Button_01.clicked.connect(self.getListItemsFromQListWidget)
myBoxLayout.addWidget(Button_01)
def item_clicked(self, arg=None):
myObject = arg.data(QtCore.Qt.UserRole)
print myObject.toPyObject().getTime()
def getListItemsFromQListWidget(self):
for i in range(self.listWidget.count()):
print self.listWidget.item(i).data(QtCore.Qt.UserRole).toPyObject().getTime()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())