如何根据QComboBox索引切换控件的启用状态

2 投票
1 回答
10422 浏览
提问于 2025-04-17 13:46

我正在使用 pyQT 4.8.3 来为一个 QGIS 插件创建一个合适的图形用户界面(GUI)。

这个表单里有三个小部件。

my_comboBox , my_lineEdit , my_spinBox

假设这个下拉框(comboBox)里有三个选项。

'combo_first_item' , 'combo_second_item' , 'combo_third_item'

我想要的具体功能是:

if 'combo_second_item' is selected, then my_lineEdit toggles state to disabled
if 'combo_third_item' selected, then my_spinBox toggles state to disabled

那么,我该如何根据下拉框中选中的字符串(或者说索引值)来切换表单中小部件的启用状态呢?

应该如何正确地设置信号和槽的连接呢?和 QbuttonBox 不同,QcomboBox 并不会触发 SetDisabled 这个槽。

谢谢。

1 个回答

4

创建一个字典,把字符串和小部件(widget)对应起来:

widgets = {'combo_first_item': my_comboBox,
           'combo_second_item': my_lineEdit,
           'combo_third_item': my_spinBox}

然后再创建一个槽(slot):

def disableWidget(currentIndex):
     widget = widgets[currentIndex]
     widget.setEnabled(False)
     # or anything else you want to do on the widget

接着,你可以把 currentIndexChanged[QString] 这个信号连接到这个槽上:

comboBox.currentIndexChanged['QString'].connect(disableWidget)

另外,你也可以用 currentIndexChanged[int] 和一个列表来代替字典。

附注:如果这个内容是在一个类的实例里面,记得相应地加上 self

撰写回答