我对 a 进行了子类化,QPushButton
以便能够重新实现paintEvent(QPaintEvent *paint)
官方文档也建议的方法。
以下是操作顺序:
a)启动应用程序后,按钮如下:
b)这是在我将鼠标悬停在它上面之后:
c)然后我点击按钮:
d) 最后我松开鼠标
e) 远离按钮
然而问题是QPainterPath
我设计的绿色盒子在我释放按钮后应该是红色的。当然,在我再次单击该按钮后,它应该再次变为绿色。
代码下方:
自定义按钮.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
我创建的函数onClickedButton()
中看到的那样,我认为单击后会触发QPainterPath
变为红色。为了做到这一点,我将它转换成一个对象(qobject_cast)。但不幸的是,它并没有像expexted那样工作。