#include "CustomComboBox.h" #include #include CustomComboBox::CustomComboBox(QWidget* parent) : QComboBox(parent), m_firstClick(true) // 默认是第一次点击 { // 启用事件过滤器来处理滚轮事件 this->installEventFilter(this); // 初始化 m_oldIndex 为当前索引 m_oldValue = this->currentIndex(); // 连接 currentIndexChanged 信号,当索引变化时,更新样式 connect(this, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { setEditColor(); // 样式更新 }); } CustomComboBox::~CustomComboBox() {} void CustomComboBox::setEditColor() { // 确保初始化时,m_oldValue 不是 -1,避免第一次调用时应用红色样式 if (m_oldValue == -1) { m_oldValue = this->currentIndex(); // 初始化时,将 m_oldValue 设置为当前索引 } // 根据索引变化来更新样式 if (this->currentIndex() != m_oldValue) { setStyleSheet("color: red;"); // 样式变红 } else { setStyleSheet(""); // 恢复默认样式 } } void CustomComboBox::setCurrentIndexByData(const QVariant& data) { // 使用 findData 查找与给定数据匹配的项的索引 int index = this->findData(data); // 如果找到匹配项,则设置该项为当前选项 if (index != -1) { this->setCurrentIndex(index); // 如果是第一次点击,则保存历史值 if (m_firstClick) { m_oldValue = this->currentIndex(); // 记录当前索引 m_firstClick = false; // 标记为不是第一次点击 } } else { qDebug() << "Data not found in ComboBox!"; } } void CustomComboBox::setSavedColor() { // 恢复默认样式并保存当前选中的索引 m_oldValue = this->currentIndex(); // 保存当前索引 m_firstClick = true; // 标记为是第一次点击 setStyleSheet(""); // 恢复默认样式 } void CustomComboBox::setWheelEnabled(bool enabled) { m_wheelEnabled = enabled; // 设置是否启用滚轮 } void CustomComboBox::setRefreshOnClick(bool enabled) { m_refreshOnClick = enabled; // 设置点击时是否刷新 } bool CustomComboBox::eventFilter(QObject* watched, QEvent* event) { // 如果启用滚轮,并且事件是滚轮事件,阻止其传播 if (!m_wheelEnabled && event->type() == QEvent::Wheel) { return true; // 阻止滚动事件 } return QComboBox::eventFilter(watched, event); // 继续默认事件处理 } void CustomComboBox::showPopup() { // 在弹出菜单时,如果启用了刷新功能,调用自定义刷新函数 if (m_refreshOnClick) { qDebug() << "ComboBox clicked, refreshing..."; // 这里可以放置刷新函数的调用代码 } QComboBox::showPopup(); // 调用父类的 showPopup 以显示下拉菜单 }