ComboBoxWidget::ComboBoxWidget()
{
ui->setupUi(this);
//安装过滤器
ui->comboBox->installEventFilter(this);
//下拉列表
m_listWidget = new QListWidget;
ui->comboBox->setModel(m_listWidget->model());
ui->comboBox->setView(m_listWidget);
ui->comboBox->setEditable(true);
ui->comboBox->lineEdit()->setReadOnly(true);
connect(ui->comboBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(slot_curTextChanged(const QString &)));
connect(m_listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(slot_itemClicked(QListWidgetItem *)));
}
//禁用鼠标点击,滚轮事件
bool ComboBoxWidget::eventFilter(QObject *watched, QEvent *event)
{
if (watched == ui->comboBox)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick)
{
if (ui->comboBox == NULL || ui->comboBox->isVisible() == false)
{
return true;
}
}
else if (event->type() == QEvent::Wheel)
{
return true;
}
}
return QWidget::eventFilter(watched, event);
}
//下拉列表添加表项
void ComboBoxWidget::addItem(const QString& text)
{
QListWidgetItem *item = new QListWidgetItem;
item->setFlags(Qt::ItemFlag::ItemIsEnabled | Qt::ItemFlag::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked);
item->setText(text);
m_listWidget->addItem(item);
}
//点击表项,自动勾选
void ComboBoxWidget::slot_itemClicked(QListWidgetItem *item)
{
ui->comboBox->blockSignals(true);
Qt::CheckState state = item->checkState();
if (state == Qt::Checked)
{
state = Qt::Unchecked;
}
else
{
state = Qt::Checked;
}
item->setCheckState(state);
ui->comboBox->blockSignals(false);
//更新当前text
//……
}