在日常使用的软件里面,有些软件提示用户时,经常会发现有些提示窗口是半透明的。那么如何实现一个可拖动的、半透明、圆角矩形窗口呢?整体思路:将窗口本身设置为透明,然后通过qss或者绘图的方式来实现半透明的效果。
方法壹(绘图方式)
TransparentWidget::TransparentWidget(QWidget *parent)
: QWidget(parent)
{
setWindowTitle(QString::fromLocal8Bit("透明无边框窗口"));
setFixedSize(480, 320);
setWindowFlag(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
QPushButton *button = new QPushButton("Hello world!", this);
button->setGeometry((geometry().width() - button->width())*0.5,
(geometry().height() - button->height())*0.5,
button->width(), button->height());
}
TransparentWidget::~TransparentWidget()
{}
void TransparentWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(QColor(0, 0, 0, 0x20)));
QRectF rect(0, 0, this->width(), this->height());
painter.drawRoundedRect(rect, 20, 20);
}
void TransparentWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_startPoint = frameGeometry().topLeft() - event->globalPos();
}
}
void TransparentWidget::mouseMoveEvent(QMouseEvent *event)
{
this->move(event->globalPos() + m_startPoint);
}
方法壹的效果图
方法贰(qss方式)
TransparentWidget::TransparentWidget(QWidget *parent)
: QWidget(parent)
{
setWindowTitle(QString::fromLocal8Bit("透明无边框窗口"));
setFixedSize(480, 320);
setWindowFlag(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
QWidget* shadow = new QWidget(this);
shadow->setGeometry(0, 0, this->width(), this->height());
QString style("QWidget{border-radius:10px; background-color:rgba(0,0,0,0.4);}");
shadow->setStyleSheet(style);
QPushButton *button = new QPushButton("Hello world!", this);
button->setGeometry((geometry().width() - button->width())*0.5,
(geometry().height() - button->height())*0.5,
button->width(), button->height());
}
方法贰的效果图
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)