zoukankan      html  css  js  c++  java
  • 教你如何用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

  • 相关阅读:
    利用Sentinel实现Redis主从切换
    Docker应用一:docker介绍
    利用RAP搭建可视化接口管理平台
    Lucene初步搜索
    Lucene索引的初步创建
    kettle不能正常自动获取字段
    配置hive元数据库mysql时候出现 Unable to find the JDBC database jar on host : master
    Lost connection to MySQL server at ‘reading initial communication packet', system error: 0 mysql远程连接问题
    Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111)解决方法
    Sqoop import加载HBase案例详解
  • 原文地址:https://www.cnblogs.com/findumars/p/5805078.html
Copyright © 2011-2022 走看看