C++ (Qt)void QComboBox::showPopup()
C++ (Qt)#include <QtGui> class CustomComboBox : public QComboBox{ Q_OBJECT public: explicit CustomComboBox(QWidget *parent = nullptr) : QComboBox(parent) { } void showPopup() override { int itemsCount = count(); QString longestText; for(int i = 0; i < itemsCount; ++i) { QString text = itemText(i); longestText = longestText.size() < text.size() ? text : longestText; } QFontMetrics fm(font()); int textSize = fm.width(longestText); view()->setMinimumWidth(textSize + (iconSize().width() * 2)); QComboBox::showPopup(); } protected: void paintEvent(QPaintEvent *event) override { Q_UNUSED(event) QStylePainter painter(this); QStyleOptionComboBox opt; initStyleOption(&opt); painter.drawComplexControl(QStyle::CC_ComboBox, opt); const QRect displayRectDelta(3, 3, -21, -5); QRect textRect = rect().adjusted(displayRectDelta.left(), displayRectDelta.top(), displayRectDelta.right(), displayRectDelta.bottom()); painter.fillRect(textRect, Qt::white); QSize defaultIconSize = iconSize(); int index = currentIndex(); QIcon icon = itemIcon(index); if(!icon.isNull()) { int iconLeft = ((textRect.width() - defaultIconSize.width()) / 2) + textRect.left(); int iconTop = ((textRect.height() - defaultIconSize.height()) / 2) + textRect.top(); int iconWidth = defaultIconSize.width() < textRect.width() ? defaultIconSize.width() : textRect.width(); int iconHeight = defaultIconSize.height() < textRect.height() ? defaultIconSize.height() : textRect.height(); iconTop = iconTop < textRect.top() ? textRect.top() : iconTop; if(isEditable()) { painter.drawPixmap(QRect(textRect.left(), iconTop, iconWidth, iconHeight), icon.pixmap(defaultIconSize)); } else { iconLeft = iconLeft < textRect.left() ? textRect.left() : iconLeft; painter.drawPixmap(QRect(iconLeft, iconTop, iconWidth, iconHeight), icon.pixmap(defaultIconSize)); } } }}; int main (int argc, char** argv){ QApplication app(argc,argv); CustomComboBox cb; cb.addItem(QIcon("linux.jpg"), "Linux Linux Linux"); cb.addItem(QIcon("macos.jpg"), "MacOS MacOS MacOS MacOs"); cb.addItem(QIcon("windows.jpg"), "Windows Windows Windows Windows Windows"); cb.show(); return app.exec();} #include "main.moc"