使用PyQt的组合框中的复选框

Abd*_*eer 5 python checkbox qt pyqt qcombobox

我需要实现一个包含CheckBoxes的下拉列表,就像使ComboBox中的条目为CheckBoxes一样。但是QComboBox不接受QCheckBox作为其成员,我找不到任何替代解决方案。我在Qt Wiki上找到了用C ++ 实现的实现,但是不知道如何将其移植到python。

小智 6

使用 Combobox 项目模型,因为项目支持复选框,您只需要将项目标记为可由用户选中,并设置初始 checkState 以使复选框出现(它仅在存在有效状态时才显示)

item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Unchecked)  # causes checkBox to show
Run Code Online (Sandbox Code Playgroud)

这是一个最小的子类示例:

from PyQt5 import QtGui, QtCore, QtWidgets
import sys, os

# subclass
class CheckableComboBox(QtWidgets.QComboBox):
    # once there is a checkState set, it is rendered
    # here we assume default Unchecked
    def addItem(self, item):
        super(CheckableComboBox, self).addItem(item)
        item = self.model().item(self.count()-1,0)
        item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
        item.setCheckState(QtCore.Qt.Unchecked)

    def itemChecked(self, index):
        item = self.model().item(i,0)
        return item.checkState() == QtCore.Qt.Checked

# the basic main()
app = QtWidgets.QApplication(sys.argv)
dialog = QtWidgets.QMainWindow()
mainWidget = QtWidgets.QWidget()
dialog.setCentralWidget(mainWidget)
ComboBox = CheckableComboBox(mainWidget)
for i in range(6):
    ComboBox.addItem("Combobox Item " + str(i))

dialog.show()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)


zku*_*nov 5

当我需要它时,我想出了一个更简单的解决方案(至少没有必要对QCombobox进行子类化)。它为我工作。即创建具有可检查动作的菜单并将其设置为按钮。然后将菜单或操作连接到插槽。

Qt中的代码(还没有使用PyQt,对不起,我希望您可以移植那个,对我来说似乎更容易)是这样的:

QMenu *menu = new QMenu;
QAction *Act1 = new QAction("Action 1", menu);
Act1->setCheckable(true);
QAction *Act2 = new QAction("Action 2", menu);
Act2->setCheckable(true);
menu->addAction(Act1);
menu->addAction(Act2);

QPushButton *btn = new QPushButton("Btn");    
btn->setMenu(menu);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助