使QWidget透明 [英] Make QWidget transparent
本文介绍了使QWidget透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 QWidget
的覆盖小部件,应该绘制一些文本,并发生在我的应用程序的中心部件。问题是,我不能设置覆盖小部件的背景是透明的。我已经尝试过:
I have a QWidget
-based overlay widget which should paint some text and take place over the central widget of my application. The problem is that I can't set background of overlay widget to be transparent. What I already tried:
-
setPalette(Qt :: transparent);
li>
-
setAttribute(Qt :: WA_TranslucentBackground,true);
-
setAttribute (Qt :: WA_OpaquePaintEvent,true);
-
setAutoFillBackground(false);
-
setStyleSheet(QWidget {background-color:transparent;});
-
setAttribute(Qt :: WA_NoSystemBackground);
setPalette(Qt::transparent);
setAttribute( Qt::WA_TranslucentBackground, true );
setAttribute( Qt::WA_OpaquePaintEvent, true );
setAutoFillBackground(false);
setStyleSheet("QWidget{background-color: transparent;}");
setAttribute(Qt::WA_NoSystemBackground);
推荐答案
最好猜测显示叠加窗口小部件,将窗口小部件转换为窗口,将其大小调整为其内容并手动将它们移动到所需位置。
My best guess to show an overlay widget, is convert the widget to a window, resize it to it's contents and move them to the desired position manually.
MainWindow示例,在视频窗口小部件中心的重叠小部件:
MainWindow Example, showing the overlay widget in the center of the video widget:
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显示视频时的示例:
Example when showing a video with LibVLC:
这篇关于使QWidget透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文