Important: Please read the Qt Code of Conduct -

How to put a string variable as the text of the qlabel.

  • I'm trying to do this:

    QLabel* label=new QLabel("Welcome ",temp->getLoggedInID());

    where temp->getLoggedInID() returns a string. So i want the text of the qlabel to be something like: "Welcome Mike"

    But this doesn't work. I would I do this?


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You can't build a string like that.

    QString("Welcome %1").arg(temp->getLoggedInID())

    Should do the job

    Hope it helps

  • Hi SGaist thanks for your help, but I didn't quite understand your solution.

    Let's say I converted two strings to qstring:


    How would i put them into the qlabel:

    QLabel* label=new QLabel("Welcome "......)


  • how about QString("Welcome ")+whateverElseQString :P

  • Moderators

    @gyll - The .arg() option that SGaist gave is better because of translation system. In some languages the name might go before the "welcome" in which case the translator can just change the template text for that language to "%1 welcome" without re-compiling the app. Of course this would need to be wrapped in tr() first but you get the point.


    QString str1 = "foo";
    QString str2 = "bar"; 
    QString text = QString("I like %1 more than %2.").arg(str1, str2);
    QLabel* label = new QLabel(text); //if it's a new label
    label->setText(text); //if it's an existing one

Log in to reply