python - 访问 QComboBox 索引值

标签 python pyqt qcombobox

我有一个组合框,其中包含 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/

相关文章:

python - 条件值设置的有效方法

python - 如何在纯 python 或 : How to bind the key left of the [1] to a shortcut in Qt 中从硬件键号/扫描码获取实际键名

c++ - Qt - 如何使用 QComboBox 更改 QTextEdit 的字体大小

c++ - QComboBox EventFilter 弹出

python - 如何恢复 QTableView 中 QComboBox 委托(delegate)的索引?

python - 范围生成器 `r_` - 具有复杂(但不是虚构)步骤的切片;使用幅度

python - 如何在 python nmap 中提供 inputfilefile(-iL) 选项?

python - 如何将 Qt Quick 中的按钮绑定(bind)到 Python PyQt 5

python - 表达式的字典列表

python - 从 .ui 访问元素