Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Creating table in QcomboBox



  • I would like to create a combobox with several columns and with column headers. I point out that I am new to programming with Qt. a bit like the image below. Thank you for kindly helping me. thank you.
    MultiColumnComboBoxControl.png



  • @devman
    This looks like a combobox up top and a separate widget, mostly QTableView/QTableWidget plus buttons and scrolling at the bottom. Would that satisfy you? I don't know whether you can do all this in a combobox delegate.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You have two options:



  • @SGaist Oh, I didn't know about QComboBox::setView(), that looks nicely suited for the popup!



  • @devman MWE:

    #include <QtWidgets>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QMainWindow w;
        QComboBox *combo = new QComboBox(&w);
    
        QStandardItemModel model(10, 3);
        model.setHorizontalHeaderLabels({"title", "name", "company"});
        for(int i=0; i< model.rowCount(); ++i){
            for(int j=0; j < model.columnCount(); ++j){
                QStandardItem *it = new QStandardItem(QString("%1 - %2").arg(i).arg(j));
                model.setItem(i, j, it);
            }
        }
        combo->setModel(&model);
        combo->setModelColumn(1);
    
        QTableView *view = new QTableView;
        combo->setView(view);
        view->setSelectionBehavior(QAbstractItemView::SelectRows);
        view->setFixedWidth(350);
    
        w.show();
    
        return a.exec();
    }
    


  • Thank you all for answering me so quickly, I received to do it with a setView but the columns just take the size of the combobox.or me I would like to display several columns even if the combobox is small.



  • @devman Have you run my MWE? In that code I have set the width of the QTableView which is larger than the width of the QComboBox: view->setFixedWidth(350);



  • Thank you very much eyllanesc, your code works perfectly


Log in to reply