【问题标题】:access selected value of QcomboBox访问 QcomboBox 的选定值
【发布时间】:2016-08-19 18:28:18
【问题描述】:

我在 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 打印时返回0; addItem 获取Qstring,

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

并且 ItemData 与 currentIndex 一起工作,

我使用insertItem,出现sae错误,如何设置值或文本并获取选定值??

【问题讨论】:

  • @thuga 我编辑的类型不正确
  • 你为什么不用int index = ui-&gt;combo-&gt;currentIndex();?在您发布的代码中,您从未为组合框设置任何数据,这就是itemData 返回 0 的原因。或者,如果您想获取当前文本,只需使用 QString selected_text = ui-&gt;combo-&gt;currentText();
  • @thuga 如果我在运行程序时使用此 index = ui-&gt;combo-&gt;currentIndex(); 获取 currentindex 而不选择,例如,如果我在没有选择的情况下运行时将 1 设置为 31 currentindex 为 1
  • @thuga 我通过这种方式设置数据ui-&gt;combo-&gt;addItem(QString::number(i)); 并尝试 insertItem() ,他们返回0,那么如何设置数据??
  • 这和QComboBox::setItemData不一样。无论如何,问题不存在。 currentIndex/currentText 应该可以工作。你甚至在哪里检查currentIndex/currentText?您是否已将插槽连接到组合框的某些信号?

标签: qt qcombobox getdate


【解决方案1】:

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

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

或者如果你想要文本:

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

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

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

但是,当您有很好的函数返回 QComboBox 类提供的选定索引/文本时,没有理由这样做。这是一个工作示例:

#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

【讨论】:

  • tnx ,例如当我选择 10 时,索引打印输出 9 和文本打印输出 10??
  • @g1331 这是预期的。 currentIndex 返回当前索引。并且通常索引从 0 开始。如果你有一个数组或容器,第一项在索引 0 中。
  • 感谢您,它很有帮助。
猜你喜欢
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2019-01-01
  • 2013-10-26
  • 1970-01-01
相关资源
最近更新 更多