QpushButton绘制圆角矩形并绘制背景颜色

要在QPushButton的paintEvent中绘制按钮的颜色,可以创建一个自定义的QPushButton类,并重写它的paintEvent函数。在paintEvent函数中,可以使用QPainter来绘制按钮的背景颜色。

以下是一个简单的示例代码,演示如何在自定义的QPushButton类中绘制按钮的颜色:

cpp 复制代码
#include <QApplication>
#include <QPushButton>
#include <QPainter>

class CustomButton : public QPushButton {
public:
    CustomButton(QWidget *parent = nullptr) : QPushButton(parent) {}

protected:
    void paintEvent(QPaintEvent *event) override {
        QPushButton::paintEvent(event);

        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿
        painter.setBrush(QColor("#ff0000")); // 设置按钮的背景颜色
        painter.drawRect(rect()); // 绘制按钮的背景
        // 在按钮上手动绘制文本,颜色为按钮文本颜色
        painter.setPen(palette().color(QPalette::ButtonText));
        painter.drawText(rect(), Qt::AlignCenter, text());
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    CustomButton button("Custom Button");
    button.resize(200, 50);
    button.show();

    return app.exec();
}

在这个示例中,我们创建了一个名为CustomButton的自定义QPushButton类,并重写了它的paintEvent函数。在paintEvent函数中,我们使用QPainter来绘制按钮的背景颜色。在示例中,我们将按钮的背景颜色设置为红色。

你可以根据需要自定义paintEvent函数以实现你想要的按钮样式和外观。

相关推荐
xcyxiner1 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner2 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner2 天前
DicomViewer (添加模型类)3
qt
xcyxiner3 天前
DicomViewer (目录调整) 2
qt
xcyxiner3 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能5 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G5 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
森G5 天前
77、线程池原理和实现------服务器源码解析----云视频服务项目
服务器·c++·qt
森G5 天前
71、打包发布---------打包发布
c++·qt
初圣魔门首席弟子5 天前
Node.js 详细介绍(知识库版)
windows·qt·node.js·知识库