以下代码创建一个包含12个下拉项的简单ComboBox。每个项目都分配了一个MyClass()实例 - 变量 myObject 使用
self.ComboBox.addItem( name, myObject ).
使用
将ComboBox本身设置为“可编辑”self.ComboBox.setEditable(True)
由于组合框是可编辑的,因此用户可以直接双击组合框并输入新的文本条目,该文本条目将成为新的Combobox下拉项。问题是键入Combobox的文本只是一个字符串(而所有其他组合框项目都处理了.setData()。是否有任何工作可以确保即使“键入”组合框项目也会分配myClass实例?< / p>
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_())
答案 0 :(得分:0)
这是适用于我的工作解决方案。
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_())