让QWidget透明化

时间:2014-08-23 20:23:24

标签: c++ qt qt4

我有一个基于QWidget的覆盖小部件,它应该绘制一些文本并在我的应用程序的中央小部件上进行。问题是我无法将叠加小部件的背景设置为透明。我已经尝试过了:

  1. setPalette(Qt::transparent);
  2. setAttribute( Qt::WA_TranslucentBackground, true );
  3. setAttribute( Qt::WA_OpaquePaintEvent, true );
  4. setAutoFillBackground(false);
  5. setStyleSheet("QWidget{background-color: transparent;}");
  6. setAttribute(Qt::WA_NoSystemBackground);

3 个答案:

答案 0 :(得分:16)

我最好猜测显示一个叠加窗口小部件,将窗口小部件转换为窗口,将其大小调整为内容并手动将它们移动到所需位置。

MainWindow示例,在视频小部件的中心显示重叠小部件:

Mwindow::Mwindow()
{
    widget = new Widget(this);
}

void Mwindow::widgetSizeMove()
{
    if (widget->width() <= videoWidget->width() && widget->height() <= videoWidget->height())
    {
        widget->setWindowOpacity(1); // Show the widget
        QPoint p = videoWidget->mapToGlobal(videoWidget->pos());
        int x = p.x() + (videoWidget->width() - widget->width()) / 2;
        int y = p.y() + (videoWidget->height() - widget->height()) / 2;
        widget->move(x, y);
        widget->raise();
    }
    else
    {
        widget->setWindowOpacity(0); // Hide the widget
    }
}

bool Mwindow::event(QEvent *event)
{
    switch (event->type())
    {
    case QEvent::Show:
        widget->show();
        QTimer::singleShot(50, this, SLOT(widgetSizeMove())); 
        //Wait until the Main Window be shown
        break;
    case QEvent::WindowActivate:
    case QEvent::Resize:
    case QEvent::Move:
        widgetSizeMove();
        break;
    default:
        break;
    }

    return QMainWindow::event(event);
}

小部件示例:

Widget::Widget(QWidget *parent) : QWidget(parent)
{
    setWindowFlags(Qt::Window | Qt::FramelessWindowHint);

    setAttribute(Qt::WA_NoSystemBackground);
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_PaintOnScreen);

    setAttribute(Qt::WA_TransparentForMouseEvents);
}

void Widget::paintEvent(QPaintEvent*)
{
    QPainter p(this);
    QString text = "Some foo goes here";
    QFontMetrics metrics(p.font());
    resize(metrics.size(0, text));
    p.drawText(rect(), Qt::AlignCenter, text);
}

使用LibVLC显示视频时的示例:

VLC based player

答案 1 :(得分:8)

最佳解决方案由Gökmen Gökselarticle

的一条评论中提供
setStyleSheet("background-color: rgba(0,0,0,0)");

答案 2 :(得分:6)

在Linux上使用:

setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_TransparentForMouseEvents);