教你如何用Qt做透明的窗体,setMask,Qt,Opacity

来源:互联网 发布:润和软件待遇 编辑:程序博客网 时间:2024/05/01 17:58
点击打开链接
// In this function, we can get the height and width of the current widget
void Widget::resizeEvent(QResizeEvent *)
{
    // Use a bitmap as a mask. A bitmap only has two kind of colors: white(value is 0)
    // or black(other values). When we use it to set mask, we can see the window at the position
    // where the color value is 0, and other place will be transparent.
    QBitmap bitMap(width(),height()); // A bit map has the same size with current widget
    QPainter painter(&bitMap);
    painter.setPen(QColor(255,255,255)); // Any color that is not QRgb(0,0,0) is right
    painter.drawRect(0,0,width(),height());

    // Now begin to draw the place where we want to show it
    painter.setPen(QColor(0,0,0));
    drawTextOnWin(&painter);
    drawImageOnWin(&painter);

    setMask(bitMap);
}
void Widget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(QColor(Qt::red));
    // As the place where we want to draw has been set opaque in the resizeEvent, so what we draw here
    // will be shown
    drawTextOnWin(&painter);
    drawImageOnWin(&painter);
}
void Widget::drawTextOnWin(QPainter *painter)
{
    painter->setFont(QFont(font().family(),15));
    painter->drawText( (width()-300)/2,0,300,50,Qt::AlignHCenter,"Now you can see me!");
}
void Widget::drawImageOnWin(QPainter *painter)
{
    QPixmap imageTest(":/imageItem/pngImage.png");
    painter->drawPixmap( (width()-imageTest.width())/2, (height()-imageTest.height())/2,
                          imageTest.width(), imageTest.height(), imageTest );
}

上面是源码。附件里是效果图。
Qt提供了setOpacity的函数,但是使用之后,窗体所有子控件都变成同样的透明色了。
这里我们利用setMask()函数,以QBitmap为参数,通过对QBitmap做精细的操作(关键在于QBitmap支持用painter直接在上面绘制),最终达到这样的效果:我们想要透明的地方变成透明,我们想要放置部件的地方变成非透明可见的。这样就达到了我们想要的效果。
具体实现的方法也很简单:如果你想在paintEvent里面绘制任何内容,也要同时在QBitmap上做绘制,前提是在QBitmap上绘制的时候画笔的rgb设置成QRgb(0,0,0)。
道理我已经讲明白了。大家可以自己把代码弄到自己的类里面实验一下。
例子中只是最简单的演示,按照这个思路我想可以做出更多更灵活的应用的,比如可以让窗体介于透明和非透明之间(这里需要准备一个对应的透明色的png图片,或者使用相应的Qt函数来做都行)。最关键的是这种方法下透明度的操作不会影响到子控件的。
这里的
图片:An_Example_How_To_Draw_A_Transparent_Widget.png 
转载:教你如何用Qt做透明的窗体,setMask,Qt,Opacity - 楚江北 - 矮子爬梯
原创粉丝点击