簡體   English   中英

更改后的pyQT Combobox打印輸出

[英]pyQT Combobox print output upon changed

我想基於哪個combox和combox中的哪一行創建一個事件(在這種情況下為打印)。 我看了一下這個舊帖子並做了一些擴展。 有道理嗎? 當我在左側組合框中按下“第二”時,我想要輸出“ 0,2”,而當我在右側組合框中按下“第二”時,我想要輸出“ 1、2”。

from PyQt4 import QtCore, QtGui
import sys


class MyClass(object):
    def __init__(self, arg):
        super(MyClass, self).__init__()
        self.row = arg
        self.col = []

    def add_column(self, col):
        self.col.append(col)


class myWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)
        comboBox = [None, None]
        myObject = [None, None]
        slotLambda = [None, None]
        for j in range(2):
            comboBox[j] = QtGui.QComboBox(self)
            if j > 0:
                comboBox[j].move(100, 0)
            test = [['first', 1], ['second', 2]]
            myObject[j] = MyClass(j)
            for num, value in test:
                comboBox[j].addItem(num)
                myObject[j].add_column(value)
                slotLambda[j] = lambda: self.indexChanged_lambda(myObject[j])
            comboBox[j].currentIndexChanged.connect(slotLambda[j])

    @QtCore.pyqtSlot(str)
    def indexChanged_lambda(self, string):
        print string.row, string.col

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myApp')
    dialog = myWindow()
    dialog.show()
    sys.exit(app.exec_())

這是沒有必要使用lambda函數來發送額外的信息,如果QComboBox被使用, QComboBox可以存儲信息為每個索引, addItem()具有其中能夠保存的信息的附加參數,我們可以通過訪問它itemData()的方法,我們可以使用setItemData()方法添加其他信息。

要知道QComboBox發出了信號,我們可以使用sender() ,此方法返回發出信號的對象。

以下示例實現了以上所有內容:

from PyQt4 import QtCore, QtGui
import sys

class myWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)

        lay = QtGui.QHBoxLayout(self)
        test = [['first', 1], ['second', 2]]

        for j in range(5):
            comboBox = QtGui.QComboBox(self)
            lay.addWidget(comboBox)
            for i, values in enumerate(test):
                text, data = values
                comboBox.addItem(text, (j, data))
            comboBox.currentIndexChanged.connect(self.onCurrentIndexChanged)

    @QtCore.pyqtSlot(int)
    def onCurrentIndexChanged(self, ix):
        combo = self.sender()
        row, column = combo.itemData(ix)
        print(row, column)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myApp')
    dialog = myWindow()
    dialog.show()
    sys.exit(app.exec_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM