Qt 之自定义控件(开关按钮)
Qt自定义控件13:继承QPushButton自绘按钮
有两种方式一个是继承 QPushButton;一个是继承 QWidget
这里选择继承 QPushButton(方便点)
要实现控件一下效果
需要重写paintEvent(QPaintEvent *event)
#include "SwitchControlButton.h"
#include<QPainter>
SwitchControlButton::SwitchControlButton(QWidget *parent )
:QPushButton(parent)
{
setCheckable(true);
this->setMinimumWidth(height()*2);
//圆角
this->setStyleSheet("QPushButton{ border-radius:10px;}");
}
SwitchControlButton::~SwitchControlButton()
{
}
void SwitchControlButton::paintEvent(QPaintEvent *event)
{
//绘制准备工作,启用反锯齿
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
drawBackground(&painter);
drawRect(&painter);
drawText(&painter);
}
void SwitchControlButton::drawText(QPainter *painter)
{
int width = this->width();
int height = this->height();
painter->save();
QRect rect;
if (isChecked())
{
rect = QRect(0, 0, width-height, height);
}
else
{
rect = QRect(height, 0, width - height, height);
}
QFont font = painter->font();
painter->setFont(font);
QString text = this->text();
painter->setPen(m_textColor);
painter->drawText(rect, Qt::AlignCenter, text);
painter->restore();
}
void SwitchControlButton::drawBackground(QPainter *painter)
{
int width = this->width();
int height = this->height();
painter->save();
if (isChecked())
{
painter->setBrush(m_CheckedBgColor);
}
else
{
painter->setBrush(m_unCheckedBgColor);
}
QRect rect(0, 0, width, height);
painter->setPen(Qt::NoPen);
painter->drawRect(rect);
painter->restore();
}
void SwitchControlButton::drawRect(QPainter *painter)
{
int width = this->width();
int height = this->height();
painter->save();
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(255,255,255));
QRect rect;
if (isChecked())
{
rect = QRect(width - height,0, height, height);
}
else
{
rect= QRect(0, 0, height, height);
}
painter->drawRoundRect(rect);
painter->restore();
}
需要注意的地方有:
绘制背景:void SwitchControlButton::drawBackground(QPainter *painter)
需要设置
painter->setPen(Qt::NoPen);
qt自带的Pen是黑色一像素的笔,会给在背景中加黑框。
如果不需要框出按键,就去掉pen
设置文字时注意 drawText(QPainter *painter)
不要让白色的按钮遮挡文字,所以要计算文字显示的位置,然后放置文字:
QRect rect;
if (isChecked())
{
rect = QRect(0, 0, width-height, height);
}
else
{
rect = QRect(height, 0, width - height, height);
}
QFont font = painter->font();
painter->setFont(font);
QString text = this->text();
painter->setPen(m_textColor);
painter->drawText(rect, Qt::AlignCenter, text);
如果想要绘制圆角的 按钮
这里配置qss时不管用的,因为我们重写了paintEvent事件
所以我们要在paintEvent事件更改
上图样式要更改两个地方
背景绘制函数
void SwitchControlButton::drawBackground(QPainter *painter)
{
//painter->drawRect(rect);这个是直角矩形
painter->drawRoundedRect(rect, 4, 4);//改成圆角矩形
}
绘制小方框的函数
void SwitchControlButton::drawRect(QPainter *painter)
{
painter->drawRoundedRect(rect,3, 3);
//painter->drawRoundRect(rect);
}
这里参数写3是为了 让小方框看起来是嵌进去的
圆角的按钮重写paintEvent事件