如何在QComboBox上实现多选

本文介绍了如何在QComboBox上实现多选功能。QComboBox由QLineEdit和QComboBoxListView组成,通过QStandardItemModel来管理数据。文章提出了两种实现多选的方法:一是通过设置QStandardItem的可勾选性,但存在一些控制问题;二是利用QAbstractItemView的setIndexWidget结合QCheckBox,这种方法能更好地控制状态,且不会自动收起下拉列表。最后,文章提供了一个名为MultiCombo的自定义类,继承自QComboBox,并详细说明了其实现过程,包括如何替换LineEdit、添加元素、更新LineEdit内容以及重写hidePopup和resizeEvent函数。
摘要由CSDN通过智能技术生成

1. QComboBox的底层实现

QComboBox底层是由QLineEdit和QComboBoxListView组成的。其中对QLineEdit和QComboBoxListView数据的管理则是通过QComboBoxPrivate类来处理。在QComboBoxPrivate中有个QComboBoxPrivateContainer* viewContainer();函数用于初始化QComboBox的view,其实现如下:

QComboBoxPrivateContainer* QComboBoxPrivate::viewContainer()
{
    if (container)
        return container;

    Q_Q(QComboBox);
    container = new QComboBoxPrivateContainer(new QComboBoxListView(q), q);
    container->itemView()->setModel(model);
    container->itemView()->setTextElideMode(Qt::ElideMiddle);
    updateDelegate(true);
    updateLayoutDirection();
    updateViewContainerPaletteAndOpacity();
    QObject::connect(container, SIGNAL(itemSelected(QModelIndex)),
                     q, SLOT(_q_itemSelected(QModelIndex)));
    QObject::connect(container->itemView()->selectionModel(),
                     SIGNAL(currentChanged(QModelIndex,QModelIndex)),
                     q, S
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值