原文 https://blog.csdn.net/liusanping456/article/details/74990395
我做了一些修改:
h文件
C++
#include <QListWidget>
#include <QLineEdit>
#include <QComboBox>
private slots:
......
void stateChanged(int state);
void textChanged(const QString &text);
private:
QListWidget *pListWidget;
QLineEdit *pLineEdit;
QString strSelectedText;
bool bSelected;
};
ccp文件
C++
QString SQL="";
QString ND=mySQL::ND;
SQL=QString("SELECT xmdm,xmmc FROM `hsxm` WHERE type_id='%1' and nd='%2' and length(xmdm)=1 order by xmdm").arg(mySQL::TypeId).arg(ND);
QSqlQuery query(mySQL::cn); //查询 表并输出,测试能否正常操作数据库
query.exec(SQL);
pListWidget = new QListWidget(this);
pLineEdit = new QLineEdit(this);
ui->cmbHSXM->addItem("");
while(query.next()){
QString str=QString("%1 %2").arg(query.value("xmdm").toString().trimmed()).arg(query.value("xmmc").toString().trimmed());
//ui->cmbHSXM->addItem(str);
QListWidgetItem *pItem = new QListWidgetItem(pListWidget);
pListWidget->addItem(pItem);
pItem->setData(Qt::UserRole, str);
QCheckBox *pCheckBox = new QCheckBox(this);
pCheckBox->setText(QStringLiteral("[%1]").arg(str));
pListWidget->addItem(pItem);
pListWidget->setItemWidget(pItem, pCheckBox);
connect(pCheckBox, SIGNAL(stateChanged(int)), this, SLOT(stateChanged(int)));
}
ui->cmbHSXM->setModel(pListWidget->model());
ui->cmbHSXM->setView(pListWidget);
ui->cmbHSXM->setLineEdit(pLineEdit);
pLineEdit->setReadOnly(true); //ui.comboBox->setEditable(true);
connect(pLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString &)));
......
void Formkmxx::stateChanged(int state)
{
int tmpi=state;
tmpi++;
bSelected = true;
QString strSelectedData("");
strSelectedText.clear();
QCheckBox *pSenderCheckBox = nullptr;
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;
delete pSenderCheckBox;
}
void Formkmxx::textChanged(const QString &text)
{
if (!bSelected){
pLineEdit->setText(strSelectedText);
}
QString str=text;
str+="";
}
运行效果图:
发表评论