def material(color = QColor("red") , back_color = QColor("red") , ambient_color = QColor.fromRgbF(.4, .4, .4, 1.0) , specular_color = QColor.fromRgbF(.4, .4, .4, 1.0) , light_power = 2e5 , shininess = 0.1 , light_follows_camera = True , light_position = QVector3D(0,0,-10) , reverse_backfaces = True): ''' \param color front faces color \param back_color back faces color \param shininess material specular reflection ratio parameter [0, 1.0] \param light_follows_camera if True, the light position is assigned camera's position, else \a light_position is used \param light_position light_follows_camera is False: - light_position.xyz define light's position - if light_position.w == 0.0, light is a spot light, else light is an omni-diretional light \param spot_direction if light_follows_camera is False, and light_position.w == 0.0, defines spotlight's direction ''' return Effect.Effect( name = "material" , shader0 = Effect.GLSLProgram( uniforms = { 'color' : color , 'back_color' : back_color , 'ambient_color': ambient_color , 'specular_color': specular_color , 'light_power': light_power , 'shininess': shininess , 'light_follows_camera': light_follows_camera , 'light_position': light_position , 'reverse_backfaces' : reverse_backfaces } , vertex_shader = MATERIAL_VERTEX_SHADER , fragment_shader = MATERIAL_FRAGMENT_SHADER.format("color") ))
def textured_material(\ textures #expects: {'diffuse': ndarray}, in the future we could add more samplers/texcoords pairs , color = QColor("green") , back_color = QColor("red") , ambient_color = QColor.fromRgbF(.1, .1, .1, 1.0) , specular_color = QColor.fromRgbF(.1, .1, .1, 1.0) , light_power = 1e3 #light power should be roughly ("sight distance")^2 , shininess = 0.01 , light_follows_camera = True , light_position = QVector3D(0,0,-10) , reverse_backfaces = True): ''' \param light_follows_camera if True, the light position is assigned camera's position, else \a light_position is used \param light_position light_follows_camera is False: - light_position.xyz define light's position ''' return Effect.Effect( name = "textured_material" , shader0 = Effect.GLSLProgram( uniforms = { 'color': color #not used, meant to be diffuse color , 'back_color' : back_color , 'ambient_color': ambient_color , 'specular_color': specular_color , 'light_power': light_power , 'shininess': shininess , 'light_follows_camera': light_follows_camera , 'light_position': light_position , 'reverse_backfaces' : reverse_backfaces} , textures = textures , vertex_shader = MATERIAL_VERTEX_SHADER , fragment_shader = MATERIAL_FRAGMENT_SHADER.format("texture2D(diffuse, diffuse_tc.st)") ))
def __init__(self, parent=None): super(GLWidget, self).__init__(parent) self.timer = QTimer(self) self.timer.setSingleShot(False) self.timer.setInterval(16) self.timer.timeout.connect(self.animateFigures) self.timer.start() # parameters of the robot (square base) # length of arms of the robot self.fl = 0.4 self.sl = 0.3 self.tl = 0.3 # width of arms of the robot self.width = 0.1 # distance from each joint to end edge of the robot self.free_dist = 0.05 # 0 - rotation, 1 - position self.mode = 0 # start position of the handle self.x = 0 self.y = 0 self.z = 0.9 # target position of the handle self.xTarget = 0 self.yTarget = 0 self.zTarget = 0.9 # camera settings self.xRot = 60 * 16 self.yRot = 0 * 16 self.zRot = 0 * 16 self.cameraDepth = 0.7 self.cameraTransX = 0.0 self.cameraTransY = 0.2 # start position of joints self.curFirstRotate = 0.0 self.curSecondRotate = 0.0 self.curThirdRotate = 0.0 # target position of joints self.targetFirstRotate = 0.0 self.targetSecondRotate = 0.0 self.targetThirdRotate = 0.0 # result precesion for minimizing algorithm self.precision = 1e-1 # self.model = ModelLoader("models//sphere//point.obj") self.lastPos = QPoint() self.colorRed = QColor.fromRgbF(1.0, 0.0, 0.0, 0.0) self.colorBlue = QColor.fromRgbF(0.0, 0.0, 1.0, 0.0) self.colorGreen2 = QColor.fromRgbF(0.0, 1.0, 0.0, 0.0) self.colorGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0) self.colorPurple = QColor.fromCmykF(0.39, 0.39, 0.0, 0.0) self.colorGray = QColor.fromCmykF(0.5, 0.5, 0.5, 0.5) self.setMinimumSize(500, 500)
def update_custom_colors(self): for key, rgba in prefs.custom_colors.items(): color = c.fromRgbF(*rgba) if color: self.d[key] = color if 'custom_colors' in ctrl.settings.s_document: for key, rgba in ctrl.settings.s_document['custom_colors'].items(): color = c.fromRgbF(*rgba) if color: self.d[key] = color
def __init__(self, docker, left_color=default_color, right_color=default_color, parent=None): super(ColorSlider, self).__init__(parent) self.docker = docker self.left_color = left_color self.right_color = right_color self.slider_pixmap = None self.value_x = None self.cursor_fill_color = QColor.fromRgbF(1, 1, 1, 1) self.cursor_outline_color = QColor.fromRgbF(0, 0, 0, 1) self.need_redraw = True
def update_custom_colors(self): for key, rgba in prefs.custom_colors.items(): color = c.fromRgbF(*rgba) if color: self.d[key] = color custom_colors = ctrl.doc_settings.get('custom_colors') if custom_colors: for key, rgba in custom_colors.items(): color = c.fromRgbF(*rgba) if color: self.d[key] = color
def __init__(self, parent=None): super(HousePlant, self).__init__(parent) self.m_pot = RenderableEntity(self) self.m_plant = RenderableEntity(self.m_pot) self.m_cover = RenderableEntity(self.m_pot) self.m_potMaterial = QNormalDiffuseMapMaterial() self.m_plantMaterial = QNormalDiffuseMapAlphaMaterial() self.m_coverMaterial = QNormalDiffuseMapMaterial() self.m_potImage = QTextureImage() self.m_potNormalImage = QTextureImage() self.m_plantImage = QTextureImage() self.m_plantNormalImage = QTextureImage() self.m_coverImage = QTextureImage() self.m_coverNormalImage = QTextureImage() self.m_plantType = HousePlant.Bamboo self.m_potShape = HousePlant.Cross self.m_pot.transform().setScale(0.03) self.m_pot.addComponent(self.m_potMaterial) self.m_plant.addComponent(self.m_plantMaterial) self.m_cover.addComponent(self.m_coverMaterial) self.m_potMaterial.diffuse().addTextureImage(self.m_potImage) self.m_potMaterial.normal().addTextureImage(self.m_potNormalImage) self.m_plantMaterial.diffuse().addTextureImage(self.m_plantImage) self.m_plantMaterial.normal().addTextureImage(self.m_plantNormalImage) self.m_coverMaterial.diffuse().addTextureImage(self.m_coverImage) self.m_coverMaterial.normal().addTextureImage(self.m_coverNormalImage) self.updatePlantType() self.updatePotShape() self.m_coverImage.setSource( QUrl.fromLocalFile('assets/houseplants/cover.webp')) self.m_coverNormalImage.setSource( QUrl.fromLocalFile('assets/houseplants/cover_normal.webp')) self.m_potImage.setSource( QUrl.fromLocalFile('assets/houseplants/pot.webp')) self.m_potNormalImage.setSource( QUrl.fromLocalFile('assets/houseplants/pot_normal.webp')) self.m_potMaterial.setShininess(10.0) self.m_potMaterial.setSpecular(QColor.fromRgbF(0.75, 0.75, 0.75, 1.0)) self.m_plantMaterial.setShininess(10.0) self.m_coverMaterial.setSpecular(QColor.fromRgbF( 0.05, 0.05, 0.05, 1.0)) self.m_coverMaterial.setShininess(5.0)
def __init__(self, systemModel, parent=None): super(GLWidget, self).__init__(parent) self.setFixedSize(systemModel.view_width, systemModel.view_height) self.systemModel = systemModel self.min_method = None self.min_options = None self.errval0 = None self.errval1 = None self.errval = None self.iter_count = 0 self.image = None self.image_file = None self._show_target_image = True self.full_image = None self.image_bg_threshold = None self.latest_rendered_image = None self.im_def_scale = systemModel.view_width / systemModel.cam.width self.im_scale = self.im_def_scale self.im_xoff = 0 self.im_yoff = 0 self.im_width = systemModel.cam.width self.im_height = systemModel.cam.height self.debug_c = 0 self.gl = None self._paint_entered = False self._render = True self._algo_render = False self._center_model = False self._discretize_tol = False self.latest_discretization_err_q = False self.add_image_noise = True self._noise_image = os.path.join(SCRIPT_DIR, '../data/noise-fg.png') self._width = None self._height = None self._side = None self._gl_image = None self._object = None self._lastPos = QPoint() self._imgColor = QColor.fromRgbF(1, 1, 1, 0.4) self._fgColor = QColor.fromRgbF(0.6, 0.6, 0.6, 1) self._bgColor = QColor.fromRgbF(0, 0, 0, 1) #self._bgColor = QColor.fromCmykF(0.0, 0.0, 0.0, 1.0) self._frustum_near = 0.1 self._frustum_far = self.systemModel.max_distance self._expire = 0
def __init__(self, *args): super(ColorPickerWidget, self).__init__(*args) self.updating = False self.updatingAlpha = False self.ui = ColorPickerForm() self.ui.setupUi(self) self.setWindowFlags(Qt.Popup) self.preview = ColorPreviewWidget(self.ui.containerPreview) self.hueSlider = HueSliderWidget(self.ui.containerHueSlider) self.alphaSlider = AlphaSliderWidget(self.ui.containerAlphaSlider) self.colorPlane = ColorPlaneWidget(self.ui.containerColorPlane) self.hueSlider.valueChanged.connect(self.onHueChanged) self.alphaSlider.valueChanged.connect(self.onAlphaSliderChanged) self.colorPlane.valueChanged.connect(self.onColorBaseChanged) self.ui.buttonOK.clicked.connect(self.onButtonOK) self.ui.buttonCancel.clicked.connect(self.onButtonCancel) self.ui.buttonCopyHEX.clicked.connect(self.onButtonCopyHEX) self.ui.buttonCopyRGB.clicked.connect(self.onButtonCopyRGBA) self.ui.buttonCopyHSV.clicked.connect(self.onButtonCopyHSV) self.ui.buttonScreenPick.clicked.connect(self.onButtonScreenPick) self.ui.numR.valueChanged.connect(self.onTextRGBChanged) self.ui.numG.valueChanged.connect(self.onTextRGBChanged) self.ui.numB.valueChanged.connect(self.onTextRGBChanged) self.ui.numH.valueChanged.connect(self.onTextHSVChanged) self.ui.numS.valueChanged.connect(self.onTextHSVChanged) self.ui.numV.valueChanged.connect(self.onTextHSVChanged) self.ui.textHex.textChanged.connect(self.onTextHexChanged) self.ui.numA.valueChanged.connect(self.onAlphaSliderChanged) self.originalColor = QColor.fromRgbF(0.0, 0.0, 0.0) self.currentColor = QColor.fromRgbF(1.0, 1.0, 0.0) self.preview.setColor(self.currentColor) self.preview.setOriginalColor(self.originalColor) self.updateAlphaWidgets() self.updateTextWidgets() self.updateColorPlane()
def __init__(self, x, y, z, ID): self.x0 = x self.y0 = y self.z0 = z self.show_grid = True self.ID = ID self.r_pick = (self.ID & 0x000000FF) >> 0 self.g_pick = (self.ID & 0x0000FF00) >> 8 self.b_pick = (self.ID & 0x00FF0000) >> 16 self.pick_color = QColor.fromRgbF(self.r_pick / 255.0, self.g_pick / 255.0, self.b_pick / 255.0, 1.0) self.vertices = ((self.x0 + 1, self.y0, self.z0), (self.x0 + 1, self.y0 + 1, self.z0), (self.x0, self.y0 + 1, self.z0), (self.x0, self.y0, self.z0), (self.x0 + 1, self.y0, self.z0 + 1), (self.x0 + 1, self.y0 + 1, self.z0 + 1), (self.x0, self.y0, self.z0 + 1), (self.x0, self.y0 + 1, self.z0 + 1)) self.edges = ((0, 1), (0, 3), (0, 4), (2, 1), (2, 3), (2, 7), (6, 3), (6, 4), (6, 7), (5, 1), (5, 4), (5, 7)) self.surfaces = ((0, 1, 2, 3), (3, 2, 7, 6), (6, 7, 5, 4), (4, 5, 1, 0), (1, 5, 7, 2), (4, 0, 3, 6)) self.isActive = False self.isSelected = False self.color = self.trolltechGreen
def grid(orientation='xy', span=250, div=5, color=QColor.fromRgbF(.3, .3, .3, 1.0), matrix=np.eye(4, dtype='f4'), name="grid_xz"): #FIXME optimize (meshgrid?, numba?) color = ensure_QColor(color) l = [] n = int(span * 2 / div) for i in range(0, n * n, n): l.extend([i, i + n - 1]) for i in range(n): l.extend([i, (n - 1) * n + i]) v = [] for x in np.arange(-span, span, div): for y in np.arange(-span, span, div): v.append([x, y, 0]) vertices = np.array(v, 'f4') if orientation == 'xy': pass elif orientation == 'xz': vertices[:, 2] = vertices[:, 1] vertices[:, 1] = 0 return lines(np.array(l, 'u4'), vertices, color, matrix, name)
def locs(): qcd = QColorDialog(parent=vis.get_main_window()) qcd.setWindowFlag(Qt.WindowStaysOnTopHint, True) qcd.setCurrentColor(QColor.fromRgbF(*vis.get_grid_coordinates_color())) qcd.exec() if qcd.result() == 1: vis.set_grid_coordinates_color((qcd.selectedColor().getRgbF()))
def bg(): qcd = QColorDialog(parent=vis.get_main_window()) qcd.setWindowFlag(Qt.WindowStaysOnTopHint, True) qcd.setCurrentColor(QColor.fromRgbF(*vis.get_background_color())) qcd.exec() if qcd.result() == 1: vis.set_background_color((qcd.selectedColor().getRgbF()[:3]))
def paintEvent(self, event): painter = QtGui.QPainter(self) painter.setPen(Qt.NoPen) w = self.width() h = self.height() painter.setBrush(self.originalColor) painter.drawRect(0, 0, w, h / 2) cSolid = QColor(self.previewColor) cSolid.setAlphaF(1) #left 1/2 for solid color painter.setBrush(cSolid) painter.drawRect(0, h / 2, w / 2, h / 2 + 1) #draw chekerGrid x0 = w / 2 y0 = h / 2 w2 = w / 2 h2 = h / 2 painter.setBrush(Qt.white) painter.drawRect(x0, y0, w2, h2) painter.setBrush(QColor.fromRgbF(0.5, 0.5, 0.5)) for y in range(4): for x in range(w2 / 10): if (x % 2) == (y % 2): painter.drawRect(x0 + x * 10, y0 + y * 10, 10, 10) #right 2/3 for color with alpha painter.setBrush(self.previewColor) painter.drawRect(x0, y0, w2 + 1, h2 + 1)
def data(self, index, role): if not index.isValid(): return QVariant() elif role == Qt.BackgroundRole: if index.column() == 1: color_s = super().data(index) #print(color_s) mpl_color = matplotlib.colors.to_rgb(color_s) color_q = QColor.fromRgbF(mpl_color[0], mpl_color[1], mpl_color[2]) else: color_q = QColor.fromRgbF(1.0, 1.0, 1.0) return QBrush(color_q) elif role != Qt.DisplayRole: return QVariant() return super().data(index, role)
def addDebugContent(self): try: greenBrush = QBrush(Qt.green) outlinePen = QPen(Qt.black) outlinePen.setWidth(2) rect = self.grScene.addRect(-100, -100, 80, 100, outlinePen, greenBrush) rect.setFlag(QGraphicsItem.ItemIsMovable) text = self.grScene.addText( "This is my Awesome text!", QFont("Ubuntu")) text.setFlag(QGraphicsItem.ItemIsSelectable) text.setFlag(QGraphicsItem.ItemIsMovable) text.setDefaultTextColor(QColor.fromRgbF(1.0, 1.0, 1.0)) widget1 = QPushButton("Hello World") proxy1 = self.grScene.addWidget(widget1) proxy1.setFlag(QGraphicsItem.ItemIsMovable) proxy1.setPos(0, 30) widget2 = QTextEdit() proxy2 = self.grScene.addWidget(widget2) proxy2.setFlag(QGraphicsItem.ItemIsSelectable) proxy2.setPos(0, 60) line = self.grScene.addLine(-200, -200, 400, -100, outlinePen) line.setFlag(QGraphicsItem.ItemIsMovable) line.setFlag(QGraphicsItem.ItemIsSelectable) except Exception as ex: print("Exception caught in EditorWidget - addDebugContent()") print(ex) handleError(ex)
def paintEvent(self, event): painter = QtGui.QPainter(self) color = QColor.fromRgbF(0, 0, 0) # color.setAlphaF( 0.5 ) painter.setPen(Qt.NoPen) painter.setBrush(color) painter.drawRect(event.rect())
def __init__(self, rootEntity): super(SceneModifier, self).__init__() self.m_rootEntity = rootEntity self.listOfObjects = [] self.switchModelCount = 0 self.normalDiffuseSpecularMapMaterial = QNormalDiffuseSpecularMapMaterial( ) self.normalDiffuseSpecularMapMaterial.setTextureScale(1.0) self.normalDiffuseSpecularMapMaterial.setShininess(80.0) self.normalDiffuseSpecularMapMaterial.setAmbient( QColor.fromRgbF(1.0, 1.0, 1.0, 1.0)) diffuseImage = QTextureImage() diffuseImage.setSource(QUrl.fromLocalFile('loading.png')) self.normalDiffuseSpecularMapMaterial.diffuse().addTextureImage( diffuseImage) background = QImage() background.load('loading.png') self.planeEntity = PlaneEntity(self.m_rootEntity) self.planeEntity.mesh().setHeight(20.0) self.planeEntity.mesh().setWidth(20.0 * background.width() / background.height()) self.planeEntity.mesh().setMeshResolution(QSize(5, 5)) self.planeEntity.m_transform.setRotationZ(180.0) self.planeEntity.addComponent(self.normalDiffuseSpecularMapMaterial)
def _updateGlyphAttributes(self, *_): name = None unicodes = None width = None leftMargin = None rightMargin = None markColor = None if self._glyph is not None: glyph = self._glyph name = glyph.name if glyph.leftMargin is not None: leftMargin = round(glyph.leftMargin) if glyph.rightMargin is not None: rightMargin = round(glyph.rightMargin) foreGlyph = glyph.font[glyph.name] unicodes = " ".join( "%06X" % u if u > 0xFFFF else "%04X" % u for u in foreGlyph.unicodes ) width = round(foreGlyph.width) if foreGlyph.markColor is not None: markColor = QColor.fromRgbF(*tuple(foreGlyph.markColor)) self.nameEdit.setText(name) self.unicodesEdit.setText(unicodes) self.widthEdit.setValue(width) self.leftMarginEdit.setValue(leftMargin) self.rightMarginEdit.setValue(rightMargin) self.markColorWidget.setColor(markColor) self._updateLayerAttributes()
def _updateGlyphAttributes(self, notification=None): name = None unicodes = None width = None leftSideBearing = None rightSideBearing = None markColor = None if self._glyph is not None: name = self._glyph.name unicodes = " ".join("%06X" % u if u > 0xFFFF else "%04X" % u for u in self._glyph.unicodes) width = str(int(self._glyph.width)) if self._glyph.leftMargin is not None: leftSideBearing = str(int(self._glyph.leftMargin)) if self._glyph.rightMargin is not None: rightSideBearing = str(int(self._glyph.rightMargin)) if self._glyph.markColor is not None: markColor = QColor.fromRgbF( *tuple(self._glyph.markColor)) self.nameEdit.setText(name) self.unicodesEdit.setText(unicodes) self.widthEdit.setText(width) self.leftSideBearingEdit.setText(leftSideBearing) self.rightSideBearingEdit.setText(rightSideBearing) self.markColorWidget.setColor(markColor)
def __init__(self): super(MixerSliderDocker, self).__init__() main_program = Krita.instance() settings = main_program.readSetting( "", "MixerSliderColors", "RGBA,U8,sRGB-elle-V2-srgbtrc.icc,1,0.8,0.4,1|" + "RGBA,U8,sRGB-elle-V2-srgbtrc.icc,0,0,0,1" ) # alpha=1 == non-transparent self.default_left_color = self.qcolor_to_managedcolor( QColor.fromRgbF(0.4, 0.8, 1, 1)) self.default_right_color = self.qcolor_to_managedcolor( QColor.fromRgbF(0, 0, 0, 1)) # make base-widget and layout self.widget = QWidget() self.sliders = [] self.top_layout = QVBoxLayout() self.main_layout = QHBoxLayout() self.top_layout.addLayout(self.main_layout) self.top_layout.addStretch(0) self.settings_button = QPushButton() icon = main_program.icon("configure") self.settings_button.setIcon(icon) self.settings_button.setToolTip(i18n('Change settings')) self.settings_button.setMaximumSize(30, 30) self.main_layout.addWidget(self.settings_button) self.layout = QVBoxLayout() self.layout.setSpacing(0) self.main_layout.addLayout(self.layout) for line in settings.split(";"): colors = line.split('|') if len(colors) < 2: # discard old configurations continue left_color = self.parse_color(colors[0].split(',')) right_color = self.parse_color(colors[1].split(',')) widget = SliderLine(left_color, right_color, self) self.sliders.append(widget) self.layout.addWidget(widget) self.widget.setLayout(self.top_layout) self.setWindowTitle(i18n("Mixer Slider Docker")) self.setWidget(self.widget) [x.show() for x in self.sliders] self.settings_button.clicked.connect(self.init_ui)
def __init__(self): super(QQuickRenderer, self).__init__() self._qfbo = None self._window = None self._renderer = None self._next_renderer = None self._qcolor = QColor.fromRgbF(0.0, 0.0, 0.0)
def brd(): qcd = QColorDialog(parent=vis.get_main_window()) qcd.setOption(QColorDialog.ShowAlphaChannel) qcd.setWindowFlag(Qt.WindowStaysOnTopHint, True) qcd.setCurrentColor(QColor.fromRgbF(*vis.get_grid_border_color())) qcd.exec() if qcd.result() == 1: vis.set_grid_border_color((qcd.selectedColor().getRgbF()))
def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) # make marker pixmap self.mkpixmap = QPixmap(self.basepixmap.size()) self.mkpixmap.fill(Qt.transparent) br = QBrush(QColor(Config.dimcolor)) painter = QPainter() painter.begin(self.mkpixmap) painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(), br) for marker in self.radar['markers']: pt = getPoint(marker["location"], self.point, self.zoom, self.rect.width(), self.rect.height()) mk2 = QImage() mkfile = 'teardrop' if 'image' in marker: mkfile = marker['image'] if os.path.dirname(mkfile) == '': mkfile = os.path.join('markers', mkfile) if os.path.splitext(mkfile)[1] == '': mkfile += '.png' mk2.load(mkfile) if mk2.format != QImage.Format_ARGB32: mk2 = mk2.convertToFormat(QImage.Format_ARGB32) mkh = 80 # self.rect.height() / 5 if 'size' in marker: if marker['size'] == 'small': mkh = 64 if marker['size'] == 'mid': mkh = 70 if marker['size'] == 'tiny': mkh = 40 if 'color' in marker: c = QColor(marker['color']) (cr, cg, cb, ca) = c.getRgbF() for x in range(0, mk2.width()): for y in range(0, mk2.height()): (r, g, b, a) = QColor.fromRgba(mk2.pixel(x, y)).getRgbF() r = r * cr g = g * cg b = b * cb mk2.setPixel(x, y, QColor.fromRgbF(r, g, b, a).rgba()) mk2 = mk2.scaledToHeight(mkh, 1) painter.drawImage(pt.x - mkh / 2, pt.y - mkh / 2, mk2) painter.end() self.wmk.setPixmap(self.mkpixmap)
def cp(): cd = QColorDialog(parent=vis.get_main_window()) cd.setWindowFlag(Qt.WindowStaysOnTopHint, True) cd.setOptions(QColorDialog.ShowAlphaChannel) cd.setCurrentColor(QColor.fromRgbF(*vis.get_added_matter_color())) cd.exec() if cd.result() == 1: vis.set_added_matter_color((cd.selectedColor().getRgbF()))
def onTextRGBChanged(self, value): if self.updating: return r = self.ui.numR.value() g = self.ui.numG.value() b = self.ui.numB.value() color = QColor.fromRgbF(r, g, b) color.setAlphaF(self.currentColor.alphaF()) self.setColor(color) self.updateColorPlane()
def test_addMatiere_appendd(self, fk, cm): groupe = fk.f_groupeMatiere() res = cm.addMatiere(str(groupe.id), True) with db_session: new = groupe.matieres.select()[:][-1] assert res == [ { "activites": [], "bgColor": QColor.fromRgbF(1.000000, 1.000000, 1.000000, 1.000000), "fgColor": QColor.fromRgbF(0.000000, 0.000000, 0.000000, 1.000000), "groupe": str(groupe.id), "id": str(new.id), "nbPages": 0, "nom": "nouvelle", "position": 0, } ]
def test_addAnnotation_AnnotationDessin(self, am, qtbot, fk): s = am(2) x = s.model x.addAnnotation( "AnnotationDessin", { "endX": 0.9571428571428572, "endY": 0.9583333333333334, "fillStyle": QColor.fromRgbF(0.000000, 0.000000, 0.000000, 0.000000), "height": 0.09473684210526316, "lineWidth": 3.0, "opacity": 1.0, "startX": 0.04285714285714286, "startY": 0.041666666666666664, "strokeStyle": QColor.fromRgbF(0.000000, 0.000000, 0.000000, 1.000000), "tool": "trait", "width": 0.08027522935779817, "x": 0.24426605504587157, "y": 0.2644736842105263, }, ) new_annot = x.data(x.index(2, 0), AnnotationRole) old_annot = x.data(x.index(0, 0), AnnotationRole) assert new_annot.parent() == old_annot.parent() assert new_annot.undoStack == old_annot.undoStack assert x.rowCount() == 3 assert x._data[-1].x == 0.24426605504587157 s.undoStack.undo() assert x.rowCount() == 2 s.undoStack.redo() assert x.rowCount() == 3
def init_color(self): diff = (50, 40, 30, 20, 10, 0, -10, -20, -30, -40, -50) for tbl, color in zip((self.ui.mfcColor, self.ui.mtdColor), self.cfg['color']): tbl.clear() for i, (r, g, b) in enumerate(color): tbl.insertRow(i) tbl.setItem(i, 0, QtWidgets.QTableWidgetItem(str(diff[i]))) tbl.setItem(i, 1, QtWidgets.QTableWidgetItem('')) tbl.item(i, 1).setBackground(QBrush(QColor.fromRgbF(r, g, b)))
def initializeGL(self): debug(self.getOpenglInfo()) self.setClearColor(QColor.fromRgbF(0.0, 0.0, 0.0, 1.0)) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_CULL_FACE) if self._renderer: self._renderer.prepare()
def __init__(self, parent=None): super(QQuickGLItem, self).__init__(parent=parent) self.renderer = None self._qrenderer = None self._qcolor = QColor.fromRgbF(0.0, 0.0, 0.0) self.windowChanged.connect(self._onWindowChanged) self.setProperty('focus', True) self.setProperty('mirrorVertically', True) self.setAcceptedMouseButtons(Qt.AllButtons)
def colorToQColor(color): """ Returns the QColor_ that corresponds to the defcon Color_ *color*. TODO: Color lacks online documentation. .. _Color: https://github.com/typesupply/defcon/blob/ufo3/Lib/defcon/objects/color.py .. _QColor: http://doc.qt.io/qt-5/qcolor.html """ r, g, b, a = Color(color) return QColor.fromRgbF(r, g, b, a)
def _changeColor(self): layer = self._getCurrentLayer() if not layer: return startColor = layer.color and QColor.fromRgbF(*layer.color) or QColor('limegreen') qcolor = QColorDialog.getColor(startColor, self, options=QColorDialog.ShowAlphaChannel) if not qcolor.isValid(): # cancelled return layer.color = qcolor.getRgbF()
def mix(color1, color2, bias=0.5): def mix_real(a, b, bias): return a + (b - a) * bias if bias <= 0.0: return color1 if bias >= 1.0: return color2 if isnan(bias): return color1 r = mix_real(color1.redF(), color2.redF(), bias) g = mix_real(color1.greenF(), color2.greenF(), bias) b = mix_real(color1.blueF(), color2.blueF(), bias) a = mix_real(color1.alphaF(), color2.alphaF(), bias) return QColor.fromRgbF(r, g, b, a)
def qColor(self): r = fmod(self.h, 1.0) h = r+1.0 if r < 0.0 else r c = limit(self.c, min=0.0, max=1.0) y = limit(self.y, min=0.0, max=1.0) hs = h * 6.0 if hs < 1.0: th = hs tm = self.luma_r + self.luma_g * th elif hs < 2.0: th = 2.0 - hs tm = self.luma_g + self.luma_r * th elif hs < 3.0: th = hs - 2.0 tm = self.luma_g + self.luma_b * th elif hs < 4.0: th = 4.0 - hs tm = self.luma_b + self.luma_g * th elif hs < 5.0: th = hs - 4.0 tm = self.luma_b + self.luma_r * th else: th = 6.0 - hs tm = self.luma_r + self.luma_b * th # calculate RGB channels in the sorted order if tm >= y: tp = y + y * c * (1.0 - tm) / tm to = y + y * c * (th - tm) / tm tn = y - (y * c) else: tp = y + (1.0 - y) * c to = y + (1.0 - y) * c * (th - tm) / (1.0 - tm) tn = y - (1.0 - y) * c * tm / (1.0 - tm) # return RGB channels in the appropriate order if hs < 1.0: return QColor.fromRgbF(self._igamma(tp), self._igamma(to), self._igamma(tn), self.a) elif hs < 2.0: return QColor.fromRgbF(self._igamma(to), self._igamma(tp), self._igamma(tn), self.a) elif hs < 3.0: return QColor.fromRgbF(self._igamma(tn), self._igamma(tp), self._igamma(to), self.a) elif hs < 4.0: return QColor.fromRgbF(self._igamma(tn), self._igamma(to), self._igamma(tp), self.a) elif hs < 5.0: return QColor.fromRgbF(self._igamma(to), self._igamma(tn), self._igamma(tp), self.a) else: return QColor.fromRgbF(self._igamma(tp), self._igamma(tn), self._igamma(to), self.a)
def _parse_qcolor_arrayish(color_spec): if len(color_spec) < 3 or len(color_spec) > 4: raise ValueError('Expecting an array of length 3 or 4') if len(set(type(x) for x in color_spec)) > 1: raise ValueError('All components must have the same type') comp_type = type(color_spec[0]) if comp_type == int: if not all(0 <= x <= 255 for x in color_spec): raise ValueError('Integer components must be in the [0..255] range') return QColor.fromRgb(*color_spec) elif comp_type == float: if not all(0.0 <= x <= 1.0 for x in color_spec): raise ValueError('Float components must be in the [0.0..1.0] range') return QColor.fromRgbF(*color_spec) raise ValueError('Only int and float components are supported')
def __init__(self, index, filled=False): super().__init__() self.index = index self.internalId = str(index.internalId()) self.parent = index.parent() # calculate length = self.index.data(TreeModel.LengthRole) slope = self.index.data(TreeModel.ResultRole) self.x = numpy.arange(length * LENGTH_COEFFICIENT) self.y = slope * self.x # update item's data color = self.index.data(TreeModel.ColorRole) self.setData(self.x, self.y, pen=pyqtgraph.mkPen(width=3, color=color), antialias=True) if filled: self.setFillLevel(0.0) self.setBrush(QColor.fromRgbF(color.redF(), color.greenF(), color.blueF(), COLOR_TRANSPARENCY))
def _updateLayerAttributes(self, notification=None): self.layerSetWidget.clear() if self._font is None: return layerSet = self._font.layers if layerSet is None: return for layer in layerSet: item = QTreeWidgetItem(self.layerSetWidget) item.setFlags(item.flags() | Qt.ItemIsEditable) item.setText(0, layer.name) widget = ColorVignette(self) color = layer.color if color is not None: color = QColor.fromRgbF(*tuple(color)) widget.setColor(color) widget.setMargins(2, 2, 2, 2) widget.setMayClearColor(False) widget.colorChanged.connect(self.writeLayerColor) widget.setProperty("layer", layer) self.layerSetWidget.setItemWidget(item, 1, widget) self.layerSetWidget.setColumnWidth(1, 100)
def _makeItem(self, layer): isDefault = layer is self._layerSet.defaultLayer name = layer.name color = layer.color item = QListWidgetItem() item.setText(name) if color: pixmap = QPixmap(100, 100) # change color pixmap.fill(QColor.fromRgbF(*color)) icon = QIcon(pixmap) else: icon = QIcon(":/resources/defaultColor.svg") item.setIcon(icon) if isDefault: font = item.font() font.setBold(True) item.setFont(font) item.setFlags(item.flags() | Qt.ItemIsEditable) return item;
# ------ _defaultColors = dict( # General # ------- background=QColor(Qt.white), # Font # ---- # vertical metrics fontVerticalMetrics=QColor(204, 206, 200), fontPostscriptBlues=QColor(236, 209, 215, 100), fontPostscriptFamilyBlues=QColor.fromRgbF(1, 1, .5, .3), # TODO: change that # guidelines fontGuideline=QColor.fromRgbF(1, 0, 0, .5), # Glyph # ----- # contour fill glyphContourFill=QColor.fromRgbF(.95, .95, .95, .3), # contour stroke glyphContourStroke=QColor(34, 34, 34), # component fill glyphComponentFill=QColor(90, 90, 90, 135), # component stroke glyphComponentStroke=QColor.fromRgbF(0, 0, 0, 1),
def getQColor(cls): color = cls.getColor() return QColor.fromRgbF(*color)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) redrawRect = event.rect() beginRow = redrawRect.top() // self.squareSize endRow = redrawRect.bottom() // self.squareSize # XXX: do we need to maintain self._column when we have (endColumn - # beginColumn)? beginColumn = redrawRect.left() // self.squareSize endColumn = redrawRect.right() // self.squareSize gradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight) gradient.setColorAt(0.0, cellHeaderBaseColor) gradient.setColorAt(1.0, cellHeaderLineColor) dirtyGradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight) dirtyGradient.setColorAt(0.0, cellHeaderBaseColor.darker(125)) dirtyGradient.setColorAt(1.0, cellHeaderLineColor.darker(125)) markGradient = QLinearGradient(0, 0, 0, self.squareSize-GlyphCellHeaderHeight) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): key = row * self._columns + column if key >= len(self._glyphs): break glyph = self._glyphs[key] painter.save() painter.translate(column * self.squareSize, row * self.squareSize) painter.fillRect(0, 0, self.squareSize, self.squareSize, Qt.white) # prepare header colors brushColor = gradient linesColor = cellHeaderHighlightLineColor # mark color if not glyph.template: if glyph.markColor is not None: markColor = QColor.fromRgbF(*tuple(glyph.markColor)) markGradient.setColorAt(1.0, markColor) markGradient.setColorAt(0.0, markColor.lighter(125)) painter.fillRect(0, GlyphCellHeaderHeight, self.squareSize, self.squareSize - GlyphCellHeaderHeight, QBrush(markGradient)) if glyph.dirty: brushColor = dirtyGradient linesColor = cellHeaderHighlightLineColor.darker(110) # header gradient painter.fillRect(0, 0, self.squareSize, GlyphCellHeaderHeight, QBrush(brushColor)) # header lines painter.setPen(linesColor) minOffset = painter.pen().width() # disable antialiasing to avoid lines bleeding over background painter.setRenderHint(QPainter.Antialiasing, False) painter.drawLine(0, 0, 0, GlyphCellHeaderHeight - 1) painter.drawLine(self.squareSize - 2, 0, self.squareSize - 2, GlyphCellHeaderHeight -1) painter.setPen(QColor(170, 170, 170)) painter.drawLine(0, GlyphCellHeaderHeight, self.squareSize, GlyphCellHeaderHeight) painter.setRenderHint(QPainter.Antialiasing) # header text painter.setFont(headerFont) painter.setPen(QColor(80, 80, 80)) name = metrics.elidedText(glyph.name, Qt.ElideRight, self.squareSize - 2) painter.drawText(1, 0, self.squareSize - 2, GlyphCellHeaderHeight - minOffset, Qt.TextSingleLine | Qt.AlignCenter, name) painter.restore() painter.setPen(cellGridColor) rightEdgeX = column * self.squareSize + self.squareSize bottomEdgeY = row * self.squareSize + self.squareSize painter.drawLine(rightEdgeX, row * self.squareSize + 1, rightEdgeX, bottomEdgeY) painter.drawLine(rightEdgeX, bottomEdgeY, column * self.squareSize + 1, bottomEdgeY) if self._currentDropIndex is not None: painter.setPen(Qt.green) if self._currentDropIndex == key: painter.drawLine(column * self.squareSize, row * self.squareSize, column * self.squareSize, bottomEdgeY) # special-case the end-column elif column == endColumn and self._currentDropIndex == key+1: yPos = self.mapFromGlobal(QCursor.pos()).y() if row == yPos // self.squareSize: painter.drawLine(rightEdgeX - 1, row * self.squareSize, rightEdgeX - 1, bottomEdgeY) # selection code if key in self._selection: painter.setRenderHint(QPainter.Antialiasing, False) painter.fillRect(column * self.squareSize + 1, row * self.squareSize + 1, self.squareSize - 3, self.squareSize - 3, cellSelectionColor) painter.setRenderHint(QPainter.Antialiasing) if not glyph.template: font = glyph.getParent() outline = glyph.getRepresentation("defconQt.QPainterPath") uPM = font.info.unitsPerEm if uPM is None or not uPM > 0: uPM = 1000 descender = font.info.descender if descender is None or not descender < 0: descender = -250 factor = (self.squareSize-GlyphCellHeaderHeight) / (uPM*(1+2*GlyphCellBufferHeight)) x_offset = (self.squareSize-glyph.width*factor)/2 # If the glyph overflows horizontally we need to adjust the scaling factor if x_offset < 0: factor *= 1+2*x_offset/(glyph.width*factor) x_offset = 0 # TODO: the * 1.8 below is somewhat artificial y_offset = descender*factor * 1.8 painter.save() painter.setClipRect(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight, self.squareSize, self.squareSize-GlyphCellHeaderHeight) painter.translate(column * self.squareSize + x_offset, row * self.squareSize + self.squareSize + y_offset) painter.scale(factor, -factor) painter.fillPath(outline, Qt.black) painter.restore() else: painter.save() painter.setFont(voidFont) painter.setPen(QPen(Qt.lightGray)) rect = QRectF(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight, self.squareSize, self.squareSize-GlyphCellHeaderHeight) # TODO: need to flag template glyphs as to whether they have unicodings or not if glyph.unicode is not None: text = chr(glyph.unicode) else: text = "✌" painter.drawText(rect, Qt.AlignCenter, text) painter.restore()
from defconQt.util import platformSpecific from PyQt5.QtCore import QMimeData, QRectF, QSize, Qt from PyQt5.QtGui import (QBrush, QColor, QCursor, QDrag, QFont, QFontMetrics, QKeySequence, QLinearGradient, QPainter, QPen) from PyQt5.QtWidgets import QApplication, QMessageBox, QScrollArea, QWidget import math cellGridColor = QColor(130, 130, 130) cellHeaderBaseColor = QColor(230, 230, 230) cellHeaderLineColor = QColor(220, 220, 220) cellHeaderHighlightLineColor = QColor(240, 240, 240) cellSelectionColor = QColor.fromRgbF(.2, .3, .7, .15) GlyphCellBufferHeight = .2 GlyphCellHeaderHeight = 14 # TODO: consider extracting each platform-specific thing (fonts, shortcuts) in a # purposed folder headerFont = QFont() headerFont.setFamily('Lucida Sans Unicode') headerFont.insertSubstitution('Lucida Sans Unicode', 'Lucida Grande') headerFont.insertSubstitution('Lucida Sans Unicode', 'Luxi Sans') headerFont.setPointSize(8) voidFont = QFont(headerFont) voidFont.setPointSize(24) metrics = QFontMetrics(headerFont) def proceedWithDeletion(self): closeDialog = QMessageBox(QMessageBox.Question, "", "Delete glyphs", QMessageBox.Yes | QMessageBox.No, self) closeDialog.setInformativeText("Are you sure you want to delete them?")
def __init__(self): self.font = QFont("DejaVu Sans") self.background_color = QColor.fromRgbF(1.0, 1.0, 1.0) self.midcolor = QColor.fromRgbF(0.75, 0.75, 0.75) self.foreground_color = QColor.fromRgbF(0, 0, 0)
QFontMetrics, QKeySequence, QLinearGradient, QPainter, QPen, ) from PyQt5.QtWidgets import QApplication, QMessageBox, QScrollArea, QWidget import math import time import unicodedata cellGridColor = QColor(130, 130, 130) cellHeaderBaseColor = QColor(230, 230, 230) cellHeaderLineColor = QColor(220, 220, 220) cellHeaderHighlightLineColor = QColor(240, 240, 240) cellSelectionColor = QColor.fromRgbF(0.2, 0.3, 0.7, 0.15) GlyphCellBufferHeight = 0.2 GlyphCellHeaderHeight = 14 headerFont = QFont() headerFont.setFamily("Lucida Sans Unicode") headerFont.insertSubstitution("Lucida Sans Unicode", "Lucida Grande") headerFont.insertSubstitution("Lucida Sans Unicode", "Luxi Sans") headerFont.setPointSize(platformSpecific.headerPointSize) voidFont = QFont(headerFont) voidFont.setPointSize(24) metrics = QFontMetrics(headerFont) arrowKeys = (Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right)
# ------ # Colors # ------ _defaultColors = dict( # General # ------- background=QColor(Qt.white), # Font # ---- # guidelines fontGuideline=QColor.fromRgbF(1, 0, 0, .5), # Glyph # ----- # contour fill glyphContourFill=QColor.fromRgbF(.85, .85, .85, .5), # contour stroke glyphContourStroke=QColor.fromRgbF(0, 0, 0, 1), # component fill glyphComponentFill=QColor.fromRgbF(0, 0, 0, .4), # component stroke glyphComponentStroke=QColor.fromRgbF(0, 0, 0, 1), # points glyphOnCurvePoints=QColor(4, 100, 166, 190), glyphOtherPoints=QColor.fromRgbF(.6, .6, .6, 1),
def activate_color_theme(self, theme_key, try_to_remember=True): """ Prepare root color (self.hsv), depending on what kind of color settings are active :param theme_key: :param try_to_remember: bool -- try to restore the previous base color, effective only for randomising palettes. """ self.theme_key = theme_key if theme_key in self.default_themes: data = self.default_themes[theme_key] elif theme_key in self.custom_themes: data = self.custom_themes[theme_key] else: self.theme_key = self.default data = self.default_themes[self.theme_key] log.error(f'Unable to find color theme "{theme_key}"') self.hsv = data.get('hsv', [0.00, 0.29, 0.35]) # dark rose) contrast = data.get('contrast', 55) faded = data.get('faded', False) bw = data.get('bw', False) colors = data.get('colors', None) build = data.get('build', '') if build == 'solarized_lt': self.build_solarized(light=True) return elif build == 'solarized_dk': self.build_solarized(light=False) return elif build == 'random': found = False if try_to_remember: remembered = ctrl.settings.get('last_key_colors') # found from forest's settings if theme_key in remembered: self.hsv = list(remembered[theme_key]) found = True if not found: lu_min = data.get('lu_min', 25) lu = 101 lu_max = data.get('lu_max', 95) while not (lu_min < lu < lu_max): r = random.random() g = random.random() b = random.random() hu, su, lu = rgb_to_husl(r, g, b) key_color = c.fromRgbF(r, g, b) self.hsv = list(key_color.getHsvF())[:3] if ctrl.forest: remembered = ctrl.settings.get('last_key_colors') if remembered: remembered[theme_key] = self.hsv else: remembered = {theme_key: self.hsv} ctrl.settings.set('last_key_colors', remembered, level=FOREST) if colors: for key, (r, g, b, a) in colors.items(): color = c.fromRgbF(r, g, b) color.setAlphaF(a) self.d[key] = color color = self.d['content1'] self.current_hex = color.name() self.hsv = list(color.getHsvF())[:3] self.gradient.setColorAt(1, self.d['background1']) self.gradient.setColorAt(0, self.d['background1'].lighter()) else: self.compute_palette(self.hsv, contrast=contrast, faded=faded)
# ------ # Colors # ------ _defaultColors = dict( # General # ------- background=QColor(Qt.white), # Font # ---- # vertical metrics fontVerticalMetrics=QColor.fromRgbF(.4, .4, .4, .5), fontPostscriptBlues=QColor.fromRgbF(.5, .7, 1, .3), fontPostscriptFamilyBlues=QColor.fromRgbF(1, 1, .5, .3), # Glyph # ----- # margins glyphMarginsFill=QColor.fromRgbF(.5, .5, .5, .11), glyphMarginsStroke=QColor.fromRgbF(.7, .7, .7, .5), # contour fill glyphContourFill=QColor.fromRgbF(.85, .85, .85, .5), # contour stroke glyphContourStroke=QColor.fromRgbF(0, 0, 0, 1), # component fill glyphComponentFill=QColor.fromRgbF(0, 0, 0, .4),
from defconQt.tools.drawing import drawTextAtPoint from PyQt5.QtCore import QPointF, Qt from PyQt5.QtGui import QBrush, QColor, QPainter, QPainterPath, QPen, QTransform # ------ # Colors # ------ _defaultColors = dict( # General # ------- background=QColor(Qt.white), # Glyph # ----- # contour fill glyphContourFill=QColor.fromRgbF(0.85, 0.85, 0.85, 0.5), # contour stroke glyphContourStroke=QColor.fromRgbF(0, 0, 0, 1), # component fill glyphComponentFill=QColor.fromRgbF(0, 0, 0, 0.4), # component stroke glyphComponentStroke=QColor.fromRgbF(0, 0, 0, 1), # points glyphOnCurvePoints=QColor(4, 100, 166, 190), glyphOtherPoints=QColor.fromRgbF(0.6, 0.6, 0.6, 1), # anchors glyphAnchor=QColor(228, 96, 15, 200), # selection glyphSelection=QColor(165, 190, 216, 155), )
def colorToQColor(color): return QColor.fromRgbF(*Color(color))
from defcon import Glyph from defconQt.representationFactories.glyphCellFactory import ( GlyphCellHeaderHeight, GlyphCellMinHeightForHeader) from defconQt.tools import platformSpecific from defconQt.tools.glyphsMimeData import GlyphsMimeData from PyQt5.QtCore import pyqtSignal, QRectF, QSize, Qt from PyQt5.QtGui import ( QColor, QCursor, QDrag, QPainter, QPainterPath, QPalette) from PyQt5.QtWidgets import QApplication, QScrollArea, QSizePolicy, QWidget import time import unicodedata backgroundColor = Qt.white cellGridColor = QColor(190, 190, 190) insertionPositionColor = QColor.fromRgbF(.16, .3, .85, 1) cacheBustSize = 10 class GlyphCellWidget(QWidget): """ The :class:`GlyphCellWidget` widget displays a list of Glyph_ organized in cells with their names inside headers. This widget allows keyboard navigation and selection of one or more cells, and emits the *glyphActivated* signal upon double-click or Return keyboard pressed and yields the concerned Glyph_. It also has a *selectionChanged* signal. Drag and drop can be enabled with *setAcceptDrops(True)*. This widget