基于样式表伪状态值绘制自定义QWidget
我有一个自定义的QWidget
(实际上,派生自QAbstractButton
),我必须为其实现自己的paintEvent
。如何使用样式表信息?
例如,假设有人定义了以下样式表(直接或通过继承)应用于我的自定义类:
QAbstractButton { font-weight: bold; background-color: red }
QAbstractButton:checked { background-color: blue }
在我的 paintEvent
方法中,如何获取正确的背景颜色以显示选中状态?
void MyButton::paintEvent(QPaintEvent */*event*/) {
ensurePolished(); // Don't think this is necessary...
qDebug() << Q_FUNC_INFO << isChecked(); // This is showing the right value
QStylePainter painter(this);
painter.fillRect(rect(), painter.background()); // always red, even if checked
}
我假设我必须这样做:
if (isChecked()) {
// painter.fillRect(rect(), ???);
//
// style()->drawPrimitive(???, ...);
//
// QStyleOptionButton opt;
// opt.initFrom(this);
// QBrush bg_brush = opt.???
// painter.fillRect(rect(), bg_brush);
//
// ???
} else {
painter.fillRect(rect(), painter.background());
}
如何让画笔用于 Qt 从样式表解析的选中状态背景?
I have a custom QWidget
(actually, derived from QAbstractButton
) for which I have to implement my own paintEvent
. How to I use the style sheet information?
For example, suppose someone defines the following stylesheet that applies (directly or via inheritance) to my custom class:
QAbstractButton { font-weight: bold; background-color: red }
QAbstractButton:checked { background-color: blue }
In my paintEvent
method, how do I get the correct background color to show up for the checked state?
void MyButton::paintEvent(QPaintEvent */*event*/) {
ensurePolished(); // Don't think this is necessary...
qDebug() << Q_FUNC_INFO << isChecked(); // This is showing the right value
QStylePainter painter(this);
painter.fillRect(rect(), painter.background()); // always red, even if checked
}
I assume I have to something like:
if (isChecked()) {
// painter.fillRect(rect(), ???);
//
// style()->drawPrimitive(???, ...);
//
// QStyleOptionButton opt;
// opt.initFrom(this);
// QBrush bg_brush = opt.???
// painter.fillRect(rect(), bg_brush);
//
// ???
} else {
painter.fillRect(rect(), painter.background());
}
How do I get the brush to use for the checked-state background that Qt resolved from the style sheets?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我永远无法找到如何获取解析的颜色(和填充)信息,但能够通过将其他小部件的子元素绘制到我的中来解决它。这并不是我想要做的,并且在其他情况下可能不起作用(如果你的小部件不能通过将 Qt 知道如何绘制的东西混合在一起来组成)。
我仍然认为必须有更好的方法。
I never could find out how to get the resolved color (and padding) information, but was able to work around it by painting sub-elements of other widgets into mine. This isn't exactly what I was trying to do, and may not work in other cases (if your widget can't be composed by mashing together stuff that Qt does know how to draw).
I still think there has to be a better way.