Python:如何处理可编辑的ComboBox以存储对象(数据)
下面的代码创建了一个简单的下拉框(ComboBox),里面有12个可选项。每个选项都关联了一个MyClass()的实例,也就是变量myObject,通过以下方式实现:
self.ComboBox.addItem( name, myObject ).
这个下拉框被设置为“可编辑”,使用了:
self.ComboBox.setEditable(True)
因为下拉框是可编辑的,所以用户可以直接双击下拉框,输入新的文本,这样就会生成一个新的下拉框选项。问题是,用户在下拉框中输入的文本只是一个字符串,而其他的下拉框选项都有经过.setData()处理。有没有办法确保即使是“手动输入”的下拉框选项也能关联到myClass的实例呢?
from PyQt4 import QtGui, QtCore
import sys, os
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
self.myAttr=None
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.ComboBox = QtGui.QComboBox()
self.ComboBox.setEditable(True)
for i in range(12):
name='Item '+str(i)
myObject=MyClass()
self.ComboBox.addItem( name, myObject )
self.ComboBox.currentIndexChanged.connect(self.combobox_selected)
myBoxLayout.addWidget(self.ComboBox)
def combobox_selected(self, index):
myObject=self.ComboBox.itemData(index).toPyObject()
print myObject.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_())
1 个回答
1
这是一个对我有效的解决方案。
from PyQt4 import QtGui, QtCore
import sys, os
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
self.myAttr=None
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.ComboBox = QtGui.QComboBox()
self.ComboBox.setEditable(True)
for i in range(12):
name='Item '+str(i)
myObject=MyClass()
self.ComboBox.addItem( name, myObject )
self.ComboBox.currentIndexChanged.connect(self.combobox_selected)
myBoxLayout.addWidget(self.ComboBox)
def combobox_selected(self, index):
itemName=self.ComboBox.currentText()
myObject=self.ComboBox.itemData(index).toPyObject()
if not hasattr(myObject, 'getTime'):
result=self.ComboBox.blockSignals(True)
self.ComboBox.removeItem(index)
myObject=MyClass()
self.ComboBox.addItem( itemName, myObject )
self.ComboBox.setCurrentIndex( index )
self.ComboBox.blockSignals(False)
print myObject.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_())