Search code examples
qtqcomboboxgetdate

access selected value of QcomboBox


I set a QcomboBox in gui widget and ,I add item

for(int i = 1; i < 31; i++)
        {
            ui->combo->addItem(QString::number(i));
        }

and in QComboBox slot I want to get selected value by

int index =ui->combo->itemData( ui->combo->currentText());

but have error :316: error: no matching function for call to 'QComboBox::itemData(QString)'

if I use currentIndex instead of currentText return 0 when print it; addItem get Qstring ,

void QComboBox::addItem(const QString & text, const QVariant & userData = QVariant())

and ItemData work with currentIndex,

I use insertItem and it has sae error ,so how can set value or text and get slected value??


Solution

  • You can get the current index like this:

    int index = ui->combo->currentIndex();
    

    Or if you want the text:

    QString text = ui->combo->currentText();
    

    In the code you've posted you never set any data with the Qt::UserRole to your combobox, that is why itemData returns 0. If you want to use itemData you have to set the role to Qt::DisplayRole:

    ui->combo->itemData(index, Qt::DisplayRole)
    

    But there is no reason to do this when you have nice functions that return the selected index/text provided by the QComboBox class. Here is a working example:

    #ifndef MYWIDGET_H
    #define MYWIDGET_H
    
    #include <QWidget>
    #include <QLayout>
    #include <QComboBox>
    #include <QDebug>
    
    class MyWidget : public QWidget
    {
        Q_OBJECT
    public:
        explicit MyWidget(QWidget *parent = 0) : QWidget(parent)
        {
            setLayout(new QVBoxLayout);
            comboBox = new QComboBox;
            for(int i = 1; i < 31; i++)
                comboBox->addItem(QString::number(i));
            connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(cbIndexChanged()));    
            layout()->addWidget(comboBox);
        }
    
    public slots:
        void cbIndexChanged()
        {
            int index = comboBox->currentIndex();
            QString text = comboBox->currentText();
    
            qDebug() << index << text << comboBox->itemData(index, Qt::DisplayRole);
        }
    
    private:
        QComboBox *comboBox;
    };
    
    #endif // MYWIDGET_H