首页 > 解决方案 > 将 QColorDialog 添加到 QHBoxLayout

问题描述

我正在尝试制作一个图片编辑器,您可以在其中选择右侧的颜色并在屏幕左侧编辑图片。所以我需要一个 QHBoxLayout 来并排设置我的两个窗口。我无法将我的 ColorDialog 添加到 QHBoxLayout。出于测试目的,我使用了一个按钮而不是图片。

我厌倦了用 .addWidget 添加 ColorDialog 但它没有用。ColorDialog 仍然显示,但侧面没有按钮。

def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    color = QColorDialog.getColor()

    horizontalbox = QHBoxLayout
    cancelbutton = QPushButton("CancelButton")
    horizontalbox.addWidget(cancelbutton)
    horizontalbox.addWidget(color)

    self.setLayout(horizontalbox)
    self.show()

标签: pythonpyqtpyqt5qcolordialog

解决方案


QColorDialog.getColor() 是一个静态方法,仅返回一个选定的 QColor 不允许获取小部件,因此您不应使用该方法,但您必须创建一个 QColorDialog 类的对象,如下所示。

def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)

    colordialog = QColorDialog()
    colordialog.setOptions(QColorDialog.DontUseNativeDialog)
    colordialog.currentColorChanged.connect(self.on_color_changed)

    cancelbutton = QPushButton("CancelButton")

    horizontalbox = QHBoxLayout(self)
    horizontalbox.addWidget(cancelbutton)
    horizontalbox.addWidget(colordialog)
    self.show()

def on_color_changed(self, color):
    print(color)

更新:

QColorDialog 是一个对话框窗口,其预定义的行为是关闭窗口,因此一个可能的解决方案是断开单击信号与按钮的连接,并且在按下后获得颜色必须使用连接到另一个插槽的单击信号。由于我隐藏了什么,我还看到 QColorDialog 的取消按钮是不必要的。

def initUI(self):

    self.colordialog = QColorDialog()
    self.colordialog.setOptions(QColorDialog.DontUseNativeDialog)

    button_box = self.colordialog.findChild(QtWidgets.QDialogButtonBox)
    ok_button = button_box.button(QDialogButtonBox.Ok)
    ok_button.disconnect()
    ok_button.clicked.connect(self.on_ok_button_clicked)

    # hide cancelbutton
    cancel_button = button_box.button(QDialogButtonBox.Cancel)
    cancel_button.hide()

    cancelbutton = QPushButton("CancelButton")

    horizontalbox = QHBoxLayout(self)
    horizontalbox.addWidget(cancelbutton)
    horizontalbox.addWidget(self.colordialog)
    self.show()


def on_ok_button_clicked(self):
    color = self.colordialog.currentColor()
    print(color.name())

推荐阅读