将矩形Qt按钮更改为圆形

Dar*_*fer 10 c++ qt qt-designer

我正在尝试在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();

}
Run Code Online (Sandbox Code Playgroud)

注意:如果按钮是在代码中创建的,并且在显示窗口之前应用于窗口,则会显示该按钮.我想使用Qt Designer的WYSIWIG功能,而不是在代码中创建整个表单.

sta*_*low 18

它是不可见的,但它是因为你没有以正确点为中心的椭圆.

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);
}
Run Code Online (Sandbox Code Playgroud)

PS.为什么要设置pushButton的高度两次?我假设这是一个错字,你的意思是宽度.


Lol*_*4t0 13

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

像这样:

 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;
Run Code Online (Sandbox Code Playgroud)

另见示例参考.

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