CustomComboBox.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "CustomComboBox.h"
  2. #include <QWheelEvent>
  3. #include <QDebug>
  4. CustomComboBox::CustomComboBox(QWidget* parent)
  5. : QComboBox(parent),
  6. m_firstClick(true) // 默认是第一次点击
  7. {
  8. // 启用事件过滤器来处理滚轮事件
  9. this->installEventFilter(this);
  10. // 初始化 m_oldIndex 为当前索引
  11. m_oldValue = this->currentIndex();
  12. // 连接 currentIndexChanged 信号,当索引变化时,更新样式
  13. connect(this, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
  14. setEditColor(); // 样式更新
  15. });
  16. }
  17. CustomComboBox::~CustomComboBox() {}
  18. void CustomComboBox::setEditColor()
  19. {
  20. // 确保初始化时,m_oldValue 不是 -1,避免第一次调用时应用红色样式
  21. if (m_oldValue == -1) {
  22. m_oldValue = this->currentIndex(); // 初始化时,将 m_oldValue 设置为当前索引
  23. }
  24. // 根据索引变化来更新样式
  25. if (this->currentIndex() != m_oldValue) {
  26. setStyleSheet("color: red;"); // 样式变红
  27. }
  28. else {
  29. setStyleSheet(""); // 恢复默认样式
  30. }
  31. }
  32. void CustomComboBox::setCurrentIndexByData(const QVariant& data)
  33. {
  34. // 使用 findData 查找与给定数据匹配的项的索引
  35. int index = this->findData(data);
  36. // 如果找到匹配项,则设置该项为当前选项
  37. if (index != -1) {
  38. this->setCurrentIndex(index);
  39. // 如果是第一次点击,则保存历史值
  40. if (m_firstClick) {
  41. m_oldValue = this->currentIndex(); // 记录当前索引
  42. m_firstClick = false; // 标记为不是第一次点击
  43. }
  44. }
  45. else {
  46. qDebug() << "Data not found in ComboBox!";
  47. }
  48. }
  49. void CustomComboBox::setSavedColor()
  50. {
  51. // 恢复默认样式并保存当前选中的索引
  52. m_oldValue = this->currentIndex(); // 保存当前索引
  53. m_firstClick = true; // 标记为是第一次点击
  54. setStyleSheet(""); // 恢复默认样式
  55. }
  56. void CustomComboBox::setWheelEnabled(bool enabled)
  57. {
  58. m_wheelEnabled = enabled; // 设置是否启用滚轮
  59. }
  60. void CustomComboBox::setRefreshOnClick(bool enabled)
  61. {
  62. m_refreshOnClick = enabled; // 设置点击时是否刷新
  63. }
  64. bool CustomComboBox::eventFilter(QObject* watched, QEvent* event)
  65. {
  66. // 如果启用滚轮,并且事件是滚轮事件,阻止其传播
  67. if (!m_wheelEnabled && event->type() == QEvent::Wheel) {
  68. return true; // 阻止滚动事件
  69. }
  70. return QComboBox::eventFilter(watched, event); // 继续默认事件处理
  71. }
  72. void CustomComboBox::showPopup()
  73. {
  74. // 在弹出菜单时,如果启用了刷新功能,调用自定义刷新函数
  75. if (m_refreshOnClick) {
  76. qDebug() << "ComboBox clicked, refreshing...";
  77. // 这里可以放置刷新函数的调用代码
  78. }
  79. QComboBox::showPopup(); // 调用父类的 showPopup 以显示下拉菜单
  80. }