我有一个组合框,其中包含 2 个项目 - Method01、Method02
当选择 Method01
时,如何告诉我的代码执行 Method01Func
,同样对于 Method02
也是如此?
self.connect(self.exportCombo, SIGNAL('currentIndexChanged(int)'), self.Method01Func)
在列表
中访问时,我尝试以类似的方式对其进行编码 - [0],[1]...,但遇到了错误
最佳答案
一种方法是在调用 addItem()
时使用 userData
参数。 ,并传入对您希望该项目调用的函数的引用。
这是一个简单的例子:
import sys
from PyQt4 import QtCore, QtGui
def Method01Func():
print 'method 1'
def Method02Func():
print 'method 2'
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
widget = QtGui.QWidget()
self.combo = QtGui.QComboBox()
self.combo.addItem('Method 1', Method01Func)
self.combo.addItem('Method 2', Method02Func)
self.combo.currentIndexChanged.connect(self.execute_method)
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.combo)
self.setCentralWidget(widget)
@QtCore.pyqtSlot(int)
def execute_method(self, index):
method = self.combo.itemData(index).toPyObject()
method()
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
关于python - 访问 QComboBox 索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26295018/