简体   繁体   中英

Is there no way to change background color DYNAMICALLY in PyQt5?

I'm writing an application in Python, using PyQt5. I really want to change the background of QLable, QTextEdit, or anything that I can show some colors DYNAMICALLY.

I already saw a lot of examples of changing the background color of something, but all of them seems that I need to make some "palette" thing in advance.

What I want to do is that change background color based on the user's keyboard input which indicates a color like this: #fffff or (255, 255, 255) . So is there really no way to implement this??

It doesn't matter the type of object I should use. It's just enough to be a rectangle shape.

Here is a basic example how to change the background colour dynamically by using setStyleSheet . The background color of the widget changes to whatever color is entered on the input line. Colors can be entered as a named html color (red, blue, yellow, etc.) or as a hex code in the form #rrggbb.

from PyQt5 import QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QtWidgets.QHBoxLayout(self)
        self.line_edit = QtWidgets.QLineEdit()
        self.line_edit.setPlaceholderText('Enter a color')
        self.line_edit.setStyleSheet('QLineEdit {background-color:white}')
        layout.addWidget(self.line_edit)

        self.line_edit.editingFinished.connect(self.change_background)

    def change_background(self):
        col = self.line_edit.text()
        self.setStyleSheet(f'QWidget {{background-color: {col};}}')
        self.line_edit.clear()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    widget = Widget()
    widget.resize(400,300)
    widget.show()
    app.exec()

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