這個控件寫了好久了,元老級別的控件之一,開發之初主要是本身的好幾個項目要用到,好比提供一個顏色下拉框設置對應的曲線或者時間顏色,視頻監控項目中常常用到的OSD標籤設置,這個控件的難度係數接近0,初學者都會,其實網上搜索也不少人提供了繪製的方法,就是枚舉QColor::colorNames()拿到全部的內置的顏色,而後生成對應的圖片做爲icon設置到下拉框的item中去,對應icon的寬高由控件自己的寬高決定,本控件繼承自qcombobox控件,徹底保留了該控件的全部特性,同時新增了顏色改變信號,以便用戶使用。linux
#ifndef COMBOBOX_H #define COMBOBOX_H /** * 自定義寬高下拉框控件 做者:feiyangqingyun(QQ:517216493) 2017-4-11 * 1:可設置下拉框元素高度 * 2:可設置下拉框元素寬度 * 3:可設置是否自動調整下拉框元素寬度,根據元素寬高自動調整 */ #include <QComboBox> #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT ComboBox : public QComboBox #else class ComboBox : public QComboBox #endif { Q_OBJECT Q_PROPERTY(int itemWidth READ getItemWidth WRITE setItemWidth) Q_PROPERTY(int itemHeight READ getItemHeight WRITE setItemHeight) Q_PROPERTY(bool autoWidth READ getAutoWidth WRITE setAutoWidth) public: explicit ComboBox(QWidget *parent = 0); protected: void showEvent(QShowEvent *); private: int itemWidth; //元素寬度 int itemHeight; //元素高度 bool autoWidth; //是否自動調整元素寬度 int maxItemWidth; //最大元素寬度 public: int getItemWidth() const; int getItemHeight() const; bool getAutoWidth() const; public Q_SLOTS: void setItemWidth(int itemWidth); void setItemHeight(int itemHeight); void setAutoWidth(bool autoWidth); }; #endif // COMBOBOX_H
#pragma execution_character_set("utf-8") #include "combobox.h" #include "qlistview.h" #include "qdebug.h" ComboBox::ComboBox(QWidget *parent) : QComboBox(parent) { itemWidth = 5; itemHeight = 20; autoWidth = true; this->setView(new QListView()); } void ComboBox::showEvent(QShowEvent *) { if (autoWidth) { //自動計算全部元素,找到最長的元素 QFontMetrics fm = this->fontMetrics(); int count = this->count(); for (int i = 0; i < count; i++) { int textWidth = fm.width(this->itemText(i)); itemWidth = textWidth > itemWidth ? textWidth : itemWidth; } //寬度增長像素,由於有邊距 this->view()->setFixedWidth(itemWidth + 20); } } int ComboBox::getItemWidth() const { return this->itemWidth; } int ComboBox::getItemHeight() const { return this->itemHeight; } bool ComboBox::getAutoWidth() const { return this->autoWidth; } void ComboBox::setItemWidth(int itemWidth) { if (this->itemWidth != itemWidth) { this->itemWidth = itemWidth; if (!autoWidth) { this->view()->setFixedWidth(itemWidth); } } } void ComboBox::setItemHeight(int itemHeight) { if (this->itemHeight != itemHeight) { this->itemHeight = itemHeight; this->setStyleSheet(QString("QComboBox QAbstractItemView::item{min-height:%1px;}").arg(itemHeight)); } } void ComboBox::setAutoWidth(bool autoWidth) { if (this->autoWidth != autoWidth) { this->autoWidth = autoWidth; } }