customcombobox.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "customcombobox.h"
  2. #include <QApplication>
  3. #include <QGraphicsDropShadowEffect>
  4. #include <QListView>
  5. #include <QDebug>
  6. #include <QStyleFactory>
  7. #include <QWheelEvent>
  8. CustomComboBox::CustomComboBox(QWidget *parent)
  9. : QComboBox(parent)
  10. {
  11. }
  12. CustomComboBox::~CustomComboBox()
  13. {
  14. }
  15. /* 设置下拉框阴影 */
  16. void CustomComboBox::setViewShadowEffect()
  17. {
  18. /* 设置这个样式,在Linux下才不会出现白色背景 */
  19. setStyle(QStyleFactory::create("Windows"));
  20. setView(new QListView());
  21. if (nullptr != view() && nullptr != view()->window())
  22. {
  23. view()->window()->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
  24. view()->window()->setAttribute(Qt::WA_TranslucentBackground);
  25. QGraphicsDropShadowEffect *pShadowEffect = new QGraphicsDropShadowEffect(this);
  26. pShadowEffect->setBlurRadius(LISTVIEW_MARGIN); // 模糊度
  27. pShadowEffect->setColor(QColor(0, 0, 0, 90)); // 阴影的颜色
  28. pShadowEffect->setOffset(0, 0); // 水平和垂直偏移量
  29. view()->setGraphicsEffect(pShadowEffect);
  30. QApplication::setEffectEnabled(Qt::UI_AnimateCombo, false);
  31. }
  32. }
  33. void CustomComboBox::showPopup()
  34. {
  35. QComboBox::showPopup();
  36. if (nullptr != view()) {
  37. view()->setMinimumWidth(width() + LISTVIEW_MARGIN * 2);
  38. }
  39. QWidget *popup = findChild<QFrame*>();
  40. if (nullptr != popup) {
  41. popup->move(mapToGlobal(QPoint(-LISTVIEW_MARGIN, height() - LISTVIEW_MARGIN + 4)));
  42. }
  43. }
  44. void CustomComboBox::wheelEvent(QWheelEvent *event)
  45. {
  46. if (m_wheelDisabled) {
  47. event->ignore(); // 禁用滚轮修改内容
  48. } else {
  49. QComboBox::wheelEvent(event); // 正常处理滚轮事件
  50. }
  51. }