Source code for schrodinger.ui.qt.color_picker
"""
Color Picker button to select and display a color from a color dialog
"""
from schrodinger.models import mappers
from schrodinger.models import parameters
from schrodinger.Qt import QtGui
from schrodinger.Qt.QtWidgets import QColorDialog
from schrodinger.Qt.QtWidgets import QToolButton
MAX_ALPHA_VALUE = 255
[docs]class ButtonWithColorPicker(mappers.TargetMixin, QToolButton):
"""
This color picker is a modification of the QToolButton. It opens a dialog where a
specific color can be selected. The button has an icon indicating what color
is currently selected.
"""
[docs] def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setToolTip('Opens color picker')
self.clicked.connect(self._onButtonClicked)
self._color = QtGui.QColor()
def _getDialogColor(self):
"""
Display a QColorDialog and return the user's selected color
:return: Selected color from dialog
:rtype: QColor
"""
dialog_options = QColorDialog.ShowAlphaChannel | QColorDialog.DontUseNativeDialog
return QColorDialog.getColor(parent=self,
options=dialog_options,
initial=self.color)
def _onButtonClicked(self):
"""
Handles opening the color dialog and setting the color picked
"""
picked_color = self._getDialogColor()
if picked_color.isValid():
if self.color is None or picked_color.rgba() != self.color.rgba():
self.color = picked_color
self.targetValueChanged.emit()
[docs] def changeIcon(self):
"""
Changes icon to the current color selected
"""
if self.color is None:
return
r, g, b, _ = self.color.getRgb()
# Initialize the icon to the maximum alpha value for icon visability
pixmap_color = QtGui.QColor(r, g, b, MAX_ALPHA_VALUE)
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(pixmap_color)
icon = QtGui.QIcon(pixmap)
self.setIcon(icon)
@property
def color(self):
return self._color
@color.setter
def color(self, value):
self._color = value
self.changeIcon()
[docs]class AlphaLimitedColorPickerButton(ButtonWithColorPicker):
"""
Button picker subclass that forces user picked alpha values to be
below a certain ceiling
"""
DEFAULT_ALPHA_CEILING = 20
[docs] def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._alpha_ceiling = self.DEFAULT_ALPHA_CEILING
[docs] def setAlphaCeiling(self, value):
if value < 0 or value > MAX_ALPHA_VALUE:
raise ValueError(f'Invalid alpha value: {value}')
self._alpha_ceiling = value
def _getDialogColor(self):
picked_color = super()._getDialogColor()
if picked_color.alpha() > self._alpha_ceiling:
picked_color.setAlpha(self._alpha_ceiling)
return picked_color