How to get colored transient messages in QStatusBar?

4.9k Views Asked by At

I need to color-code messages flashing in the status bar of my Qt5.5 app.

I am using showMessage like this:

ui->statusBar->showMessage("My Message", 5000);

I would like to change the color of a single message. I've found no way short of subclassing QStatusBar and overriding showMessage(). Do I really need such an invasive change?

I tried to use Rich Text along the lines of:

ui->statusBar->showMessage(QString("<html><head/><body><p style=\"color:red\">%1</p></body></html>").arg("My Message"));

but it doesn't seem to be recognized (prints the tags).

Altering the palette or setting the style-sheet will not be limited to the current message.

What else could I try?

1

There are 1 best solutions below

0
On

How to get colored transient messages in QStatusBar?

Altering the palette or setting the style-sheet will not be limited to the current message.

Altering the stylesheet does not necessarily apply to all widgets in the program. You can definitely limit the scope of the stylesheet.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // the stylesheet can be applied within ui->statusBar hierarchy of 
    // objects, but you can make it even more narrow scope as
    // ui->statusBar->setStyleSheet("QStatusBar{color:red}") if needed
    ui->statusBar->setStyleSheet("color: red");
    ui->statusBar->showMessage("Text!");

    QTimer::singleShot(2000, this, SLOT(tryAnotherColor()));
}

void MainWindow::tryAnotherColor()
{
    ui->statusBar->setStyleSheet("color: blue");
    ui->statusBar->showMessage("More Text!");
}

I tried to use Rich Text

My guess is that not all Qt widget controls have rich-text rendering functionality but most do understand CSS-like stylesheets..