Search code examples
c++qtuser-interfaceqcomboboxqvariant

How to convert QComboBox value to int in QT


i'm making a simple calculator using Qt with QT Creator I want to convert a value from QCombobox (that conatain the operations :'+' , '-', '*','/') to int so i have used this :

// operation is the name of my QComboBox :)

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

When trying to print the value of i to test it i get :

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

Output

valeur 1219552

valeur 1219552

valeur 1219552

valeur 1219552

valeur 1219552

The conversion is give me the same value that it's not corresponding to the index of the QComboBox whenver i choose any of the operations . However it make the addition operation successfully !!!
Calculator
This is the hole file to that demonstrate what i'm trying to accomplish :

#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));
    }
}

I have used the graphical interface to put the value for the comboBox comboBox  Values

Any suggestions?


Solution

  • You meant to write:

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

    This gives the selected combo-box index (0 is the first, "+", 1 the second, "-" and so on).

    itemData is relevant only if you attached data to the item using setItemData.