访问 QcomboBox 的选定值

access selected value of QcomboBox

我在 gui 小部件中设置了一个 QcomboBox 并添加了项目

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

在 QComboBox 插槽中,我想通过

获取选定的值
int index =ui->combo->itemData( ui->combo->currentText());

但有错误:316: error: no matching function for call to 'QComboBox::itemData(QString)'

如果我在打印时使用 currentIndex 而不是 currentText return 0; addItem 获取 Qstring ,

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

并且 ItemData 与 currentIndex 一起工作,

我使用insertItem,它有sae错误,那么如何设置值或文本并获取选择的值??

你可以这样获取当前索引:

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

或者如果你想要文本:

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

在您发布的代码中,您从未使用 Qt::UserRole 向您的组合框设置任何数据,这就是 itemData returns 0 的原因。如果您想使用 itemData 你必须将角色设置为 Qt::DisplayRole:

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

但是当您拥有 return 由 QComboBox class 提供的选定 index/text 的不错的功能时,没有理由这样做。这是一个工作示例:

#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