简体   繁体   中英

Add QColorDialog to QHBoxLayout

I am trying to make a picture editor where you can choose your color on the right side and edit the picture on the left side of your screen. So I need a QHBoxLayout to set my two windows side by side. I can't add my ColorDialog to the QHBoxLayout. For test purpose I used a button instead of the picture.

I tired to add the ColorDialog with.addWidget but it didn't work. The ColorDialog is still shown but without the button on the side.

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() is a static method only returns a selected QColor does not allow to obtain the widget so you should not use that method but you must create an object of the class QColorDialog as I show below.

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)

Update:

QColorDialog is a dialog window whose predefined behavior is to close the window, so a possible solution is to disconnect the clicked signal from the button, and to get the color after pressing you must use the clicked signal connected to another slot. I also see the cancel button of the QColorDialog unnecessary because of what I have hidden.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM