pyqt5通过颜色对话框来改变多个部件的背景颜色,代码实现
时间: 2023-06-03 18:02:26 浏览: 168
请参考以下代码实现:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFrame, QColorDialog
class Mainwindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建多个部件
self.button1 = QPushButton('按钮1', self)
self.button2 = QPushButton('按钮2', self)
self.frame = QFrame(self)
self.frame.setStyleSheet('background-color: yellow')
# 设置部件位置和大小
self.button1.setGeometry(50, 50, 100, 30)
self.button2.setGeometry(50, 100, 100, 30)
self.frame.setGeometry(50, 150, 100, 100)
# 连接颜色对话框和槽函数
self.color_picker = QColorDialog(self)
self.color_picker.colorSelected.connect(self.change_color)
def change_color(self):
color = self.color_picker.currentColor().name()
# 改变多个部件的背景颜色
self.button1.setStyleSheet(f'background-color:{color}')
self.button2.setStyleSheet(f'background-color:{color}')
self.frame.setStyleSheet(f'background-color:{color}')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Mainwindow()
window.show()
sys.exit(app.exec_())
```
运行后,打开颜色对话框,选择颜色即可改变多个部件的背景颜色。
阅读全文