| 1 | /* |
| 2 | * Copyright (C) 2020-2022 Roy Qu (royqh1979@gmail.com) |
| 3 | * |
| 4 | * This program is free software: you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation, either version 3 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | */ |
| 17 | #ifndef QPATCHEDCOMBOBOX_H |
| 18 | #define QPATCHEDCOMBOBOX_H |
| 19 | |
| 20 | #include <QComboBox> |
| 21 | #include <QListView> |
| 22 | #include <QPaintEvent> |
| 23 | #include <QPainter> |
| 24 | |
| 25 | class QPatchedComboBoxListView : public QListView |
| 26 | { |
| 27 | Q_OBJECT |
| 28 | public: |
| 29 | QPatchedComboBoxListView(QComboBox *cmb = nullptr) : combo(cmb) {} |
| 30 | |
| 31 | protected: |
| 32 | void resizeEvent(QResizeEvent *event) override |
| 33 | { |
| 34 | resizeContents(viewport()->width(), contentsSize().height()); |
| 35 | QListView::resizeEvent(event); |
| 36 | } |
| 37 | |
| 38 | QStyleOptionViewItem viewOptions() const override |
| 39 | { |
| 40 | QStyleOptionViewItem option = QListView::viewOptions(); |
| 41 | option.showDecorationSelected = true; |
| 42 | // if (combo) |
| 43 | // option.font = combo->font(); |
| 44 | return option; |
| 45 | } |
| 46 | |
| 47 | void paintEvent(QPaintEvent *e) override |
| 48 | { |
| 49 | if (combo) { |
| 50 | QStyleOptionComboBox opt; |
| 51 | opt.initFrom(combo); |
| 52 | opt.editable = combo->isEditable(); |
| 53 | if (combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo)) { |
| 54 | //we paint the empty menu area to avoid having blank space that can happen when scrolling |
| 55 | QStyleOptionMenuItem ; |
| 56 | menuOpt.initFrom(this); |
| 57 | menuOpt.palette = palette(); |
| 58 | menuOpt.state = QStyle::State_None; |
| 59 | menuOpt.checkType = QStyleOptionMenuItem::NotCheckable; |
| 60 | menuOpt.menuRect = e->rect(); |
| 61 | menuOpt.maxIconWidth = 0; |
| 62 | menuOpt.tabWidth = 0; |
| 63 | QPainter p(viewport()); |
| 64 | combo->style()->drawControl(QStyle::CE_MenuEmptyArea, &menuOpt, &p, this); |
| 65 | } |
| 66 | } |
| 67 | QListView::paintEvent(e); |
| 68 | } |
| 69 | |
| 70 | private: |
| 71 | QComboBox *combo; |
| 72 | }; |
| 73 | |
| 74 | class QPatchedComboBox : public QComboBox |
| 75 | { |
| 76 | Q_OBJECT |
| 77 | public: |
| 78 | explicit QPatchedComboBox(QWidget *parent = nullptr); |
| 79 | }; |
| 80 | |
| 81 | #endif // QPATCHEDCOMBOBOX_H |
| 82 | |