简体   繁体   中英

QstringList to Qstring conversion issues

I am working on VS2015 with qt framework. In my source code, I have a function for printing in the GUI screen. This function is called each time something needs to be printed. It goes like this.

void Trial::Print_MessageBox(QString string)
{

    ui.MessagesScreen->appendPlainText(string); 
    Cursor_Messagebox.movePosition(QTextCursor::End);
    ui.MessagesScreen->setTextCursor(Cursor_Messagebox);
    ui.MessagesScreen->ensureCursorVisible();
}

// Output in MessageBox
void Trial::Print_MessageBox(QFlags<QNetworkInterface::InterfaceFlag> flags)
{
    QString str = QString("Flag %1").arg(flags);
    ui.MessagesScreen->appendPlainText(str);
}

The above function has no problems and running well.

Now I am trying to read a text file. This has set of values in no order or size. An example for this:

231, 54, 4 \\n

47777, 2211, 676, 9790, 34236, 7898\\n

1, 3\\n

Objective is to convert these into integers (line by line) and print them in the GUI and also send them (line by line) to other system. So I tried to do it with the following.

void Trial::ReadFile_Data()
{
    QFile file("input.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        Print_MessageBox("Error in reading File");
        return;
    }
    QTextStream in(&file);
    while (!in.atEnd())
    {
        QString line = in.readLine();
        Print_MessageBox(line);
        int conv = line.toInt();
        QString str = QString("%1 %2").arg("Values are: ").arg(conv);
        Print_MessageBox(str);
        QStringList fields = line.split(",");
    }
    file.close();
}

When I print the "line", it is just printing the same values as in the file. When I do the conversion and printing, I get an error (which is expected) Now I try to remove "," with the help of split then I get QstringList which I cannot use as I have the Qstring function to print(this cant be changed)

I am not getting any pointers from here. Please help me out as this is bugging me since long time.

Just simple...

QStringList::const_iterator constIterator;

for (constIterator = fonts.constBegin(); constIterator != fonts.constEnd();
           ++constIterator) {

        cout << (*constIterator).toLocal8Bit().constData() << endl;
}

where fonts is your QStringlist

Your question reduces to "How do I iterate over a QStringList ".

Like this:

// C++11
for (auto field : fields) Print_messageBox(field);
// C++98
foreach (QString field, fields) Print_messageBox(field);

See here for information about how foreach aka Q_FOREACH was implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM