而不是使用.addItem("Item Name", "My Data")
来填充QComboBox
我先创建它的项目:
item = QtGui.QStandardItem("Item Name")
然后我设置项目的数据:
item.setData("My data")
问题。如何从currentIndexChanged()
方法内部获取存储在Combo项目中的数据,该方法将单击的ComboBox项目的索引作为参数:
import sys
import PySide.QtCore as QtCore
import PySide.QtGui as QtGui
class MyCombo(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
vLayout=QtGui.QVBoxLayout(self)
self.setLayout(vLayout)
self.combo=QtGui.QComboBox(self)
self.combo.currentIndexChanged.connect(self.currentIndexChanged)
comboModel=self.combo.model()
for i in range(3):
item = QtGui.QStandardItem(str(i))
item.setData('MY DATA' + str(i) )
comboModel.appendRow(item)
vLayout.addWidget(self.combo)
def currentIndexChanged(self, index):
print index
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyCombo()
w.show()
sys.exit(app.exec_())
答案 0 :(得分:2)
import sys
from PySide import QtGui, QtCore
class MyCombo(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
vLayout=QtGui.QVBoxLayout(self)
self.setLayout(vLayout)
self.combo=QtGui.QComboBox(self)
self.combo.currentIndexChanged.connect(self.currentIndexChanged)
comboModel=self.combo.model()
for i in range(3):
item = QtGui.QStandardItem(str(i))
comboModel.appendRow(item)
self.combo.setItemData(i,'MY DATA' + str(i))
vLayout.addWidget(self.combo)
def currentIndexChanged(self, index):
print self.combo.itemData(index)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyCombo()
w.show()
sys.exit(app.exec_())
这应该适合你,我认为
答案 1 :(得分:0)
工作解决方案发布在下面。
使用item.setData()
方法时,我们应指定与Role
相关联的数据。
class MyCombo(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
vLayout=QtGui.QVBoxLayout(self)
self.setLayout(vLayout)
self.combo=QtGui.QComboBox(self)
self.combo.currentIndexChanged.connect(self.currentIndexChanged)
comboModel=self.combo.model()
for i in range(3):
item = QtGui.QStandardItem(str(i))
item.setData('MY DATA' + str(i), QtCore.Qt.UserRole )
comboModel.appendRow(item)
vLayout.addWidget(self.combo)
def currentIndexChanged(self, index):
modelIndex=self.combo.model().index(index,0)
print self.combo.model().data(modelIndex, QtCore.Qt.UserRole)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyCombo()
w.show()
sys.exit(app.exec_())