【发布时间】:2017-05-05 13:15:49
【问题描述】:
我是 PyQt 的初学者。 在pyqt4中:如何通过点击按钮改变QComboBox当前值
我想要
点击按钮前:
组合框当前值为“C”,在单击按钮之前(如此图)
点击按钮后:
点击按钮后,组合框当前值必须变为“Java”(如图)
我怎样才能得到这个? 请用代码告诉我。
谢谢
【问题讨论】:
标签: python button combobox pyqt pyqt4
我是 PyQt 的初学者。 在pyqt4中:如何通过点击按钮改变QComboBox当前值
我想要
点击按钮前:
组合框当前值为“C”,在单击按钮之前(如此图)
点击按钮后:
点击按钮后,组合框当前值必须变为“Java”(如图)
我怎样才能得到这个? 请用代码告诉我。
谢谢
【问题讨论】:
标签: python button combobox pyqt pyqt4
Qt 具有所谓的“信号”和“插槽”,可以让小部件相互通信。每当单击 QPushButton 时,它都会自动发出信号。在您的代码中,您可以将此信号连接到任何其他小部件的方法(然后此方法成为“插槽”)。结果就是每次发送信号都会执行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_()
【讨论】: