通过以下代码,我尝试使用QStyle.drawControl()呈现一个红色按钮
#include <QtCore/QtCore>
#include <QtGui/QtGui>
class Widget : public QWidget
{
virtual void paintEvent(QPaintEvent* event)
{
QStyleOptionButton opt;
opt.palette = QPalette(Qt::red);
opt.state = QStyle::State_Active | QStyle::State_Enabled;
opt.rect = QRect(50, 25, 100, 50);
QPainter painter(this);
style()->drawControl(QStyle::CE_PushButton, &opt, &painter);
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
Widget w;
w.resize(200, 100);
w.show();
return app.exec();
}然而,我得到了以下结果:

如何使用QStyle.drawControl()呈现红色按钮
我在Windows XP上使用Qt 4.8.1和Visal Studio 2010。
发布于 2012-08-11 07:25:53
这些按钮是由原生样式引擎绘制的,因此可能根本不使用调色板(请参阅常见问题解答中的that question )。
您可以使用带有样式表的实际按钮,该样式表作为最后一个参数传递给自己的按钮的样式drawControl函数。
class Widget : public QWidget
{
// To allow the automatic deletion without parenting it
QScopedPointer<QPushButton> button;
public:
Widget() : button(new QPushButton) {
button->setStyleSheet("background-color: red");
}
virtual void paintEvent(QPaintEvent* event)
{
QStyleOptionButton opt;
opt.state = QStyle::State_Active | QStyle::State_Enabled;
opt.rect = QRect(50, 25, 100, 50);
QPainter painter(this);
button->style()->drawControl(QStyle::CE_PushButton, &opt, &painter,
button.data());
}
};但是您将失去原生样式,因此您必须伪造它(bali182's answer可能对这一部分有用)。
或者,您可以使用具有colorize效果的相同按钮,并调用其render()函数来绘制它:

class Widget : public QWidget {
QScopedPointer<QPushButton> button;
public:
Widget() : button(new QPushButton) {
QGraphicsColorizeEffect *effect = new QGraphicsColorizeEffect(button.data());
effect->setColor(Qt::red);
button->setGraphicsEffect(effect);
}
virtual void paintEvent(QPaintEvent* event) {
button->setFixedSize(100, 50);
button->render(this, QPoint(50, 25));
}
};发布于 2012-08-10 21:41:48
你想要做的事情似乎过于复杂了。如果您只想要一个红色按钮,为什么不使用QPushButton的setStyleSheet()方法呢?它需要一个QString,你可以像CSS一样定义你的按钮。这里我为您创建了一个红色按钮,类似于XP ui按钮:
QPushButton
{
background: qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 #f4a3a3,stop: 1 #cc1212);
border-width: 1px;
border-color: #d91414;
border-style: solid;
padding: 5px;
padding-left:10px;
padding-right:10px;
border-radius: 3px;
color:#000;
}
QPushButton:hover
{
border-color: #e36666;
}
QPushButton:pressed
{
background:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop: 0 #de8383, stop: 1 #ad0C0C);
border-color: #d91414;
}现在,您只需要将上面的代码作为字符串传递给按钮的setStyleSheet()方法。如果想要创建一个按钮小部件(默认情况下是红色的),则扩展QPushButton类,使用上面的内容创建一个静态QString字段,并在构造函数中将该按钮设置为样式表。
样式表上更容易理解的示例: Stylesheet Examples
https://stackoverflow.com/questions/11901037
复制相似问题