qtsplitstackqstringqstringlist

Add String from textEdit to a QStack


I am trying to capture the contents from textEdit and add it to a QStack. The content I am splitting so to be able to reverse the order of the sentence captured. I already have that part covered, but I want to be able to convert from QStringList to be pushed to the QStack. This is what I have:

    void notepad::on_actionReversed_Text_triggered()
{

    QString unreversed = ui->textEdit->toPlainText();
    QStringList ready = unreversed.split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts);

    QStack<QString> stack;
    stack.push(ready);

    QString result;

    while (!stack.isEmpty())
    {
        result += stack.pop();
        ui->textEdit->setText(result);
    }


}

Solution

  • QStack::push only takes objects of it's template type.

    i.e. In your case you must push QString's onto the QStack<QString>, and not a list.

    So, iterate the list of strings pushing each one in turn.

    foreach (const QString &str, ready) {
        stack.push(str);
    }
    


    Something else that is wrong is that you are updating textEdit inside the for loop. You actually want to build up the string in the loop and afterwards update the text.

    QString result;
    while (!stack.isEmpty()) {
        result += stack.pop();
    }
    
    ui->textEdit->setText(result);
    


    An alternate answer could be to do away with the stack and just iterate the QStringList ready in reverse order to build up result string.