将 Window 属性重置为默认 pyqt5

Reset Window Attribute to default pyqt5

我有一个小问题。 我可以使用以下代码使小部件的背景透明。

self.setwindowFlags(Qt.WA_TranslucentBackground)

应用后,我想通过任何事件将其恢复到初始状态。 帮帮我。

一个非常基本的解决方案是存储当前状态,以便您最近可以恢复它。

请注意,如果 setWindowFlags 在显示 小部件后 被调用,您可能需要 explicitly show it again:

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..

class SomeWidget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.defaultWindowFlags = self.windowFlags()
        self.setwindowFlags(Qt.WA_TranslucentBackground)

        # ...
        self.restoreButton = QtWidgets.QPushButton('Restore state')
        # ...
        self.restoreButton.clicked.connect(self.restoreFlags)

    def restoreFlags(self):
        # setWindowFlags calls setParent(), so you might need to show it again if
        # it was visible before; let's store the current state
        isVisible = self.isVisible()
        self.setWindowFlags(self.defaultWindowFlags)
        if isVisible:
            self.setVisible(True)

试一试:

import sys
from PyQt5 import QtWidgets, QtCore


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        self.widget = QtWidgets.QWidget(self)
        self.widget.setStyleSheet('.QWidget {background-color: blue;}')
        self.widget.setObjectName('widget')
        self.widget.setFixedSize(700, 500)

        close_button = QtWidgets.QPushButton('close window', clicked=self.close)

        self.change_button = QtWidgets.QPushButton('change StyleSheet')
        self.change_button.setCheckable(True)
        self.change_button.toggled.connect(self.button_state_func)   

        layout = QtWidgets.QGridLayout(self.widget)
        layout.addWidget(close_button)
        layout.addWidget(self.change_button)

    def button_state_func(self, state):
        if state:
            self.widget.setStyleSheet('QWidget#widget {background-color: transparent;}')
        else:
            self.widget.setStyleSheet('QWidget#widget {background-color: yellow;}')       
        

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())