简体   繁体   中英

How to make a QWidget based window have a transparent background?

Example code is here and it runs like that, the image looks like:

时钟 .

The main strategy is to use the QBrush to load a backgroud image that has a number and other stuff, the picture originally has the transparent background.

But how to make the QWidget window have a transparent backgroud has stucked me.

In PyQt, you need to add the flag to all your existing window flags using the bitwise OR operator |, to make it work:

window.setWindowFlags(window.windowFlags() | QtCore.Qt.FramelessWindowHint)

And then do window.setAttribute(QtCore.Qt.WA_TranslucentBackground)

Remember to call the show() method after setting flags. Quoting the docs here:

Note: This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again..

On the bitwise operator: https://wiki.python.org/moin/BitwiseOperators

Hope that was useful.

Edit: Removed some incorrect information, Thanks to @ekhumoro's comments from below.

If you need to have a window (based QWidget) with transparent background you can to my knowledge only achieve this if you also make the window frameless.

The following example does that. Important are setting window flag FramelessWindowHint and setting attribute WA_TranslucentBackground .

from PySide import QtCore, QtGui

app = QtGui.QApplication([])

window = QtGui.QWidget()
window.setWindowFlags(QtCore.Qt.FramelessWindowHint)
window.setAttribute(QtCore.Qt.WA_TranslucentBackground)
window.show()

layout = QtGui.QVBoxLayout(window)
button = QtGui.QPushButton('Exit')
button.clicked.connect(app.quit)
layout.addWidget(button)

app.exec_()

Which only shows a freestanding button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM