Qt按钮字体旋转

#include "mainwindow.h"
#include "ui_mainwindow.h"

class RotatedButton : public QPushButton
{
public:
    explicit RotatedButton(const QString &text, QWidget *parent = nullptr)
        : QPushButton(text, parent)
    {
    }
    bool state = false;
    bool Spec = true;

protected:
    void paintEvent(QPaintEvent *event) override
    {
        QPushButton::paintEvent(event);
        QString str = "测试";//text();
        int len = str.length();
        this->setText("");
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        // 将坐标原点移到按钮中心
        //painter.translate(rect().center());
        painter.translate(QPointF(20,20));
        // 将字符串旋转90度
        if(state)
        {
            painter.rotate(-90);
            painter.drawText(0, 10, str.at(0));
            painter.drawText(0, 40, str.at(1));
        }
        else
        {
            painter.rotate(0);
            painter.drawText(10, 20, str.at(0));
            painter.drawText(40, 20, str.at(1));
        }
        // 绘制按钮中的字符串

    }
};
RotatedButton *pBtn ;
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QVBoxLayout layout(ui->centralwidget);

    pBtn = new RotatedButton("测试",ui->centralwidget);
    pBtn->setFixedSize(100,50);
    layout.addWidget(pBtn);


}

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


void MainWindow::on_pushButton_clicked()
{
    pBtn->state = !pBtn->state;
    pBtn->repaint();
}

 

posted @ 2024-02-02 14:38  昊天一怪  阅读(164)  评论(0编辑  收藏  举报