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


// 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函數來做都行)。最關鍵的是這種方法下透明度的操作不會影響到子控件的。

這里的

轉自:http://www.qtcn.org/bbs/read.php?tid=31817

http://blog.csdn.net/zzwdkxx/article/details/30034403


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM