QT中如何将QComboBox值转换为int

How to convert QComboBox value to int in QT

我正在使用 Qt 和 QT Creator 制作一个简单的计算器 我想将一个值从 QCombobox(包含操作:'+'、'-'、'*'、'/')转换为 int,所以我使用了这个:

// operation is the name of my QComboBox :)

QVariant i = ui -> operation -> itemData(ui -> operation -> currentIndex()); 
int val = i.toInt();

当试图打印 i 的值来测试它时,我得到:

printf("valeur %d \n",i);

输出

valeur 1219552

valeur 1219552

valeur 1219552

valeur 1219552

valeur 1219552

每当我选择任何操作时,转换都会给我与不对应于 QComboBox 索引的相同值。但是它使加法操作成功!!!

这是演示我要完成的任务的孔文件:

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this); // lance la construction de la fenêtre.
    connect(ui->boutonEgale, SIGNAL(clicked()), this,SLOT(calculerOperation()));

}

Dialog::~Dialog()
{
    delete ui;
}


void Dialog::calculerOperation()
{
    QVariant i =   ui->operation->itemData(ui->operation->currentIndex());  
    int val = i.toInt();

    int rst = 0;
    switch(val)
    {
    case 0:  // +
    rst = ui->nb1->value() + ui->nb2->value();
    ui->result->setText(QString::number(rst));  
    break;
    case 1:  // -
    rst = ui->nb1->value() - ui->nb2->value();
    ui->result->setText(QString::number(rst));  
    break;
    case 2: // *
    rst = ui->nb1->value() * ui->nb2->value();
    ui->result->setText(QString::number(rst));   
    break;
    case 3: // /
    rst = ui->nb1->value() / ui->nb2->value();
    ui->result->setText(QString::number(rst));   
    break;
    default:
    rst = ui->nb1->value() + ui->nb2->value();
    ui->result->setText(QString::number(rst));
    }
}

我已经使用图形界面为组合框输入值

有什么建议吗?

您打算写:

int val = ui->operation->currentIndex();

这给出了选定的 combo-box 索引(0 是第一个,“+”,1 第二个,“-”等等)。

itemData 仅当您使用 setItemData.

将数据附加到项目时才相关

您似乎混淆了 QComboBox 可以包含的两个值:文本(您在 Qt Creator 对话框屏幕截图中编辑的内容)和存储在 QVariant 中的实际有用负载 QCombobox::setItemData(int, QVariant, int) http://doc.qt.io/qt-4.8/qcombobox.html#setItemData。如果您想在每个组合框条目旁边保存并稍后检索一个 int,请使用后一个函数和相应的 QComboBox::itemData(int, int) 进行检索。

严格来说,QComboBox里面有一个full-blownQStandardItemModel用来存储数据。引用文档:

QComboBox uses the model/view framework for its popup list and to store its items. By default a QStandardItemModel stores the items and a QListView subclass displays the popuplist. You can access the model and view directly (with model() and view()), but QComboBox also provides functions to set and get item data (e.g., setItemData() and itemText()). You can also set a new model and view (with setModel() and setView()). For the text and icon in the combobox label, the data in the model that has the Qt::DisplayRole and Qt::DecorationRole is used.