gpt4 book ai didi

python - PyQt5:创建具有非透明子项的半透明窗口

转载 作者:太空狗 更新时间:2023-10-29 21:45:51 27 4
gpt4 key购买 nike

我想创建一个具有半透明背景的全屏窗口,但子部件完全可见(一种叠加效果)。

这是我目前所拥有的:

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_())

最佳答案

好吧,虽然它似乎不适用于可用的标志,但您仍然可以使用 Qt.WA_TranslucentBackground,因为可以在该透明度上绘制半透明矩形。

从 QMainWindow 派生主窗口并改用该类。

应用 self.setAttribute(Qt.WA_TranslucentBackground, True) 到那个类

像这样实现你的主窗口类的paintEvent(类似的,可能有错误,但原理应该有效):

QPixmap canvas(rect())

canvas.fill(Qt.transparent) # fill transparent (makes alpha channel available)

QPainter p(canvas) # draw on the canvas
p.setOpacity(0.3)
p.setBrush(QBrush(Qt.white)) # use the color you like
p.setPen(QPen(Qt.transparen))

p.drawRect(rect()) # draws the canvas with desired opacity

p.start(self) # now draw on the window itself
p.drawPixmap(rect(), canvas)

关于python - PyQt5:创建具有非透明子项的半透明窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982167/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com