Search code examples
c++qlineedit

How to display concatenated string and int in qlineedit or qtextedit?


I have here:

int num = 000;
std::string result;
std::string text = "asdasd";
result += text + std::to_string(num);

I want to display the result in qlineedit.


Solution

  • Since you are using , you should use QString instead of std::string to avoid many unnecessary conversions.
    Indeed, QString is the string class used by all the Qt library (containers, ...).

    Your sample will become then:

    int num = 0;
    QString text = "asdasd";
    QString result = text + QString::number(num);
    

    Then, you'll be able to write:

    my_widget->setText(result); // QLineEdit or QTextEdit
    

    If you really want to use a std::string anyway, you'll need to convert it to a proper QString. You could use QString::fromStdString() for this purpose.

    For example:

    my_widget->setText(QString::fromStdString(result));