Qt之窗体透明 (三种不同的方法和效果)

关于窗体透明,经常遇到,网上的资料倒不少,也不知道写的时候是否验证过,很多都不正确。。。今天就在此一一阐述!

    以下各效果是利用以前写过的一个小程序作为示例进行讲解!(代码过多,贴主要部分)

正常状态

效果如下:

Qt之窗体透明

    这部分代码就不贴了(主要讨论透明效果)。
 

一、全透明

    setWindowOpacity(0.5);

    取值范围为:0.0 - 1.0,默认值为1.0,全透明为0.0,不透明则为1.0。

效果如下:

Qt之窗体透明


    显而易见,窗体及其子窗体全部透明!

二、主窗体透明(子窗体不透明)

1、主窗体采用背景色

setAttribute(Qt::WA_TranslucentBackground, true);

void paintEvent(QPaintEvent *event)

{

    QPainter painter(this);

    painter.fillRect(this->rect(), QColor(0, 0, 255, 80));  //QColor最后一个参数80代表背景的透明度

}

效果如下:

Qt之窗体透明

    显而易见,主窗体透明而子窗体不透明!

2、主窗体采用背景图片

setAttribute(Qt::WA_TranslucentBackground, true);

void QZXingWidget::paintEvent(QPaintEvent *event)

{

    QPixmap covert_pixmap(":/Images/background");

    QPixmap pixmap(covert_pixmap.width(), covert_pixmap.height());

    pixmap.fill(Qt::transparent); 

    QPainter painter(&pixmap);

    QPoint start_point(0, 0);

    QPoint end_point(0, pixmap.height());

    //QLinearGradient进行渐变色设置

    QLinearGradient linear_gradient(start_point, end_point);

    linear_gradient.setColorAt(0, QColor(255, 255, 255, 100));

    linear_gradient.setColorAt(0.5, QColor(255, 255, 255, 150));

    linear_gradient.setColorAt(1, QColor(255, 255, 255, 255));

    painter.fillRect(this->rect(), QBrush(linear_gradient));

    painter.setCompositionMode(QPainter::CompositionMode_SourceIn); 

    painter.drawPixmap(0, 0, covert_pixmap);

    painter.end();

    QPainter painter2(this);

    painter2.drawPixmap(0, 0, pixmap);

}

效果如下:

Qt之窗体透明

    显而易见,主窗体透明而子窗体不透明!

三、子窗体透明(主窗体不透明)

    这部分我就不过多阐述了,请参考:Qt之透明提示框(模拟QQ).

http://blog.sina.com.cn/s/blog_a6fb6cc90101i19x.html

猜你喜欢

转载自blog.csdn.net/Think88666/article/details/86180480