Is it possible to draw a colored rectangle on a pushButton?

  • I want after choosing a color from the QColorDialog put a rectangle (as a preview) on the PushButton and change its color to the color which I have chosen.

    The PushButton before choosing the color:

    alt text

    The PushButton after choosing the color:

    alt text

    Is it possible to draw a colored rectangle on a pushButton, and how can I do that (an example)?

  • Qt Champions 2017

    Yes its possible by just subclassing the button and make a new paintEvent function.
    However, what about the text.?
    Anyway a quick way is just keep a copy and reset it back if needed.

    Test project with subclass

    alt text

    void ColorButton::paintEvent(QPaintEvent* event) {
      QPushButton::paintEvent(event); // call base paint
      if (!text().isEmpty()) { return; } // if it still show text we dont paint color
      QPainter p(this);
      QBrush b(Color);
      QRect colorRect(rect());
      int reduced = width() / 4;
      QMargins m(reduced, 2, reduced, 2) ;
      colorRect = colorRect.marginsRemoved(m);
      p.fillRect( colorRect, b );

  • @mrjj : Thank you for your answer.

  • Qt Champions 2017

    np. please mark as solved if possible.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.