Search code examples
c++qtqcombobox

Qt ComboBox 2 columns or horizontal columns?


I have a QComboBox with a rather long drop down. With style sheets qss I can reduce the length, but I wonder if I can display the items horizontally or in 2 columns?

As my values are just keys (1 character) I could use 2,3,4 columns or use something which expands horizontally instead of vertically. Any chance to do so?

DropDown


Solution

  • It must be replaced with a QListView with a flow QListView::LeftToRight and set an appropriate size of the view and popup:

    #include <QApplication>
    #include <QBoxLayout>
    #include <QComboBox>
    #include <QListView>
    
    class HorizontalComboBox: public QComboBox
    {
    public:
        HorizontalComboBox(QWidget *parent = nullptr):
            QComboBox(parent)
        {
            QListView *m_view  = new QListView(this);
            m_view->setFlow(QListView::LeftToRight);
            setView(m_view);
            for(QWidget* o: findChildren<QWidget *>()){
                if(o->inherits("QComboBoxPrivateContainer")) {
                    //popup
                    o->setFixedHeight(view()->height());
                    break;
                }
            }
        }
        virtual void showPopup() override {
            QComboBox::showPopup();
            int w = 0;
            for(int i=0; i<count(); i++){
                QModelIndex ix= model()->index(i, modelColumn(), rootModelIndex());
                w += view()->visualRect(ix).width();
            }
            view()->setFixedWidth(w);
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        HorizontalComboBox w;
        w.addItems(QString("ABCDEFGHIJKLMNOPQRSTUVWXYZ").split("", QString::SkipEmptyParts));
        w.show();
        return a.exec();
    }