0

公式ドキュメントでも推奨されているメソッドQPushButtonを再実装できるように、 a をサブクラス化しました。paintEvent(QPaintEvent *paint)

以下は一連の操作です。

a) アプリケーションを起動すると、ボタンは次のようになります。

b

b) これは、カーソルを合わせた後のものです。

c

c) 次に、ボタンをクリックします。

b

d) そして最後にマウスを放します

d

e) ボタンから離れる

b

ただし、問題は、ボタンを放した後QPainterPath、緑色のボックスを設計したときに赤色になることです。もちろん、ボタンをもう一度クリックすると、再び緑色になるはずです。

コードの下:

custombutton.h

class CustomButton : public QPushButton
{
    Q_OBJECT
public:
    CustomButton(QWidget *parent = nullptr);
    ~CustomButton();

    QString FirstName = "MACHINE";
    QString LastName = "CONTROL";

protected:
    void paintEvent(QPaintEvent *);
};

カスタムボタン.cpp

CustomButton::CustomButton(QWidget *parent) : QPushButton(parent)
{
    setGeometry(150, 150, 110, 110);
    setAttribute(Qt::WA_TranslucentBackground);
    setStyleSheet(
        "QPushButton{background-color: lightGray;border: 1px solid black; border-radius: 5px;}"
        "QPushButton:hover{background-color: gray;}"
        "QPushButton:pressed{background-color: lightGray;}");
}

CustomButton::~CustomButton()
{

}    

void CustomButton::paintEvent(QPaintEvent *paint)
{
    QPushButton::paintEvent(paint);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);
    QPainterPath path;
    path.addRoundedRect(QRectF(15, 15, 80, 5), 2, 2);
    QPen pen(Qt::black, 0.3);
    p.setPen(pen);
    p.fillPath(path, Qt::darkGreen);
    p.drawPath(path);
    p.save();

    p.drawText(QPoint(20, 60), FirstName);
    p.drawText(QPoint(20, 80), LastName);
    p.setFont(QFont("Arial", 10));
    p.restore();
}

メインウィンドウ.h

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

public slots:
    void onClickedButton();
private:
    Ui::MainWindow *ui;
    CustomButton *newBtn;
};

メインウィンドウ.cpp

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    newBtn = new CustomButton(this);
    newBtn->show();
    connect(newBtn, &QPushButton::clicked, this, &MainWindow::onClickedButton);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onClickedButton()
{
    QPushButton* target = qobject_cast<QPushButton*>(sender());
    if (target != nullptr)
    {
        QPainter p;
        p.setRenderHint(QPainter::Antialiasing);
        QPainterPath path;
        path.addRoundedRect(QRectF(15, 15, 80, 5), 2, 2);
        QPen pen(Qt::black, 0.3);
        p.setPen(pen);
        p.fillPath(path, Qt::darkRed);
        p.drawPath(path);
        p.save();
        p.restore();
    }
}

ご覧のとおり、クリックすると が赤くなると思われるMainWindow関数を作成しました。そして、それを行うために、オブジェクト (qobject_cast) にキャストしました。しかし、残念なことに、期待どおりに機能しませんでした。onClickedButton()QPainterPath

4

1 に答える 1