如何通过单击 PyQt4 中的按钮更改 QComboBox 值 (python2.7)?

how to change QComboBox value by clicking button in PyQt4 (python2.7)?

我是 PyQt 的初学者。 在 pyqt4:how 中通过单击按钮更改 QComboBox 当前值

我要

点击按钮前:

组合框当前值为 "C",在单击按钮之前(如此图片)

点击按钮后:

组合框当前值必须变成 "Java" 点击按钮后(像这张图)

我怎样才能得到这个? 请用代码告诉我。

谢谢

Qt 有所谓的 'signals' 和 'slots' 让小部件相互通信。每当单击时,QPushButton 都会自动发出信号。在您的代码中,您可以将此信号连接到任何其他小部件的方法(此方法随后变为 'slot')。结果是每次发送信号都会执行slot方法

下面是一段代码,其中连接了 QPushButton clicked 信号和 QComboBox setCurrentIndex 方法。它应该提供您正在寻找的行为:

from PyQt4 import QtGui


class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.init_widgets()
        self.init_connections()


    def init_widgets(self):
        self.button = QtGui.QPushButton(parent=self)
        self.button.setText('Select Java')

        self.combo_box = QtGui.QComboBox(parent=self)
        self.combo_box.addItems(['C', 'Java'])

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.button, 0)
        layout.addWidget(self.combo_box, 1)
        self.setLayout(layout)


    def init_connections(self):
        self.button.clicked.connect(lambda: self.combo_box.setCurrentIndex(1))


qt_application = QtGui.QApplication([])
window = Window()
window.show()
qt_application.exec_()