问题描述
我正在尝试在Qt中创建一个圆形按钮。在设计器中创建了一个带有单个按钮 QPushButton
的简单表单。我正在尝试使用 setMask()
将其变为圆形按钮。一旦应用 setMask()
,按钮就会消失。
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();
}
注意:如果按钮是在代码中创建并应用于在显示窗口之前的窗口中,显示按钮。我想使用Qt Designer的WYSIWIG功能,而不是在代码中创建整个表单。
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.
推荐答案
它将变得不可见,但这是因为您没有将椭圆围绕正确的点。
It is going invisible, but its because you do not have the ellipse centered around the correct point.
QWidget :: setMask 仅导致零件
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。为什么要两次设置按钮的高度?我假设这是一个错字,而您的意思是宽度。
Ps. Why do you set the height of the pushButton twice? I'm assuming that's a typo and you meant width.
这篇关于将矩形Qt按钮更改为圆形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!