将矩形 Qt 按钮更改为圆形

Change rectangular Qt button to round

本文关键字:按钮 Qt      更新时间:2023-10-16

我正在尝试在Qt中创建一个圆形按钮。 在设计器中创建了一个带有单个按钮QPushButton的简单窗体。 我正在尝试使用 setMask() 将其变成圆形按钮。 一旦应用setMask()按钮就会消失。 是否需要创建自定义小部件来制作圆形按钮?

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QtGui/QPushButton>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->pushButton->setText("Test Text");
    ui->pushButton->setFixedHeight(200);
    ui->pushButton->setFixedWidth(200);
    //Set Starting point of region 5 pixels inside , make region width & height
    //values same and less than button size so that we obtain a pure-round shape
    QRegion* region = new QRegion(*(new QRect(ui->pushButton->x()+5,ui->pushButton->y()+5,190,190)),QRegion::Ellipse);
    ui->pushButton->setMask(*region);
    ui->pushButton->show();

}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_pushButton_clicked()
{
    QMessageBox msgbox;
    msgbox.setText("Text was set");
    msgbox.show();
}

注意: 如果在代码中创建按钮并在显示窗口之前应用于窗口,则会显示该按钮。 我想使用Qt设计器的所见即所得功能,而不是在代码中创建整个表单。

它变得不可见,但这是因为您没有以正确点为中心的椭圆。

QWidget::setMask"仅导致与区域重叠的小部件部分可见。如果该区域包含小部件 rect() 之外的像素,则该区域中的窗口系统控件可能可见,也可能不可见,具体取决于平台"。

请尝试此代码,您将看到:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->pushButton->setText("Test Text");
    ui->pushButton->setFixedHeight(200);
    ui->pushButton->setFixedWidth(200);
    QRect rect(0,0,190,190);
    qDebug() << rect.size();
    qDebug() << ui->pushButton->size();
    QRegion region(rect, QRegion::Ellipse);
    qDebug() << region.boundingRect().size();
    ui->pushButton->setMask(region);
}

附言。为什么要将按钮的高度设置两次?我假设这是一个错字,你的意思是宽度。

我认为最简单的解决方案是使用样式表。

喜欢这个:

 background-color: white;
 border-style: solid;
 border-width:1px;
 border-radius:50px;
 border-color: red;
 max-width:100px;
 max-height:100px;
 min-width:100px;
 min-height:100px;

另请参阅示例和参考。

请注意,您必须为按钮创建完整的样式,因为标准样式将不适用。

这将

完美地工作,试试这个 -

QPushButton {
color: #333;
border: 2px solid #555;
border-radius: 20px;
border-style: outset;
background: qradialgradient(
cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 #fff, stop: 1 #888
);
padding: 5px;
}
QPushButton:hover {
background: qradialgradient(
cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 #fff, stop: 1 #bbb
);
}