Issue
Generally I set combobox data as follows:
cbo.addItem("xyz",QVariant(1))
-- xyz is value shown in the cbo and 1 is its data
I am setting checkable cbo value from a pyqt model as follows:
model = QtGui.QStandardItemModel(len(cases_array), 1)
for index, case in enumerate(cases_array):
item = QtGui.QStandardItem(case[1])
item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
item.setData(QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
model.setItem(index, 0, item)
cbo.setModel(model)
It works great. But when I do cbo.itemData(0).toPyObject()
I dont get any value.
How can I set cbo data value.
Solution
As the docs points out:
void QComboBox::addItem(const QString &text, const QVariant &userData = QVariant())
Adds an item to the combobox with the given text, and containing the specified userData (stored in the Qt::UserRole). The item is appended to the list of existing items.
The userData is associated with the Qt::UserRole
role so you must use that role (or a larger one).
Considering the above, I have created the following example:
import sys
from PyQt4 import QtCore, QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
cases_array = [
("text1", "data1"),
("text2", "data2"),
("text3", "data3"),
("text4", "data4"),
]
cbo = QtGui.QComboBox()
model = QtGui.QStandardItemModel(0, 1)
for index, (text, data) in enumerate(cases_array):
item = QtGui.QStandardItem(text)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setData(QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
item.setData(data, QtCore.Qt.UserRole)
model.appendRow(item)
cbo.setModel(model)
def on_current_index_changed(index):
text = cbo.itemText(index)
data = cbo.itemData(index, QtCore.Qt.UserRole)
check_state = cbo.itemData(index, QtCore.Qt.CheckStateRole)
print(index, text, data, check_state)
cbo.currentIndexChanged[int].connect(on_current_index_changed)
cbo.show()
sys.exit(app.exec_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.