python - 将 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()
解决方案
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())
推荐阅读
- r - R rvest 检索空表
- wordpress - 我已经为页面启用了类别,如何在 url 中显示页面的类别?
- python - 我需要帮助将 txt 文件中的值添加到一组元组
- c# - 如何将跨度添加到当前没有元素的字符串中的字符?
- angular - Angular Js 7 用它自己的 Base Url 覆盖 azure Web Api url
- haxe - 为具有必需的可为空 int 参数的函数定义可选参数 extern
- php - 从变量中获取部分文本
- symfony - 为 API 配置防火墙
- css - 如何在 CSS 表中设置 wiki 表格格式化类?
- c++ - 是否递增指向 0 大小的动态数组的指针未定义?