7

使用以下代码,我尝试使用以下代码呈现红色按钮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。

4

2 回答 2

9

这些按钮是由原生样式引擎绘制的,因此可能根本不使用调色板(请参阅常见问题解答中的那个问题)。

您可以使用带有样式表的实际按钮,将其作为最后一个参数传递给自己按钮的样式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可能对那部分有用)。

或者您可以使用具有着色效果的相同按钮并调用其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-10T23:25:53.490 回答
3

您正在尝试做的事情似乎过于复杂。如果你只想要一个红色按钮,为什么不使用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字段,并在构造函数中将按钮设置为样式表。

更易于理解的样式表示例: 样式表示例

于 2012-08-10T13:41:47.533 回答