• 在QComboBox的基础上实现复选功能


    这个是最近的一个项目上需要实现的功能。要求如下:

    1. 下拉列表的项目可以多选
    2. 显示框不能编辑
    3. 所选中的项目在显示框中出现

    下面根据网上的提示代码(参照博客 一去二三里),主要实现如下代码(与参照略有不同):

    实现方案:

    QListWidget、QListWidgetItem、QComboBox

    初始化控件及模拟数据填充:

     1     comboBox = new QComboBox(this); //初始化显示控件
     2 
     3     QHBoxLayout* mainLayout = new QHBoxLayout(this);
     4     mainLayout->addWidget(comboBox);
     5     setLayout(mainLayout);
     6 
     7     //初始化数据源
     8     listWidget = new QListWidget;
     9     for(int i = 0; i < 5; ++i)
    10     {
    11         QListWidgetItem* item = new QListWidgetItem(tr.("Item %1").arg(i));
    12         item->setCheckState(Qt::Unchecked); //显示复选框
    13 
    14         listWidget->addItem(item);
    15     }
    16 
    17    //默认选中第一个数据
    18     QListWidgetItem* item = listWidget->item(0);
    19     if(item)
    20     {
    21         item->setCheckState(Qt::Checked);
    22     }
    23 
    24     //设置数据源到显示控件中
    25     comboBox->setModel(listWidget->model());
    26     comboBox->setView(listWidget);
    27 
    28     //设置只读编辑框
    29     comboBox->setEditable(true);
    30     QLineEdit* lineEdit = comboBox->lineEdit();
    31     if(lineEdit)
    32     {
    33         lineEdit->setReadOnly(true);
    34     }
    35 
    36     setMinimumWidth(200);
    37 
    38     //更新显示的内容
    39     connect(comboBox, SIGNAL(currentIndexChanged(int)), this,         SLOT(onCurrentIndexChanged(int)));
    View Code

    更新显示内容的代码如下(需要在头文件中设置该函数为槽函数):

     1     //获取当前点击的对象
     2     QListWidgetItem* item = listWidget->item(index);
     3     if(!item)
     4         return ;
     5 
     6     //更新当前点击对象的选中状态
     7     if(item->checkState() == Qt::Unchecked)
     8     {
     9         item->setCheckState(Qt::Checked);
    10     }
    11     else
    12     {
    13         item->setCheckState(Qt::Unchecked);
    14     }
    15 
    16     //循环获取所有选中状态的对象显示文字
    17     QString text;
    18     for(int row = 0, rows = listWidget->count(); row < rows; ++row)
    19     {
    20         QListWidgetItem* item = listWidget->item(row);
    21         if(item && item->checkState() == Qt::Checked)
    22         {
    23             text.append(item->text() + ";");
    24         }
    25     }
    26 
    27     //更新显示控件的文字
    28     comboBox->lineEdit()->setText(text.mid(0, text.size() - 1));
    View Code

    完整的实现代码,请点击 这里

    MultiComboBox文件夹里包含所有的实现文件

  • 相关阅读:
    【证明】—— 二叉树的相关证明
    ubuntu编译安装opencv
    【换句话说】【等价描述】—— 定义及概念的不同描述
    YOLOv3训练自己的数据
    【证明】【一题多解】布尔不等式(union bound)的证明
    机器视觉:MobileNet 和 ShuffleNet
    keras图像风格迁移
    【算法导论】【排序】—— 计数排序(counting sort)
    【等价转换】—— min/max 的转换与互相转换
    卷积神经网络特征图可视化(自定义网络和VGG网络)
  • 原文地址:https://www.cnblogs.com/zhugaopeng/p/8196499.html
Copyright © 2020-2023  润新知