将QColorDialog添加到QHBoxLayou

2024-04-25 02:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个图片编辑器,你可以在右边选择颜色,在屏幕的左边编辑图片。 所以我需要一个QHBoxLayout来设置我的两个窗口并排。我无法将ColorDialog添加到QHBoxLayout。为了测试,我用了一个按钮而不是图片。你知道吗

我很想用.addWidget添加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()

Tags: self编辑屏幕颜色def图片编辑器按钮
1条回答
网友
1楼 · 发布于 2024-04-25 02:18:29

你知道吗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的cancel按钮是不必要的,因为我隐藏了什么。你知道吗

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())

相关问题 更多 >