QVector<QString> convert to double



  • Hello everybody,

    i have a vector filled with Strings and i want to convert them into double numbers to use them as data points in a graph. The Vector is filled with Strings, because it gets the values from a table.

    My current code looks like this:

    QVector<double>  x(num_rows);
    QVector<QString> y(num_rows);
    for (int i=0; i<num_rows; ++i)
    {
      x[i] = 1.5*i;
      y[i] = ui->tableWidget->item(i,2)->text().toDouble();
    }
    

    The result is:
    QVector("%", "\u0000", "\u0000", "\u0000", "\u0000", "\u0000", "%")
    instead of:
    QVector(37, 36,8, 36,9, 36,7, 36,9, 36,8, 37)

    Thanks for your help.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Your y vector looks like that because you made it like a QVector<QString>. Since you already convert your QTableWidget content to double, why not make it a QVector<double> like x ?



  • Hi and welcome to devnet,

    y[i] = ui->tableWidget->item(i,2)->text().toDouble();
    

    you're converting a text into number and then assign to a QString!!!

    Have you tried with

    QVector<double> x(num_rows);
    QVector<double> y(num_rows); // <-- Now is a Vector of double
    for (int i=0; i<num_rows; ++i)
    {
      x[i] = 1.5*i;
      y[i] = ui->tableWidget->item(i,2)->text().toDouble();
    }
    

    ??



  • it works. Thank you!

    One more Question. The values for x[i] are in sql datetime format (yyyy-mm-dd hh:mm:ss). And in my Vector they are converted to Strings. How can i use these data in the right way? My aim is to plot them on xAxis, using QCustomPlot.

    QVector<QString>  x(num_rows);
    QVector<double> y(num_rows);
    for (int i=0; i<num_rows; ++i)
    {
      x[i] = ui->tableWidget->item(i,1)->text();
      y[i] = ui->tableWidget->item(i,2)->text().toDouble();
    }
    

    response:QVector("2015-11-17 18:50:00",......)



  • Most Qt SQL drivers return the value as QVariant, from there you can normally use the QVariant::toDate() or QVariant::toDateTime() functions.

    Otherwise you need to use the static QDateTime::fromString() function, just set the format correctly.

    QDateTime date = QDateTime::fromString(x[i], "yyyy-MM-dd hh:mm:ss");
    

    PS: the above format is just an example, you need to update based on your format that you have but it looks like it should work based on your response:

    response:QVector("2015-11-17 18:50:00",......)



  • I got it, thank you!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.