Change the Qt Rectangular Button to Round

I am trying to create a round button in Qt. A simple push-button form was created in the design. I am trying to turn this into a round button using setMask. As soon as setMask is applied, the button disappears. Do I need a custom widget to create a round button?

#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(); } 

Note. If the button is created in code and applied to the window before the window is displayed, the button is displayed. I would like to use the WYSIWIG features for Qt Designer, and not create the entire form in the code.

+8
c ++ qt qt-designer
source share
2 answers

It will be invisible, but this is because you do not have an ellipse centered around the right point.

QWidget :: setMask "causes only parts of the widget that overlap the region to be visible. If pixels outside the widget's rectangle () are included in the region, window system controls in this region may or may not be displayed depending on the platform."

Try using this code and you will see:

 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 = new QRect(0,0,190,190); qDebug() << rect->size(); qDebug() << ui->pushButton->size(); QRegion* region = new QRegion(*rect,QRegion::Ellipse); qDebug() << region->boundingRect().size(); ui->pushButton->setMask(*region); } 

Ps. Why do you set pushButton height twice? I assume the typo and you meant the width.

+15
source share

I think the easiest solution would be to use a stylesheet.

Like this:

  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; 

See also examples and reference .

Please note that you need to create a full style for your button, as the standard style will not apply.

+10
source share

All Articles