如何使全窗口透明而按钮和标签不透明

时间:2018-03-29 19:21:28

标签: qt

如何使全窗口背景透明,但QDialog上的按钮和标签不应该是透明的。

编辑:

我使用的是CENTOS 7和qt5.5。下面是我尝试过的示例代码,其中QDialog应该是透明的而按钮不是。

#include <QtGui>
#include <QDialog>
#include <QPushButton>

class Dialog : public QDialog
{
public:
    Dialog() : QDialog(0, Qt::FramelessWindowHint) // hint is required on Windows
    {
///////////////////////////////////////////////////////////
        setFixedSize(500, 500); // size of the background image
        //setStyleSheet("background-color: rgba(180, 190, 200, 175);");
        setAttribute(Qt::WA_TranslucentBackground);
///////////////////////////////////////////////////////////
        QPushButton *button1 = new QPushButton("Button-1", this);
        button1->setStyleSheet("background-color: rgb(150, 170, 190);");
        button1->setGeometry(0,30,100,30);
///////////////////////////////////////////////////////////
        QPushButton *button2 = new QPushButton("Button-2", this);
        button2->setStyleSheet("background-color: rgb(150, 170, 190);");
        button2->setGeometry(100,90,100,30);
///////////////////////////////////////////////////////////
    }

protected:

};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}

2 个答案:

答案 0 :(得分:0)

如果你想要透明背景:

MainWindow v;

v.setStyleSheet("background:transparent");
v.setAttribute(Qt::WA_TranslucentBackground);

v.setWindowFlags(Qt::FramelessWindowHint);

v.show();

对于按钮,不要忘记在样式表中将边框更改为无边框

答案 1 :(得分:0)

一种简单的方法是窃取对话框几何体并使用它来定位无父按钮,然后自由设置对话框的setWindowOpacity()

#include <QApplication>
#include <QtGui>
#include <QDialog>
#include <QPushButton>

class Dialog : public QDialog
{
public:
    Dialog() : QDialog(0, Qt::FramelessWindowHint) // hint is required on Windows
    {
        setFixedSize(500, 500); // size of the background image
        setWindowOpacity(0.7);
        setWindowFlags(Qt::Tool | Qt::FramelessWindowHint);
        this->show();
        int x = this->geometry().x();
        int y = this->geometry().y();
        this->hide();
        QPushButton *button1 = new QPushButton("Button-1");
        button1->setStyleSheet("background-color: rgb(150, 170, 190);");
        button1->setGeometry(0+x,30+y,100,30);
        button1->setWindowFlags(Qt::FramelessWindowHint);
        QPushButton *button2 = new QPushButton("Button-2");
        button2->setStyleSheet("background-color: rgb(150, 170, 190);");
        button2->setGeometry(x+100,y+90,100,30);
        button1->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
        button2->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
        button1->show();
        button2->show();
    }
protected:

};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();
    return a.exec();
}

请记住,如果父母是关键的话,你可以使用具有对话框的顶级课程和作为孩子的按钮进行更好的设计。

相关问题