在运行QMainWindow时如何运行QColorDialog窗口?

时间:2018-11-05 23:31:18

标签: python pyqt pyqt5 qcolordialog

使用PyQt5,我想使用QColorDialog小部件来获取颜色,但是要保持QMainWindow运行,以便可以在主GUI中立即更新对颜色的任何更改。用户不必按“确定”即可将新颜色发送到主GUI,它将不断更新以匹配子窗口中当前存在的任何颜色。使用QColorDialog可以吗?

1 个答案:

答案 0 :(得分:0)

仅当使用Qt的QColorDialog而不是每个操作系统的本机时,您才能获得在调色板上单击的颜色,因此必须使用QColorDialog::DontUseNativeDialog设置选项:

from PyQt5 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)

        button = QtWidgets.QPushButton("Open QColorDialog")
        self.label = QtWidgets.QLabel("Background", alignment=QtCore.Qt.AlignCenter)
        self.label.setAutoFillBackground(True)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(button)
        lay.addWidget(self.label)

        self.color_dialog = QtWidgets.QColorDialog(self)
        self.color_dialog.setOptions(QtWidgets.QColorDialog.DontUseNativeDialog |
                                     QtWidgets.QColorDialog.NoButtons)
        self.color_dialog.currentColorChanged.connect(self.on_currentColorChanged)
        button.clicked.connect(self.color_dialog.show)

    @QtCore.pyqtSlot(QtGui.QColor)
    def on_currentColorChanged(self, color):
        pal = self.label.palette()
        pal.setColor(QtGui.QPalette.Background, color)
        self.label.setPalette(pal)
        # or
        # self.label.setStyleSheet("background-color: {}".format(color.name()))

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())