How to align QComboBox dropdown menu
-
I used QLineEdit to align QCombobox texts to center, but the dropdown menu is still aligned to the left. How can I align it to center?
2nd question. After using QLineEdit, clicking on the text will not popup dropdown menu. I have to click that down-arrow to call the dropdown. Is there a way to pop it up by just clicking the text?
-
If you want to align the texts of a QComboBox to the center, it is not necessary to use a QLineEdit since a QProxyStyle is enough. In the case of the popup, a custom delegate is sufficient:
#include <QtWidgets> class AlignDelegate: public QStyledItemDelegate{ public: AlignDelegate(Qt::Alignment alignment, QObject *parent = nullptr): QStyledItemDelegate(parent), m_alignment(alignment) { } protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const { QStyledItemDelegate::initStyleOption(option, index); option->displayAlignment = m_alignment; } Qt::Alignment m_alignment; }; class AlignComboBoxProxy: public QProxyStyle{ public: using QProxyStyle::QProxyStyle; void drawItemText(QPainter *painter, const QRect &rect, int /*flags*/, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole) const { QProxyStyle::drawItemText(painter, rect, Qt::AlignCenter, pal, enabled, text, textRole); } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QComboBox w; w.setStyle(new AlignComboBoxProxy(w.style())); for(int i=0; i < 10; ++i){ w.addItem(QString("item-%1").arg(i)); } w.setItemDelegate(new AlignDelegate(Qt::AlignCenter, &w)); w.show(); return a.exec(); }
-
@eyllanesc said in How to align QComboBox dropdown menu:
If you want to align the texts of a QComboBox to the center, it is not necessary to use a QLineEdit since a QProxyStyle is enough. In the case of the popup, a custom delegate is sufficient:
#include <QtWidgets> class AlignDelegate: public QStyledItemDelegate{ public: AlignDelegate(Qt::Alignment alignment, QObject *parent = nullptr): QStyledItemDelegate(parent), m_alignment(alignment) { } protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const { QStyledItemDelegate::initStyleOption(option, index); option->displayAlignment = m_alignment; } Qt::Alignment m_alignment; }; class AlignComboBoxProxy: public QProxyStyle{ public: using QProxyStyle::QProxyStyle; void drawItemText(QPainter *painter, const QRect &rect, int /*flags*/, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole) const { QProxyStyle::drawItemText(painter, rect, Qt::AlignCenter, pal, enabled, text, textRole); } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QComboBox w; w.setStyle(new AlignComboBoxProxy(w.style())); for(int i=0; i < 10; ++i){ w.addItem(QString("item-%1").arg(i)); } w.setItemDelegate(new AlignDelegate(Qt::AlignCenter, &w)); w.show(); return a.exec(); }
This is perfect! Thank you so much!