Karthik Shivanna
Karthik Shivanna

Reputation: 3

How to add variable value in Qt QMessageBox?

printf("This machine calculated all prime numbers under %d %d times in %d 
  seconds\n", MAX_PRIME, NUM_OF_CORES, run_time);

I want this output to be printed in QMessageBox text Box.

I have gone through QMessageBox documentation didn't find anything helpful.

Upvotes: 0

Views: 4301

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126827

QMessageBox has nothing for it because it's none of its business - it just displays strings as you passed them. However, QString does provide methods for formatting data replacing placeholders using the arg method:

QMessageBox::information(parent,
     QString("This machine calculated all prime numbers under %1 %2 times in %3 seconds")
         .arg(MAX_PRIME)
         .arg(NUM_OF_CORES)
         .arg(run_time), "Message title");

http://doc.qt.io/qt-5/qstring.html#argument-formats

http://doc.qt.io/qt-5/qstring.html#arg

Upvotes: 4

Kirill Chernikov
Kirill Chernikov

Reputation: 1420

First of all you must fill QString for you QMessageBox. You can do it with method arg of QString. Then you can show message box with static method information of QMessageBox. In your case code will be:

QMessageBox::information(nullptr/*or parent*/, "Title",  
    QString("This machine calculated all prime numbers under %1 %2 times in %3 seconds")
    .arg(MAX_PRIME).arg(NUM_OF_CORES).arg(run_time));

Upvotes: 1

Related Questions