简体   繁体   English

访问QComboBox索引值

[英]Accessing QComboBox index values

I have a comboxbox which contains 2 items - Method01, Method02 How can I tell my code to execute Method01Func when Method01 is selected, likewise for Method02 too? 我有一个包含2项comboxbox - Method01, Method02我怎么能告诉我的代码来执行Method01FuncMethod01选择,也为Method02呢?

self.connect(self.exportCombo, SIGNAL('currentIndexChanged(int)'), self.Method01Func)

I tried to code it in something similar when accessing in a list - [0],[1]... but I was bumped with errors list访问[0],[1] ...时,我尝试用类似的方式对其进行编码,但是我被错误所困扰

One way to do it is to make use of the userData parameter when calling addItem() , and pass in a reference to the function you want that item to call. 一种实现方法是在调用addItem()时使用userData参数,并将引用传递给您希望该项目调用的函数。

Here's a simple example: 这是一个简单的例子:

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_()

alternatively You can send the current items text with the signal: 或者,您可以通过信号发送当前项目文本:

self.exportCombo.currentIndexChanged[str].connect(self.execute_method)

and check it in the slot: 并在插槽中检查它:

def execute_method(self, text):
    (self.Method01Func() if text == 'Method01' else self.Method02Func())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM