提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这里可以添加本文要记录的大概内容:
项目使用自定义按钮,查找资料后开发成功,记录一下方便以后使用!
提示:以下是本篇文章正文内容,下面案例可供参考
一、简介
编写语言是Qt与C++ ,开发环境VS2017。自定义按钮继承于QPushButton,自定义主要包含按钮text文本旋转角度功能。封装一个按钮类,ui里面进行提升这个按钮类。
二、自定义按钮类
1.头文件
代码如下(示例):
#pragma once
#include <QPushButton>
class QButtonTextRotate : public QPushButton
{
Q_OBJECT
public:
QButtonTextRotate(QWidget *parent);
~QButtonTextRotate();
void setFontColor(QColor _qColor);
void initBtn();
protected:
void mousePressEvent(QMouseEvent* ev);
void mouseReleaseEvent(QMouseEvent* ev);
void enterEvent(QEvent* ev);
void leaveEvent(QEvent* ev);
void paintEvent(QPaintEvent *pEvent);
signals:
void clicked();
private:
bool bPressBtn = false;//鼠标按下
bool benterBtn = false;
QColor mQColor = QColor(255,0,0);
};
2.执行文件.cpp
代码如下(示例):
#include "QButtonTextRotate.h"
#include <qpainter.h>
#pragma execution_character_set("utf-8")
QButtonTextRotate::QButtonTextRotate(QWidget *parent)
: QPushButton(parent)
{
this->setStyleSheet("QPushButton {border: 0.05em solid lightgray;}");
}
QButtonTextRotate::~QButtonTextRotate()
{
}
void QButtonTextRotate::mousePressEvent(QMouseEvent * ev)
{
// 鼠标被按下, 发射这个自定义信号
bPressBtn = true;
emit clicked();
update(); //调用绘制函数,刷新界面
QPushButton::mousePressEvent( ev);
}
void QButtonTextRotate::mouseReleaseEvent(QMouseEvent * ev)
{
// 鼠标被按下, 发射这个自定义信号
bPressBtn = false;
update(); //调用绘制函数,刷新界面
QPushButton::mouseReleaseEvent(ev);
}
void QButtonTextRotate::enterEvent(QEvent * ev)
{
// 鼠标被按下, 发射这个自定义信号
benterBtn = true;
update(); //调用绘制函数,刷新界面
QPushButton::enterEvent(ev);
}
void QButtonTextRotate::leaveEvent(QEvent * ev)
{
// 鼠标被按下, 发射这个自定义信号
benterBtn = false;
update(); //调用绘制函数,刷新界面
QPushButton::leaveEvent(ev);
}
void QButtonTextRotate::initBtn()
{
}
void QButtonTextRotate::setFontColor(QColor _qColor)
{
mQColor = _qColor;
}
void QButtonTextRotate::paintEvent(QPaintEvent *pEvent)
{
Q_UNUSED(pEvent);
QPainter painter(this);
painter.save();
if (!bPressBtn)
{
painter.fillRect(this->rect(), QColor(225, 225, 225));
if (benterBtn)
{
painter.fillRect(this->rect(), QColor(229, 241, 251));
}
else
{
painter.fillRect(this->rect(), QColor(225, 225, 225));
}
}
if (bPressBtn)
{
painter.fillRect(this->rect(), Qt::green);
}
QPen pen;
pen.setColor(Qt::gray);
pen.setWidth(2);
painter.setPen(pen);
painter.drawRect(this->rect());
//内部填充颜色
//painter.fillRect(QRect(15, 15, 190, 190), Qt::green);
//painter.setBrush(Qt::green);
//painter.drawRect(this->rect());
QString str = this->text();
//painter.drawText(100, 100, u8"正常文字");
painter.setPen(QPen(mQColor, 2));
//painter.drawPoint(this->rect().width()/2, this->rect().height()/2);
QString rotateText = str;
painter.translate(this->rect().width()/2-8, this->rect().height() / 2-50); // 第1步:变换旋转中心到所绘制文字左下角
painter.rotate(+90); // 第2步: 旋转一定角度
painter.drawText(0, 0, rotateText); // 第3步: 绘制文字
painter.resetMatrix(); // 第4步: 恢复坐标旋转
painter.restore();
}
3.效果图片