Reputation: 885
This is a follow up question to this posting.
I am trying a method where I subclass the QToolButton and override the paint event such that a red rectangle is drawn first and the text is drawn on top of the rectangle.
I have the code mostly working, however, the text on the button is not being drawn. I have looked at a few forum posting but not much has panned out. Below is the current version of the paint override function:
virtual void paintEvent(QPaintEvent *) override
{
QString tempText;
QStylePainter p(this);
QStyleOptionToolButton opt;
initStyleOption(&opt);
tempText = opt.text;
opt.text = QString();
p.save();
p.drawComplexControl(QStyle::CC_ToolButton, opt);
p.setBrush(QColor(255,0,0,100));
p.setPen(Qt::NoPen);
p.drawRect(4,4,width()-8,height()-8);
// p.setBrush(QColor(0,0,0));
p.setPen(QColor(0,0,0));
p.setFont(this->font());
p.drawText(this->frameGeometry(), Qt::AlignCenter, tempText);
p.restore();
}
Currently, the logic of the code should be:
1) Save the text contained in opt
(This text is drawn on the button). In my code, the text in opt
is saved in a variable called tempText
2) Set opt.text
to an empty string
3) Draw the button with the red rectangle in the middle
4) Draw tempText
on the button with the proper alignment settings. For this, I was thinking about bounding the text to a frame within the button. But so far, there is no text drawn on the button.
Upvotes: 0
Views: 369
Reputation: 12898
As per the comment, QWidget::frameGeometry
returns the...
"geometry of the widget relative to its parent..."
which isn't actually what you want here. Rather you want the QRect
in which the contents of the QWidget
will be rendered. So you probably want...
p.drawText(contentsRect(), Qt::AlignCenter, tempText);
On a separate note, your paintEvent
implementation calls QPainter::save
and QPainter::restore
. Those are potentially expensive operations and should be avoided unless absolutely necessary.
Upvotes: 1