刚研究出来的QT下拉框中复选框的多选

xiaoxiao2021-02-28  53

#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QListWidget> #include <QLineEdit> #include <QComboBox> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; QListWidget *pListWidget; QLineEdit *pLineEdit; QComboBox *comboBox; QString strSelectedText; bool bSelected; private slots: void stateChanged(int state); void textChanged(const QString &text); }; #endif // MAINWINDOW_H #include "mainwindow.h"#include "ui_mainwindow.h"#include <QListWidgetItem>#include <QCheckBox>#include <QDebug>MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); pListWidget = new QListWidget(this); pLineEdit = new QLineEdit(this); for (int i = 0; i < 5; ++i) { QListWidgetItem *pItem = new QListWidgetItem(pListWidget); pListWidget->addItem(pItem); pItem->setData(Qt::UserRole, i); QCheckBox *pCheckBox = new QCheckBox(this); pCheckBox->setText(QStringLiteral("Qter%1").arg(i)); pListWidget->addItem(pItem); pListWidget->setItemWidget(pItem, pCheckBox); connect(pCheckBox, SIGNAL(stateChanged(int)), this, SLOT(stateChanged(int))); } comboBox = new QComboBox(this); comboBox->setModel(pListWidget->model()); comboBox->setView(pListWidget); comboBox->setLineEdit(pLineEdit); pLineEdit->setReadOnly(true); //ui.comboBox->setEditable(true); connect(pLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString &)));}MainWindow::~MainWindow(){ delete ui;}void MainWindow::stateChanged(int state){ bSelected = true; QString strSelectedData(""); strSelectedText.clear(); QCheckBox *pSenderCheckBox; int nCount = pListWidget->count(); for (int i = 0; i < nCount; ++i) { QListWidgetItem *pItem = pListWidget->item(i); QWidget *pWidget = pListWidget->itemWidget(pItem); QCheckBox *pCheckBox = (QCheckBox *)pWidget; if (pCheckBox->isChecked()) { QString strText = pCheckBox->text(); strSelectedData.append(strText).append(";"); } //所点击的复选框 if (pSenderCheckBox == pCheckBox) { int nData = pItem->data(Qt::UserRole).toInt(); qDebug() << QString("I am sender...id : %1").arg(nData); } } if (strSelectedData.endsWith(";")) strSelectedData.remove(strSelectedData.count() - 1, 1); if (!strSelectedData.isEmpty()) { //ui.comboBox->setEditText(strSelectedData); strSelectedText = strSelectedData; pLineEdit->setText(strSelectedData); pLineEdit->setToolTip(strSelectedData); } else { pLineEdit->clear(); //ui.comboBox->setEditText(""); } bSelected = false;}void MainWindow::textChanged(const QString &text){ if (!bSelected) pLineEdit->setText(strSelectedText);} #include "mainwindow.h"#include <QApplication>int main(int argc, char *argv[]){ QApplication a(argc, argv); MainWindow w; w.show(); return a.exec();}
转载请注明原文地址: https://www.6miu.com/read-77507.html

最新回复(0)