【问题标题】:Accessing QComboBox index values访问 QComboBox 索引值
【发布时间】:2014-12-05 08:43:20
【问题描述】:

我有一个包含 2 个项目的组合框 - Method01, Method02Method01被选中时,我如何告诉我的代码执行Method01FuncMethod02也是如此?

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

list - [0],[1] 中访问时,我尝试用类似的方式对其进行编码,但我遇到了错误

【问题讨论】:

    标签: python pyqt qcombobox


    【解决方案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_()
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用信号发送当前项目文本:

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

      并在槽中检查:

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

      【讨论】:

        猜你喜欢
        • 2016-08-19
        • 1970-01-01
        • 2021-02-07
        • 2019-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多