Change rectangular Qt button to round

DarwinIcesurfer picture DarwinIcesurfer · Oct 4, 2012 · Viewed 35.8k times · Source

I'm trying to create a round button in Qt. A simple form with a single button QPushButton was created in designer. I'm attempting to turn this into a round button using setMask(). As soon as setMask() is applied the button disappeares. Does a custom widget need to be created to make 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 a window before the window is displayed, the button is displayed. I would like to use the WYSIWIG capabilities of the Qt Designer rather than creating the entire form in code.

Answer

stackunderflow picture stackunderflow · Oct 4, 2012

It is going invisible, but its because you do not have the ellipse centered around the correct point.

QWidget::setMask "causes only the parts of the widget which overlap region to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform".

Try this code instead and you'll 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(0,0,190,190);
    qDebug() << rect.size();
    qDebug() << ui->pushButton->size();
    QRegion region(rect, QRegion::Ellipse);
    qDebug() << region.boundingRect().size();
    ui->pushButton->setMask(region);
}

Ps. Why do you set the height of the pushButton twice? I'm assuming that's a typo and you meant width.