Search code examples
qtbackground-color

Changing the background colour of label in QT


I have a main window and a label on it. This has to be displayed on full screen. A data will displayed on label. The background should be black and text needs to be white. I am receiving data like 1 or 2 or 3 via serial and I am fetching the related text of 1 or 2 or 3 from a file. I am also adjusting the text to fill the complete label. If the text is small, then its font size need to be increase and if it is large then it need to be small font size.

I am using stylesheet to make the background color of label to black and I am putting it after adjusting the font size of the text. Like below:

void MainWindow::SerialRead()
{
   //Reading the serial data
   //Reading the string from file
   //Adjusting the font size to fill the label

   //Changing color
   ui->label->setStyleSheet("QLabel{ background-color : black; color : white; }");
}

So after this my outcome looks like this:

enter image description here

As you can see in the above image, there is white border which is of main window because we have not set the back color of main window (it is not clearly visible because webpage color is also white). I also want the color of main window to be black so that full screen is black and text is white. I also tried setting the stylesheet in main.c for main window like below:

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow app;
  //Chaning color
  app.setStyleSheet("QMainWindow {background-color : black;}");
  app.SerialInit();
  app.SerialWrite();
  app.showFullScreen();

  return a.exec();
}

So it does changes the color of main window to black but the outcome looks like below:

enter image description here

As you can see it also changes the font size of the text which I do not want. How can I achieve this.?


Solution

  • I am also new in qt , but I can suggest you to first set a name of QMainWindow by setObjectName and then use style sheet as:

    int main(int argc, char *argv[])
    {
      QApplication a(argc, argv);
      MainWindow app;
      //Chaning color
      app.setStyleSheet("#MainWindowName{background-color : black;}");
      app.SerialInit();
      app.SerialWrite();
      app.showFullScreen();
    
      return a.exec();
    }
    

    Hope it helps.