Qt设置按钮为圆形

通过Qt 的样式表实现圆形按钮,其也可以实现圆角按钮,当然也可以使用其他的方式,比如说,通过派生按钮类使用绘图事件,进行一个图形的绘制,或者是通过自定义一个类,通过信号与槽的机制与绘图事件的配合也能实现!当然每种方法都各有千秋,各有优点,在这里将使用不破坏类机制的方式进行对按钮UI的圆型或者圆角矩形的绘制!

 

核心代码:
#include “widget.h”
#include “ui_widget.h”
#include
//根据加载文件的方式,将qss文件导入!

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->resize(800,600); //设置主窗口大小
button = new QPushButton(“Love”,this); //创建按钮
button->setGeometry((this->width()-300)/2,(this->height()-300)/2,300,300);
//根据窗口,去设置按钮的位置
button_style(); //设置按钮的样式
}

void Widget::button_style()
{
QFile file(":/new/prefix1/button.qss"); //通过文件路径创建文件对象
file.open(QFile::ReadOnly); //文件打开方式
QString str = file.readAll(); //获取qss中全部字符
this->setStyleSheet(str); //设置样式表
}

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

样式表设置区*
QPushButton { //设置图1的样式表方式
font-size:100px; //文字大小
color:yellow; //前景色也就是字体颜色
border-radius:150px; //圆角大小,因为矩形的一半为150,所以圆角大小 设置为150以后,将会成为一个原型,小于150,就是圆角矩形了。
background-color:rgba(0,255,0,200); //设置按钮背景为绿色
}

QPushButton:hover { //设置图1的样式表方式:悬停状态
font-size:100px;
color:green;
border-radius:150px;
background-color:rgba(255,255,0,200); //设置按钮背景为黄色 = 红+绿
}
QPushButton:pressed { //设置图1的样式表方式:按下状态
color:orange;
border-width:3;
border-color:orange;
border-style:solid;;
background-color:cyan; //设置按钮背景为青色
}

也可以在 QPushButton 对象下 通过 setStyleSheet()函数直接设置样式表的,但是对于一个部件的多种状态,是有些 不适用的,文件加载这种方式还是蛮好的!
---------------------
设置圆形按钮 最关键的是geometery的宽度和高度要相等,而且通过样式表设置border-radius的值为高度和宽度的一般即可。

 ui->pushButton->setStyleSheet("QPushButton{font-size:100px;color:yellow;border-radius:15px;}");

调色板主要用来也可以用来更改button的颜色

 QPalette pal =ui->pushButton->palette();//调色板
    pal.setColor(QPalette::Button,Qt::red);
    ui->pushButton->setPalette(pal);
    ui->pushButton->setAutoFillBackground(true);
    ui->pushButton->setFlat(true);
    ui->pushButton->setText("");

猜你喜欢

转载自www.cnblogs.com/tsh292278/p/11275819.html
今日推荐