Search code examples
pythonpython-3.xpyqtpyqt5qcolordialog

How to show alpha channel in PyQt5 QColorDialog


I have tried this code:

def open_color_dialog(self, label):
    dialog = QColorDialog()
    dialog.setOption(QColorDialog.ShowAlphaChannel, on=True)
    print(dialog.testOption(QColorDialog.ShowAlphaChannel)) #returning True
    color = dialog.getColor()

    if color.isValid():
        label.setStyleSheet("background-color:" + color.name() + ";")

But this code didn't work. How can I show alpha channel ?


Solution

  • The problems are:

    • The dialog object of the QColorDialog class has been created but you use the static QColorDialog::getColor() method that creates a new QColorDialog object that is displayed.

      def open_color_dialog(self, label):
          dialog = QColorDialog()
          dialog.setOption(QColorDialog.ShowAlphaChannel, on=True)
          if dialog.exec_() == QDialog.Accepted:
              color = dialog.selectedColor()
              if color.isValid():
                  # ...
      

      or

      def open_color_dialog(self, label):
          color = QColorDialog.getColor(options=QColorDialog.ShowAlphaChannel)
          if color.isValid():
              # ...
      
    • The name method of QColorDialog by default will return only rgb, if you want to get argb then you must use QColor.HexArgb as parameter:

      label.setStyleSheet(
          "background-color:{};".format(color.name(QColor.HexArgb))
      )