linux下qt窗口半透明居中实现
一. 背景:
上一个星期(2022年1月左右)一直没成功,不是设成transparent,背景却变成黑色,就是setAttribute(Qt::WA_NoSystemBackground, true);只是变成了全透明,这次成功了!
二.具体实现:
- 第一步设置成全透明
setAutoFillBackground(false); //这个不设置的话就背景变黑
setAttribute(Qt::WA_NoSystemBackground, true);
//setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground,true);
- 重载paintEvent函数
void userWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(255, 255, 255, 127)); //设置成白色,127代表透明度
painter.drawRect(0, 0, this->width(), this->height());//绘制矩形
}
3.设置窗口居于屏幕中间
QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
move((desktop->width() - this->width())/2, (desktop->height() - this->height())/2);
补充评论的
当环境是用于开发板(类似型号如sigmastar222d),qt4时,设置背景透明如下:
this->setAttribute(Qt::WA_TranslucentBackground);
QWSServer::setBackground(QColor(255,255,255,0));//窗口背景设置透明