QPainter and QStyleSheet
-
Hi everyone, I've run into a small problem. I am setting a QStyleSheet in a widget using the "background-color" attribute. I am also drawing a rectangle in the paintEvent event. Below are code fragments:
ui->centralwidget->setStyleSheet("background-color: black"); ... void EmyWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setBrush(QColor(QString("#FFFFFF"))); painter.setPen(QPen(Qt::red, 2)); painter.drawRect(50, 25, 100, 30); }
Problem is next: my rectangle drawing early than background-color, so I don't see it. How I can draw rectangle after filling background?
-
Hi everyone, I've run into a small problem. I am setting a QStyleSheet in a widget using the "background-color" attribute. I am also drawing a rectangle in the paintEvent event. Below are code fragments:
ui->centralwidget->setStyleSheet("background-color: black"); ... void EmyWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setBrush(QColor(QString("#FFFFFF"))); painter.setPen(QPen(Qt::red, 2)); painter.drawRect(50, 25, 100, 30); }
Problem is next: my rectangle drawing early than background-color, so I don't see it. How I can draw rectangle after filling background?
-
@Vlad02
Maybe by calling QWidget::painEvent()
on top.
Anyway, I don't understand why you don't draw the background yourself in paintEvent. -
@mpergand I just need to redraw it periodically, won't that slow down the redraw? Given that I will be redrawing this widget and another child widget
Note: If you subclass a custom widget from QWidget, then in order to use the StyleSheets you need to provide a paintEvent to the custom widget :
void CustomWidget::paintEvent(QPaintEvent* event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QWidget::paintEvent(event); }
https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget
Warning: Function setStyleSheet is particularly useful for demonstration purposes, where you want to show Qt's styling capabilities. Real applications should avoid it and use one consistent GUI style instead. As applicable to setStyle too.
Agree 200%