我想创建一个半透明背景的全屏窗口,但是完全可见的子窗口小部件(覆盖效果的种类).
这是我到目前为止所拥有的:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
# Create the main window
window = QMainWindow()
window.setWindowOpacity(0.3)
window.setAttribute(Qt.WA_NoSystemBackground, True)
window.setWindowFlags(Qt.FramelessWindowHint)
# Create the button
pushButton = QPushButton(window)
pushButton.setGeometry(QRect(240, 190, 90, 31))
pushButton.setText("Finished")
pushButton.clicked.connect(app.quit)
# Center the button
qr = pushButton.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
pushButton.move(qr.topLeft())
# Run the application
window.showFullScreen()
sys.exit(app.exec_())
这会产生半透明效果,但即使按钮也是半透明的.
我也试过替换了
window.setWindowOpacity(0.3)
通过这个电话
window.setAttribute(Qt.WA_TranslucentBackground, True)
但无济于事,在这种情况下,背景是完全透明的(按钮正确完全可见).
解决方案:(感谢Aaron的建议):
诀窍在于为主窗口实现自定义paintEvent.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class CustomWindow(QMainWindow):
def paintEvent(self, event=None):
painter = QPainter(self)
painter.setOpacity(0.7)
painter.setBrush(Qt.white)
painter.setPen(QPen(Qt.white))
painter.drawRect(self.rect())
app = QApplication(sys.argv)
# Create the main window
window = CustomWindow()
window.setWindowFlags(Qt.FramelessWindowHint)
window.setAttribute(Qt.WA_NoSystemBackground, True)
window.setAttribute(Qt.WA_TranslucentBackground, True)
# Create the button
pushButton = QPushButton(window)
pushButton.setGeometry(QRect(240, 190, 90, 31))
pushButton.setText("Finished")
pushButton.clicked.connect(app.quit)
# Center the button
qr = pushButton.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
pushButton.move(qr.topLeft())
# Run the application
window.showFullScreen()
sys.exit(app.exec_())