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

ボタンはネイティブ スタイル エンジンによって描画されるため、パレットはまったく使用されない場合があります ( FAQ の質問を参照してください)。

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の回答が役立つ場合があります)。

または、同じボタンを 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-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 に答える