Qt-设置倒角界面

 

实例代码:

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
View Code

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include "TWidget.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
View Code

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(QStringLiteral("Qt设置倒角界面"));

    TWidget *o = new TWidget(this);
    o->move(100, 100);
    o->resize(100, 30);
}

MainWindow::~MainWindow()
{
    delete ui;
}
View Code

TWidget.h

#ifndef TEDIT_H
#define TEDIT_H

#include <QWidget>
#include <QPainter>
#include <QStyleOption>
#include <QBitmap>
#include <QLineEdit>
#include <QMouseEvent>

class TWidget : public QWidget
{
    Q_OBJECT
public:
    TWidget(QWidget *parent = nullptr);
    ~TWidget();

protected:
    void paintEvent(QPaintEvent *event) override;
private:
    QLineEdit *m_pEdit = nullptr;
};

#endif // TEDIT_H
View Code

TWidget.cpp

#include "TWidget.h"

TWidget::TWidget(QWidget *parent)
    : QWidget(parent)
{
    m_pEdit = new QLineEdit(this);
    m_pEdit->setText("123");

//   setStyleSheet("TWidget{"
//                         "border-radius: 10px;"
//                         "background: white;"
//                         "}");
}

TWidget::~TWidget()
{
}

void TWidget::paintEvent(QPaintEvent *event)
{
    //绘制样式
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式

    QBitmap bmp(this->size());
    bmp.fill();
    QPainter painter(&bmp);

    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
    painter.setRenderHint(QPainter::Antialiasing);
    //设置边框为圆角12px
    painter.drawRoundedRect(bmp.rect(), 12, 12);
    setMask(bmp);
    QWidget::paintEvent(event);

}
View Code

 

posted on 2023-09-07 11:03  疯狂delphi  阅读(51)  评论(0编辑  收藏  举报

导航