Python PyQt5.QtGui.QColor() Examples

The following are code examples for showing how to use PyQt5.QtGui.QColor(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Python-GUI   Author: arpitj07   File: Project.py    MIT License 7 votes vote down vote up
def boxclose(self):
        teamname = self.open_screen.OpenTheTeam.text()
        myteam= sqlite3.connect('TEAM.db')
        curser= myteam.cursor()
        curser.execute("SELECT PLAYERS from team WHERE NAMES= '"+teamname+"';")
        hu= curser.fetchall()
        self.listWidget.clear()
        for i in range(len(hu)):
            item= QtWidgets.QListWidgetItem(hu[i][0])
            font = QtGui.QFont()
            font.setBold(True)
            font.setWeight(75)
            item.setFont(font)
            item.setBackground(QtGui.QColor('sea green'))
            self.listWidget.addItem(item)
            
        self.openDialog.close() 
Example 2
Project: JI-Live-Danmu-Client   Author: SJTU-UMJI-Tech   File: Marquee.py    MIT License 6 votes vote down vote up
def changeColor(self):
        if self.changeIdx < self.CHANGE_TIMES:
            pa = QPalette()
            pa.setColor(
                QPalette.Foreground,
                QColor(
                    self.RAINBOW_RGB_LIST[self.clrIdx][0] +
                    self.changeRGB[0] / self.CHANGE_TIMES * self.changeIdx,
                    self.RAINBOW_RGB_LIST[self.clrIdx][1] +
                    self.changeRGB[1] / self.CHANGE_TIMES * self.changeIdx,
                    self.RAINBOW_RGB_LIST[self.clrIdx][2] +
                    self.changeRGB[2] / self.CHANGE_TIMES * self.changeIdx))
            self.label.setPalette(pa)
            self.changeIdx += 1
            self.show()
        else:
            self.changeIdx = 0
            self.clrIdx = 0 if self.clrIdx == 6 else self.clrIdx + 1
            self.setChangeRGB(self.RAINBOW_RGB_LIST[self.clrIdx],
                              self.RAINBOW_RGB_LIST[(self.clrIdx + 1) % 7]) 
Example 3
Project: JI-Live-Danmu-Client   Author: SJTU-UMJI-Tech   File: DanmuManager.py    MIT License 6 votes vote down vote up
def parseText(self, text):
        textColor = QColor(240, 240, 240)
        style = 'fly'
        matchObject = re.search(
            r'\#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})', text)
        if matchObject:
            textColor = QColor(
                int(matchObject.group(1), 16), int(matchObject.group(2), 16),
                int(matchObject.group(3), 16))
            text = re.sub(r'\#[0-9a-fA-F]{6}', '', text)
        if re.search(r'\#top', text, re.I):
            style = 'top'
            text = re.sub(r'\#top', '', text, re.I)
        elif re.search(r'\#btm', text, re.I):
            style = 'btm'
            text = re.sub(r'\#btm', '', text, re.I)
        return text, textColor, style 
Example 4
Project: dcc   Author: amimo   File: DisasmViewMode.py    Apache License 2.0 6 votes vote down vote up
def drawCursor(self, qp):
        cursorX, cursorY = self.cursor.getPosition()

        log.debug("%s / %s", cursorX, cursorY)

        xstart = cursorX

        if cursorY not in self.OPCODES:
            log.warning("Impossible to find instruction at cursor %d, %d" % (cursorY, len(self.OPCODES)))
            return

        asm = self.OPCODES[cursorY]
        width = asm.getSelectionWidth(xstart)

        qp.setBrush(QtGui.QColor(255, 255, 0))

        qp.setOpacity(0.5)
        qp.drawRect(xstart * self.fontWidth,
                    cursorY * self.fontHeight,
                    width * self.fontWidth,
                    self.fontHeight + 2)
        qp.setOpacity(1) 
Example 5
Project: dcc   Author: amimo   File: HexViewMode.py    Apache License 2.0 6 votes vote down vote up
def drawAdditionals(self):
        self.newPix = self._getNewPixmap(self.width, self.height + self.SPACER)
        qp = QtGui.QPainter()
        qp.begin(self.newPix)
        qp.drawPixmap(0, 0, self.qpix)

        # self.transformationEngine.decorateText()

        # highlight selected text
        self.selector.highlightText()

        # draw other selections
        self.selector.drawSelections(qp)

        # draw our cursor
        self.drawCursor(qp)

        # draw dword lines
        for i in range(self.COLUMNS // 4)[1:]:
            xw = i * 4 * 3 * self.fontWidth - 4
            qp.setPen(QtGui.QColor(0, 255, 0))
            qp.drawLine(xw, 0, xw, self.ROWS * self.fontHeight)

        qp.end() 
Example 6
Project: dcc   Author: amimo   File: BinViewMode.py    Apache License 2.0 6 votes vote down vote up
def handleEditMode(self, modifiers, key, event):
        if key in range(0, 256):
            offs = self.getCursorOffsetInPage()

            self.dataModel.setData_b(self.dataModel.getOffset() + offs, str(event.text()))

            z = self.dataModel.getOffset() + offs
            # TODO: sa nu se repete, tre original_transformengine
            self.transformationEngine = RangePen(self.original_textdecorator, z, z + 0,
                                                 QtGui.QPen(QtGui.QColor(218, 94, 242), 0, QtCore.Qt.SolidLine),
                                                 ignoreHighlights=True)

            self.moveCursor(Directions.Right)

            x, y = self.cursor.getPosition()

            self.draw(refresh=True, row=y, howMany=1) 
Example 7
Project: raster-vision-qgis   Author: azavea   File: label_loader.py    GNU General Public License v3.0 6 votes vote down vote up
def _make_vector_renderer(layer, class_field, class_map):
        category_map = {}

        colors = ['Blue', 'Red', 'Green', 'Yellow']

        for i, class_item in enumerate(class_map.get_items()):
            name = class_item.name
            color = class_item.color
            if color is None:
                color = colors[i % len(colors)]
            category_map[name] = (color, name)

        categories = []
        for name, (color, label) in category_map.items():
            symbol = QgsSymbol.defaultSymbol(layer.geometryType())
            symbol_layer = QgsSimpleLineSymbolLayer()
            symbol_layer.setWidth(0.5)
            symbol.changeSymbolLayer(0, symbol_layer)
            symbol.setColor(QColor(color))

            category = QgsRendererCategory(label, symbol, name)
            categories.append(category)

        renderer = QgsCategorizedSymbolRenderer(class_field, categories)
        return renderer 
Example 8
Project: cct   Author: awacha   File: backgroundsubtractionmodel.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def data(self, index: QtCore.QModelIndex, role: int = ...):
        if role == QtCore.Qt.TextColorRole:
            if (self._samples[index.row()][index.column()] is None) and (index.column() < 2):
                return QtGui.QColor('gray')
            else:
                return None
        elif role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
            if index.column() < 2:
                if self._samples[index.row()][index.column()] is None:
                    if role == QtCore.Qt.DisplayRole:
                        return 'Select sample...'
                    else:
                        return ''
            return self._samples[index.row()][index.column()]
        elif role == QtCore.Qt.CheckStateRole:
            if index.column() == 0:
                return [QtCore.Qt.Unchecked, QtCore.Qt.Checked][self._samples[index.row()][3]]
            else:
                return None
        return None 
Example 9
Project: cct   Author: awacha   File: motorconfig.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def resetEntryBackgrounds(self):
        for widget in [self.driveRMSCurrentDoubleSpinBox,
                       self.standbyRMSCurrentDoubleSpinBox,
                       self.freewheelingDelayDoubleSpinBox,
                       self.pulseDivisorSpinBox,
                       self.rampDivisorSpinBox,
                       self.microstepExponentSpinBox,
                       self.rawMaxSpeedSpinBox,
                       self.rawMaxAccelSpinBox,
                       self.leftSwitchEnabledCheckBox,
                       self.rightSwitchEnabledCheckBox,
                       self.leftLimitDoubleSpinBox,
                       self.rightLimitDoubleSpinBox]:
            pal = widget.palette()
            pal.setColor(pal.Base, QtGui.QColor('white'))
            widget.setPalette(pal) 
Example 10
Project: cct   Author: awacha   File: circulator.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setFlagBackground(self, flag: QtWidgets.QLabel, state: bool, label: Optional[str] = None):
        palette = flag.palette()
        assert isinstance(palette, QtGui.QPalette)
        if state is None:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('gray'))
            palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('black'))
        elif state:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('lightgreen'))
            palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('black'))
        else:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))
            palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('white'))
        flag.setPalette(palette)
        flag.setAutoFillBackground(True)
        if label is not None:
            flag.setText(label) 
Example 11
Project: musaic   Author: al165   File: sliders.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.valueChanged.connect(self.repaint)

        self.setObjectName("QBoxSlider")

        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding
        )

        self.setMinimumHeight(10)
        self.setMinimumWidth(30)

        self._forground_color = QtGui.QColor('#5A5A5A')
        self._text_color = None

        self._minimum = 0
        self._maximum = 100

        self._value = 0

        self._show_text = True 
Example 12
Project: musaic   Author: al165   File: sliders.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, minimum=0, maximum=128, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setObjectName("QBoxRangeSlider")

        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding
        )

        self.setMinimumHeight(10)
        self.setMinimumWidth(30)

        self._forground_color = QtGui.QColor('#5A5A5A')
        self._text_color = None

        self._minimum = minimum
        self._maximum = maximum

        self._left = minimum
        self._right = maximum

        self._show_text = True

        self.rangeChanged.connect(self.repaint) 
Example 13
Project: musaic   Author: al165   File: sliders.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, minimum=0, maximum=10, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._sensitivity = 200

        self._emit = True

        self._value = minimum
        self.valueChanged.connect(self.repaint)

        self._minimum = minimum
        self._maximum = maximum

        self.minimum = minimum
        self.maximum = maximum
        self.value = minimum

        self._color = QtGui.QColor('#5A5A5A') 
Example 14
Project: musaic   Author: al165   File: sliders.py    GNU General Public License v3.0 6 votes vote down vote up
def paintEvent(self, e):
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        rect = painter.device().rect()

        radius = min(rect.width(), rect.height())/2

        pc = (self.value - self.minimum) / (self.maximum - self.minimum)

        a = 4.18879 - pc*5.23599
        x = math.cos(a) * (radius-1) + radius
        y = -math.sin(a) * (radius-1) + radius

        pen = QtGui.QPen()
        pen.setWidth(2)
        pen.setColor(self._color)
        painter.setPen(pen)
        painter.drawArc(1, 1, 2*radius-1, 2*radius-1, -120*16, -300*16)
        pen.setColor(QtGui.QColor('#DDDDDD'))
        painter.setPen(pen)
        painter.drawLine(radius, radius, x, y) 
Example 15
Project: SpriteMator   Author: rafaelvasco   File: draggable_list_base_widget.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, parent, label):

        self._top = 0
        self._index = 0
        self._list = parent
        self._height = parent.item_height
        self._hovered = False
        self._selected = False
        self._dragging = False
        self._label = label
        self._hit = False
        self._backColor = QColor(51, 57, 64)
        self._borderColor = QColor(132, 148, 165)
        self._backColorSelected = QColor(47, 74, 96)
        self._borderColorSelected = QColor(101, 172, 227)

    #------------------------------------------------------------------------------- 
Example 16
Project: SpriteMator   Author: rafaelvasco   File: options_bar_widget.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, canvas):
        super(OptionsBar, self).__init__()

        self._layout = QHBoxLayout()
        self._layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self._layout.setAlignment(Qt.AlignLeft)
        self._backgroundColor = QColor(10, 10, 10)

        self._toggleGridButton = QPushButton()
        self._toggleOnionSkinButton = QPushButton()
        self._toggleLightsButton = QPushButton()

        self._initialize_components(canvas)
        self._initialize_style()

        self.setLayout(self._layout) 
Example 17
Project: eddy   Author: obdasystems   File: description.py    GNU General Public License v3.0 6 votes vote down vote up
def insertURL(self, url, alias):
        """
        Executed to insert a URL in the description.
        :param url: the URL to insert
        :type url: str
        :param alias: the URL anchor text
        :type alias: str
        """
        linkFormat = QtGui.QTextCharFormat()
        linkFormat.setForeground(QtGui.QColor("blue"))
        linkFormat.setFont(self.text.currentFont())
        linkFormat.setFontPointSize(self.text.fontPointSize())
        linkFormat.setAnchorHref(url)
        linkFormat.setFontUnderline(True)
        linkFormat.setAnchor(True)
        linkFormat.setToolTip(url)
        cursor = self.text.textCursor()
        cursor.insertText(alias if alias else url, linkFormat)
        cursor.insertText(" ", self.defaultCharFormat) 
Example 18
Project: eddy   Author: obdasystems   File: description.py    GNU General Public License v3.0 6 votes vote down vote up
def insertWikiTag(self, wikiTagURL, wikiLabel):
        """
        Executed to insert a wiki tag.
        :param wikiTag: the wiki tag URL to insert
        :type wikiTagURL: str
        :param wikiLabel: the wiki tag label to insert
        :type wikiLabel: str
        """
        linkFormat = QtGui.QTextCharFormat()
        linkFormat.setForeground(QtGui.QColor("blue"))
        linkFormat.setFont(self.text.currentFont())
        linkFormat.setFontPointSize(self.text.fontPointSize())
        linkFormat.setFontUnderline(True)
        linkFormat.setAnchor(True)
        linkFormat.setAnchorHref(wikiTagURL)
        linkFormat.setToolTip(wikiTagURL)

        self.text.textCursor().insertText(wikiLabel, linkFormat)
        self.text.textCursor().insertText(" ", self.defaultCharFormat) 
Example 19
Project: eddy   Author: obdasystems   File: palette.py    GNU General Public License v3.0 6 votes vote down vote up
def paintEvent(self, paintEvent):
        """
        Perform the painting of the button in the palette.
        :type paintEvent: QPaintEvent
        """
        icon = self.icon()
        painter = QtGui.QPainter(self)
        if self.isChecked():
            painter.setBrush(QtGui.QBrush(QtGui.QColor(66, 165, 245)))
            painter.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor(66, 165, 245)), 1.0))
            painter.drawRect(0, 0, 60, 44)
        painter.setOpacity(1.0 if self.isEnabled() else 0.33)
        painter.drawPixmap(0, 0, icon.pixmap(QtCore.QSize(60, 44)))

    #############################################
    #   INTERFACE
    ################################# 
Example 20
Project: phidl   Author: amccaugh   File: quickplotter.py    MIT License 6 votes vote down vote up
def add_polygons(self, polygons, color = '#A8F22A', alpha = 1):
        qcolor = QColor()
        qcolor.setNamedColor(color)
        qcolor.setAlphaF(alpha)
        for points in polygons:
            qpoly = QPolygonF( [QPointF(p[0], p[1]) for p in points] )
            scene_poly = self.scene.addPolygon(qpoly)
            scene_poly.setBrush(qcolor)
            scene_poly.setPen(self.pen)
            self.scene_polys.append(scene_poly)
            # Update custom bounding box
            sr = scene_poly.sceneBoundingRect()
            if len(self.scene_polys) == 1:
                self.scene_xmin = sr.left()
                self.scene_xmax = sr.right()
                self.scene_ymin = sr.top()
                self.scene_ymax = sr.bottom()
            else:
                self.scene_xmin = min(self.scene_xmin, sr.left())
                self.scene_xmax = max(self.scene_xmax, sr.right())
                self.scene_ymin = min(self.scene_ymin, sr.top())
                self.scene_ymax = max(self.scene_ymax, sr.bottom()) 
Example 21
Project: hexutil   Author: stephanh42   File: example.py    MIT License 6 votes vote down vote up
def __init__(self, *args, **kws):
        super().__init__(*args, **kws)
        self.setMouseTracking(True) # we want to receive mouseMoveEvents

        self.level = Level(500)
        self.player = hexutil.origin
        self.hexgrid = hexutil.HexGrid(24)

        # initialize GUI objects needed for painting
        self.font = QtGui.QFont("Helvetica", 20)
        self.font.setStyleHint(QtGui.QFont.SansSerif)
        self.pen = QtGui.QPen()
        self.pen.setWidth(2)
        self.select_brush = QtGui.QBrush(QtGui.QColor(127, 127, 255, 127))
        self.unseen_brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 127))

        self.update_fov() 
Example 22
Project: plexdesktop   Author: coryo   File: delegates.py    GNU General Public License v3.0 6 votes vote down vote up
def placeholder_thumb_generator(title, size=150):
    """Returns a QPixmap of size with the first letter of each word in title"""
    initials = ' '.join([x[0] for x in title.split(' ') if len(x) > 2])
    key = 'placeholder' + initials
    img = QtGui.QPixmapCache.find(key)
    if img:
        return img
    qsize = QtCore.QSize(size, size)
    circle_color = QtGui.QColor(50, 50, 50)
    text_color = QtGui.QColor(75, 75, 75)
    rect = QtCore.QRect(QtCore.QPoint(0, 0), QtCore.QPoint(size, size))
    center = QtCore.QPoint(size / 2, size / 2)
    img = QtGui.QPixmap(qsize)
    img.fill(QtCore.Qt.transparent)
    p = QtGui.QPainter(img)
    p.setFont(QtGui.QFont('Open Sans', size / 4, weight=QtGui.QFont.Bold))
    p.setBrush(QtGui.QBrush(circle_color))
    p.setPen(circle_color)
    p.setRenderHint(QtGui.QPainter.Antialiasing, True)
    p.drawEllipse(center, size / 2 - 1, size / 2 - 1)
    p.setPen(text_color)
    p.drawText(rect, QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, initials)
    QtGui.QPixmapCache.insert(key, img)
    return img 
Example 23
Project: plexdesktop   Author: coryo   File: delegates.py    GNU General Public License v3.0 6 votes vote down vote up
def draw_progress_bar(plex_item, pixmap, height=6):
    """draw a progress indicator on the bottom of pixmap with height pixels"""
    if not hasattr(plex_item, 'in_progress'):
        return
    if not plex_item.in_progress:
        return
    progress_color = QtGui.QColor(204, 123, 25)
    progress = plex_item.view_offset / max(1, plex_item.duration)
    p = QtGui.QPainter(pixmap)
    rect = p.window()
    progress_rect = QtCore.QRect(rect.bottomLeft() - QtCore.QPoint(0, height),
                                 rect.bottomRight())
    progress_fill = QtCore.QRect(progress_rect)
    progress_fill.setWidth(rect.width() * progress)
    p.fillRect(progress_rect, QtGui.QBrush(QtCore.Qt.black))
    p.fillRect(progress_fill, QtGui.QBrush(progress_color)) 
Example 24
Project: JI-Live-Danmu-Client   Author: SJTU-UMJI-Tech   File: Marquee.py    MIT License 5 votes vote down vote up
def initLabel(self, label, text):
        label.setText(text)
        label.setFont(QFont('SimHei', 24, 100))
        eff = QGraphicsDropShadowEffect()
        eff.setColor(QColor(6, 6, 6))
        eff.setBlurRadius(5)
        eff.setOffset(1.5, 1.5)
        label.setGraphicsEffect(eff)
        label.setGeometry(0, 0,
                          self.fontMetrics().boundingRect(text).width() + 20,
                          self.fontMetrics().boundingRect(text).height() + 10) 
Example 25
Project: JI-Live-Danmu-Client   Author: SJTU-UMJI-Tech   File: Danmu.py    MIT License 5 votes vote down vote up
def __init__(self, text, color, top, window):
        super(Danmu, self).__init__(window)
        # clean invalid characters
        text = re.sub(r'/Emoji\d+|/表情|^ | $', '',
                      text.replace('\n', ' '))[0:MAX_STR_LEN]
        self.top = top
        self.setTextFormat(Qt.PlainText)
        self.setText(text)
        # self.setWindowFlags(Qt.FramelessWindowHint)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
        self.setFont(QFont('SimHei', FONT_SIZE, 100))
        # set size of label
        myRect = self.fontMetrics().boundingRect(text)
        self.setFixedSize(myRect.width() + 20, myRect.height() + 10)
        self.setColor(color)
        self.setShadow(QColor('#060606'), 5, 1.5)
        # self.setStyleSheet("border:1px solid red;") 
Example 26
Project: ILTIS   Author: grg2rsr   File: Processing_Object.py    GNU General Public License v2.0 5 votes vote down vote up
def calc_colors(self,nColors,HSVsubset=(0,360),HSVoffset=0):
        h = sp.linspace(HSVsubset[0],HSVsubset[1],nColors,endpoint=False).astype('int')
        h = self.add_circular_offset(h,HSVoffset,HSVsubset[1]).tolist()
        s = [255] * nColors
        v = [255] * nColors
        colors = []
        for n in range(nColors):
            Color = QColor()
            Color.setHsv(h[n],s[n],v[n])
            colors.append(Color.getRgb())
        return colors 
Example 27
Project: ILTIS   Author: grg2rsr   File: Data_Selector_Widget.py    GNU General Public License v2.0 5 votes vote down vote up
def init_data(self):
                
        self.Main.Data.Metadata.paths = self.Main.Data.Metadata.paths
        self.setRowCount(len(self.Main.Data.Metadata.paths))
        
        # table entries
        for n, path in enumerate(self.Main.Data.Metadata.paths):
            self.setItem(n, 0, QtWidgets.QTableWidgetItem(self.Main.Data.Metadata.trial_labels[n]))
            
            color = self.Main.Options.view['colors'][n]
            QColor = QtGui.QColor(*color)
            QColor.setAlpha(100)
            self.item(n, 0).setBackground(QtGui.QBrush(QColor))  # FIXME find color solution

            verticalHeader = QtWidgets.QTableWidgetItem(str(n))
            verticalHeader.setBackground(QtGui.QBrush(QColor))
            
            QColor.setAlpha(255)
            verticalHeader.setForeground(QColor)
            
            self.setVerticalHeaderItem(n, verticalHeader)

        # connect
        self.itemSelectionChanged.connect(self.selection_changed)
        self.itemChanged.connect(self.labels_changed)
        
        # select all on startup
        selection = QtWidgets.QTableWidgetSelectionRange(0,0,len(self.Main.Data.Metadata.paths) - 1, 0)
        self.setRangeSelected(selection, True)
        
        self.verticalHeader().setStyle(QtWidgets.QStyleFactory.create('Cleanlooks')) # check on windows machines
        pass 
Example 28
Project: Pesterchum   Author: henry232323   File: dialogs.py    MIT License 5 votes vote down vote up
def add_user_item(self, user):
        if user.startswith("@"):
            nam = user[1:]
            self.memoUsers.addItem(nam)
            itm = self.memoUsers.item(self.memoUsers.count() - 1)
            itm.setIcon(QIcon(self.app.theme["path"] + "/op.png"))
        elif user.startswith("&"):
            nam = user[1:]
            self.memoUsers.addItem(nam)
            itm = self.memoUsers.item(self.memoUsers.count() - 1)
            itm.setIcon(QIcon(self.app.theme["path"] + "/admin.png"))
        elif user.startswith("%"):
            nam = user[1:]
            self.memoUsers.addItem(nam)
            itm = self.memoUsers.item(self.memoUsers.count() - 1)
            itm.setIcon(QIcon(self.app.theme["path"] + "/halfop.png"))
        elif user.startswith("~"):
            nam = user[1:]
            self.memoUsers.addItem(nam)
            itm = self.memoUsers.item(self.memoUsers.count() - 1)
            itm.setIcon(QIcon(self.app.theme["path"] + "/founder.png"))
        else:
            nam = user
            self.memoUsers.addItem(nam)
            itm = self.memoUsers.item(self.memoUsers.count() - 1)
        color = self.app.getColor(nam)
        if color.startswith("rgb"):
            r, g, b = color.split(",")
            r = int(r[-2:])
            g = int(g)
            b = int(b[:-1])
        else:
            r, g, b = rgb(color, type=tuple)
        itm.setForeground(QColor(r, g, b)) 
Example 29
Project: dcc   Author: amimo   File: DisasmViewMode.py    Apache License 2.0 5 votes vote down vote up
def drawSelected(self, qp):
        qp.setFont(self.font)

        cursorX, cursorY = self.cursor.getPosition()

        if len(self.OPCODES) - 1 < cursorY:
            return

        asm = self.OPCODES[cursorY]
        _, width, text = asm.getSelectedToken(cursorX)

        for i, asm in enumerate(self.OPCODES):
            for idx, length, value in asm.tokens():
                # skip current cursor position
                if cursorY == i and cursorX == idx:
                    continue

                # check every line, if match, select it
                if value == text:
                    qp.setOpacity(0.4)
                    brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
                    qp.fillRect(idx * self.fontWidth,
                                i * self.fontHeight + 2,
                                width * self.fontWidth,
                                self.fontHeight,
                                brush)
                    qp.setOpacity(1) 
Example 30
Project: dcc   Author: amimo   File: DisasmViewMode.py    Apache License 2.0 5 votes vote down vote up
def _drawRow(self, qp, cemu, row, asm, offset=-1):
        log.debug('DRAW AN INSTRUCTION %s %s %s %s %s', asm, row, asm.get_name(), len(asm.get_operands(offset)), hex(self.getPageOffset()))

        qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))

        hex_data = asm.get_hex()

        # write hexdump
        cemu.writeAt(0, row, hex_data)

        # fill with spaces
        cemu.write((MNEMONIC_COLUMN - len(hex_data)) * ' ')

        # let's color some branch instr
        # if asm.isBranch():
        #    qp.setPen(QtGui.QPen(QtGui.QColor(255, 80, 0)))
        # else:
        qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))

        mnemonic = asm.get_name()
        cemu.write(mnemonic)

        # leave some spaces
        cemu.write((MNEMONIC_WIDTH - len(mnemonic)) * ' ')

        if asm.get_symbol():
            qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))
            cemu.write_c('[')

            qp.setPen(QtGui.QPen(QtGui.QColor('yellow'), 1, QtCore.Qt.SolidLine))
            cemu.write(asm.get_symbol())

            qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))
            cemu.write_c(']')

        self._write_operands(asm, qp, cemu, offset)
        self._write_comments(asm, qp, cemu, offset) 
Example 31
Project: dcc   Author: amimo   File: DisasmViewMode.py    Apache License 2.0 5 votes vote down vote up
def _write_comments(self, asm, qp, cemu, offset):
        comments = asm.get_comments()
        if comments:
            cemu.write(30 * ' ')

            qp.setPen(QtGui.QPen(QtGui.QColor(82, 192, 192), 1, QtCore.Qt.SolidLine))
            cemu.write('; "{0}"'.format(' '.join(comments))) 
Example 32
Project: dcc   Author: amimo   File: SourceViewMode.py    Apache License 2.0 5 votes vote down vote up
def drawCursor(self, qp):
        cursorX, cursorY = self.cursor.getPosition()

        xstart = cursorX
        width = 1

        qp.setBrush(QtGui.QColor(255, 255, 0))

        qp.setOpacity(0.5)
        qp.drawRect(xstart * self.fontWidth, cursorY * self.fontHeight, width * self.fontWidth, self.fontHeight + 2)
        qp.setOpacity(1) 
Example 33
Project: dcc   Author: amimo   File: HexViewMode.py    Apache License 2.0 5 votes vote down vote up
def drawCursor(self, qp):
        qp.setBrush(QtGui.QColor(255, 255, 0))
        if self.isInEditMode():
            qp.setBrush(QtGui.QColor(255, 102, 179))

        cursorX, cursorY = self.cursor.getPosition()

        columns = self.HexColumns[self.idxHexColumns]
        if cursorX > columns:
            self.cursor.moveAbsolute(columns - 1, cursorY)

        # get cursor position again, maybe it was moved
        cursorX, cursorY = self.cursor.getPosition()

        qp.setOpacity(0.8)
        if self.isInEditMode():
            qp.setOpacity(0.5)
        # cursor on text
        qp.drawRect((self.COLUMNS * 3 + self.gap + cursorX) * self.fontWidth, cursorY * self.fontHeight + 2,
                    self.fontWidth, self.fontHeight)

        # cursor on hex
        if not self.isInEditMode():
            qp.drawRect(cursorX * 3 * self.fontWidth, cursorY * self.fontHeight + 2, 2 * self.fontWidth,
                        self.fontHeight)
        else:
            if self.highpart:
                qp.drawRect(cursorX * 3 * self.fontWidth, cursorY * self.fontHeight + 2, 1 * self.fontWidth,
                            self.fontHeight)
            else:
                qp.drawRect(cursorX * 3 * self.fontWidth + self.fontWidth, cursorY * self.fontHeight + 2,
                            1 * self.fontWidth, self.fontHeight)

        qp.setOpacity(1) 
Example 34
Project: dcc   Author: amimo   File: HexViewMode.py    Apache License 2.0 5 votes vote down vote up
def selectionChanged(self, selected, deselected):
        item = self.ann_w.treeWidget.currentItem()
        if item:
            offset = item.getOffset()
            size = item.getSize()
            u = offset
            v = offset + size
            self.selector.addSelection((u, v, QtGui.QBrush(QtGui.QColor(125, 255, 0)), 0.2),
                                       type=TextSelection.SelectionType.NORMAL)
            self.goTo(u) 
Example 35
Project: dcc   Author: amimo   File: HexViewMode.py    Apache License 2.0 5 votes vote down vote up
def onColorPicker(self):
        """
        Show color-picker dialog to select color.

        Qt will use the native dialog by default.

        """
        dlg = QtGui.QColorDialog(QtGui.QColor(self._color), None)

        # if self._color:
        #    dlg.setCurrentColor(QtGui.QColor(self._color))

        if dlg.exec_():
            self.setColor(dlg.currentColor().name()) 
Example 36
Project: dcc   Author: amimo   File: BinViewMode.py    Apache License 2.0 5 votes vote down vote up
def drawCursor(self, qp):
        cursorX, cursorY = self.cursor.getPosition()
        qp.setBrush(self.themes['background_cursor'])

        if self.isInEditMode():
            qp.setBrush(QtGui.QColor(255, 102, 179))

        qp.setOpacity(0.8)
        qp.drawRect(cursorX * self.fontWidth, cursorY * self.fontHeight, self.fontWidth, self.fontHeight + 2)
        qp.setOpacity(1) 
Example 37
Project: kucher   Author: Zubax   File: model.py    GNU General Public License v3.0 5 votes vote down vote up
def _data_foreground(self, index: QModelIndex) -> QColor:
        node = self._unwrap(index)
        palette = QPalette()
        if node.register and (self.flags(index) & Qt.ItemIsEditable):
            if node.register.cached_value_is_default_value or not node.register.has_default_value:
                return palette.color(QPalette.Link)
            else:
                return palette.color(QPalette.LinkVisited)

        return palette.color(QPalette.WindowText) 
Example 38
Project: geoscience   Author: rolandhill   File: SectionGrid.py    GNU General Public License v3.0 5 votes vote down vote up
def setStyle(self, layer, labelSuffix='', labels=True):
        # Set the line style
        r = layer.renderer()
        r.symbol().setColor(QtGui.QColor('grey'))
        r.symbol().setOpacity(0.5)

        #Set the label style
        if labels:
            settings = QgsPalLayerSettings()
            textFormat = QgsTextFormat()
            textFormat.setFont(QtGui.QFont("Arial", 10))
            textFormat.setColor(QtGui.QColor('grey'))
            textFormat.setOpacity(0.5)
            settings.setFormat(textFormat)
            if labelSuffix == '':
                settings.fieldName = 'Label'
            else:
    #            settings.fieldName = 'Label'
                settings.fieldName = str.format("format( '%%1%%2',  format_number(Label, 0), ' %s')" % labelSuffix)
                settings.isExpression = True
            settings.formatNumbers = True
            settings.decimals = 0
            settings.placement = QgsPalLayerSettings.Line
            labeling = QgsVectorLayerSimpleLabeling(settings)
            layer.setLabeling(labeling)
            layer.setLabelsEnabled(True) 
Example 39
Project: Python-GUI   Author: arpitj07   File: Project.py    MIT License 5 votes vote down vote up
def combo2(self):
        myteam=sqlite3.connect("TEAM.db")
        cu= myteam.cursor()
        
        team = self.eval_screen.SelectTeam.currentText()
        cu.execute("SELECT PlAYERS from team WHERE NAMES='"+team+"';")
        player= cu.fetchall()
        self.eval_screen.PlayerList.clear()
        for i in range(len(player)):
            item= QtWidgets.QListWidgetItem(player[i][0])
            font = QtGui.QFont()
            font.setBold(True)
            font.setWeight(75)
            item.setFont(font)
            item.setBackground(QtGui.QColor('#ffff99'))
            self.eval_screen.PlayerList.addItem(item)
        
        cu.execute("SELECT SCORES from team WHERE NAMES='"+team+"';")
        score=cu.fetchall()
        self.teamscore=[]
        for i in range(len(score)):
            self.teamscore.append(score[i][0])
    
        self.eval_screen.ScoreList.clear()
        for i in range(len(score)):
            items= QtWidgets.QListWidgetItem(str(score[i][0]))
            font = QtGui.QFont()
            font.setBold(True)
            font.setWeight(75)
            items.setFont(font)
            items.setBackground(QtGui.QColor('#fdc086'))
            self.eval_screen.ScoreList.addItem(items) 
Example 40
Project: Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader   Author: HA6Bots   File: videoeditor.py    MIT License 5 votes vote down vote up
def updateColors(self):
        for x, mainComment in enumerate(self.scriptWrapper.scriptMap):
            self.selectedMainComment = None
            for y, subComments in enumerate(mainComment):
                if y == 0:
                    self.selectedMainComment = self.getTopLevelByName("Main Comment %s" % str(x))
                    if subComments is True:
                        self.selectedMainComment.setForeground(0, QtGui.QBrush(QtGui.QColor("green")))
                    else:
                        self.selectedMainComment.setForeground(0, QtGui.QBrush(QtGui.QColor("red")))
                else:
                    if subComments is True:
                        self.selectedMainComment.child(y - 1).setForeground(0, QtGui.QBrush(QtGui.QColor("green")))
                    else:
                        self.selectedMainComment.child(y - 1).setForeground(0, QtGui.QBrush(QtGui.QColor("red"))) 
Example 41
Project: Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader   Author: HA6Bots   File: videoeditor.py    MIT License 5 votes vote down vote up
def animategroup(self, widgets, color):
        self.changeanimationgroup = QParallelAnimationGroup()
        for widget in widgets:
            effect = QtWidgets.QGraphicsColorizeEffect(widget)
            widget.setGraphicsEffect(effect)
            anim = QtCore.QPropertyAnimation(effect, b"color")
            anim.setDuration(500)
            anim.setStartValue(QtGui.QColor(0, 0, 0))
            anim.setKeyValueAt(0.25, color)
            anim.setEndValue(QtGui.QColor(0, 0, 0))
            self.changeanimationgroup.addAnimation(anim)
        self.changeanimationgroup.start() 
Example 42
Project: openeo-qgis-plugin   Author: Open-EO   File: drawPoly.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, iface, action):
        canvas = iface  #.mapCanvas()
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas
        self.iface = iface
        self.action = action
        self.status = 0
        mFillColor = QColor(254, 178, 76, 63)
        self.rb = QgsRubberBand(self.canvas, QgsWkbTypes.PolygonGeometry)
        self.rb.setColor(mFillColor)
        #return None 
Example 43
Project: cct   Author: awacha   File: devicestatus.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def checkIfDeviceIsConnected(self, device: Device):
        if device.get_connected():
            color = QtGui.QColor('lightgreen')
            tooltip = 'Connected to {}'.format(':'.join([str(x) for x in device.deviceconnectionparameters]))
        else:
            color = QtGui.QColor('red')
            tooltip = 'Disconnected'
        self.setLabelBackgroundColor(self.connectedLabel, color)
        self.connectedLabel.setToolTip(tooltip) 
Example 44
Project: cct   Author: awacha   File: devicestatus.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def checkIfReady(self, device: Device):
        if device.is_ready():
            color = QtGui.QColor('lightgreen')
            tooltip = 'Device is ready'
        else:
            color = QtGui.QColor('red')
            tooltip = 'Device is not ready'
        self.setLabelBackgroundColor(self.readyLabel, color)
        self.readyLabel.setToolTip(tooltip) 
Example 45
Project: cct   Author: awacha   File: devicestatus.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def checkIfBusy(self, device: Device, status=None):
        if device.is_busy(status):
            color = QtGui.QColor('yellow')
            tooltip = 'Device is busy'
            text = 'BU'
        else:
            color = QtGui.QColor('lightgreen')
            tooltip = 'Device is idle'
            text = 'ID'
        self.setLabelBackgroundColor(self.busyLabel, color)
        self.busyLabel.setToolTip(tooltip)
        self.busyLabel.setText(text) 
Example 46
Project: cct   Author: awacha   File: devicestatus.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def onDeviceTelemetry(self, device: Device, telemetry: TelemetryInfo):
        if telemetry.last_recv > 5:
            color = QtGui.QColor('red')
            tooltip = 'Device is not responding. Last message received {:.3f} seconds ago'.format(telemetry.last_recv)
        else:
            color = QtGui.QColor('lightgreen')
            tooltip = 'Last message received {:.3f} seconds ago'.format(telemetry.last_recv)
        self.setLabelBackgroundColor(self.lastRecvLabel, color)
        self.lastRecvLabel.setToolTip(tooltip)

        if telemetry.last_send > 5:
            color = QtGui.QColor('red')
            tooltip = 'Not sending to device. Last message sent {:.3f} seconds ago'.format(telemetry.last_send)
        else:
            color = QtGui.QColor('lightgreen')
            tooltip = 'Last message sent {:.3f} seconds ago'.format(telemetry.last_send)
        self.setLabelBackgroundColor(self.lastSendLabel, color)
        self.lastSendLabel.setToolTip(tooltip)

        if telemetry.watchdog_active:
            if telemetry.watchdog > telemetry.watchdog_timeout:
                color = QtGui.QColor('red')
                tooltip = 'Communication watchdog error (wd value: {:.2f} sec)'.format(telemetry.watchdog)
            elif telemetry.watchdog > telemetry.watchdog_timeout * 0.5:
                color = QtGui.QColor('yellow')
                tooltip = 'Communication watchdog warning (wd value: {:.2f} sec)'.format(telemetry.watchdog)
            else:
                color = QtGui.QColor('lightgreen')
                tooltip = 'Communication watchdog OK (wd value: {:.2f} sec)'.format(telemetry.watchdog)
            self.setLabelBackgroundColor(self.watchDogLabel, color)
            self.watchDogLabel.setToolTip(tooltip)
            self.watchDogLabel.setEnabled(True)
        else:
            self.watchDogLabel.setEnabled(False)
            self.setLabelBackgroundColor(self.watchDogLabel, QtGui.QColor('gray')) 
Example 47
Project: cct   Author: awacha   File: logindialog.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def accept(self):
        if self.credo.services['accounting'].authenticate(self.operatorLineEdit.text(), self.passwordLineEdit.text()):
            return super().accept()
        else:
            palette = self.passwordLineEdit.palette()
            palette.setColor(QtGui.QPalette.Base, QtGui.QColor('red'))
            self.passwordLineEdit.setPalette(palette)
            return False 
Example 48
Project: cct   Author: awacha   File: detector.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setFlagBackground(self, flag: QtWidgets.QLabel, state: str):
        palette = flag.palette()
        assert isinstance(palette, QtGui.QPalette)
        if state == 'ok':
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('green'))
        elif state == 'warning':
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('orange'))
        else:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))
        flag.setPalette(palette)
        flag.setAutoFillBackground(True) 
Example 49
Project: cct   Author: awacha   File: motorconfig.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def onWidgetChanged(self):
        pal = self.sender().palette()
        pal.setColor(pal.Base, QtGui.QColor('yellow'))
        self.sender().setPalette(pal) 
Example 50
Project: cct   Author: awacha   File: motorconfig.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def onApply(self):
        changes = {}
        for widget, attribute in [
            (self.driveRMSCurrentDoubleSpinBox, 'maxcurrent'),
            (self.standbyRMSCurrentDoubleSpinBox, 'standbycurrent'),
            (self.freewheelingDelayDoubleSpinBox, 'freewheelingdelay'),
            (self.pulseDivisorSpinBox, 'pulsedivisor'),
            (self.rampDivisorSpinBox, 'rampdivisor'),
            (self.microstepExponentSpinBox, 'microstepresolution'),
            (self.rawMaxSpeedSpinBox, 'maxspeedraw'),
            (self.rawMaxAccelSpinBox, 'maxaccelerationraw'),
            (self.leftSwitchEnabledCheckBox, 'leftswitchenable'),
            (self.rightSwitchEnabledCheckBox, 'rightswitchenable'),
            (self.leftLimitDoubleSpinBox, 'softleft'),
            (self.rightLimitDoubleSpinBox, 'softright')]:
            assert isinstance(widget, QtWidgets.QWidget)
            if widget.palette().color(QtGui.QPalette.Base) != QtGui.QColor('yellow'):
                continue
            if isinstance(widget, (QtWidgets.QDoubleSpinBox, QtWidgets.QSpinBox)):
                changes[attribute] = widget.value()
            elif isinstance(widget, QtWidgets.QCheckBox):
                changes[attribute] = widget.isChecked()
        result = QtWidgets.QMessageBox.warning(
            self,
            'Confirm changes',
            'Do you really want to commit the following changes to motor {}?\n'.format(self.motor.name) +
            '\n'.join(['{}: {} -> {}'.format(attr, self.motor.get_variable(attr), changes[attr])
                       for attr in sorted(changes)]),
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No
        )
        if result == QtWidgets.QMessageBox.Yes:
            for attr in changes:
                self.motor.set_variable(attr, changes[attr])
        self.resetEntryBackgrounds() 
Example 51
Project: cct   Author: awacha   File: xraysource.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setFlagBackground(self, flag: QtWidgets.QLabel, state: bool):
        palette = flag.palette()
        assert isinstance(palette, QtGui.QPalette)
        if state is None:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('gray'))
            palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('black'))
        elif state:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('lightgreen'))
            palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('black'))
        else:
            palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))
            palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor('white'))
        flag.setPalette(palette)
        flag.setAutoFillBackground(True) 
Example 52
Project: cct   Author: awacha   File: fsnranges.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def data(self, index: QtCore.QModelIndex, role: int = QtCore.Qt.DisplayRole) -> typing.Any:
        if role == QtCore.Qt.DisplayRole:
            return str(self._data[index.row()][index.column()])
        elif role == QtCore.Qt.BackgroundColorRole:
            if self._data[index.row()][0]>self._data[index.row()][1]:
                return QtGui.QColor('orange')
            else:
                return None
        elif role == QtCore.Qt.DecorationRole:
            if self._data[index.row()][0] > self._data[index.row()][1]:
                return QtGui.QIcon.fromTheme('dialog-warning')
        return None 
Example 53
Project: IC   Author: Awapic   File: interface_catchment.py    GNU General Public License v3.0 5 votes vote down vote up
def showLayer(self, layer, params):
        added_layer = QgsProject.instance().addMapLayer(layer)
        color = params.get('color')
        width = params.get('width')
        if color:
            added_layer.renderer().symbol().setColor(QColor(color))
        if width:
            added_layer.renderer().symbol().setWidth(width)
        added_layer.triggerRepaint()
        self.iface.layerTreeView().refreshLayerSymbology(added_layer.id())
        # self.log('Added layer "%s" with color: %s, width: %s to the map.' %(layer.sourceName(),color,width)) 
Example 54
Project: musaic   Author: al165   File: elements.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, block, instrument, track_view, bar_num, height=80, *args, **kwargs):
        super(QtWidgets.QGraphicsItem, self).__init__(*args, **kwargs)

        self.block = block
        self.section = block.sections[0]
        self.section.addCallback(self.sectionChanged)

        self.instrument = instrument
        self._track_view = track_view
        self.bar_num = bar_num
        self._height = height

        self._bar_width = self._track_view.getBarWidth()
        self._y = self.instrument.id_ * self._track_view.getInstrumentHeight()

        hue = (self.section.id_ * 0.16) % 1.0
        r, g, b = hsv_to_rgb(hue, 0.8, 0.5)
        hex_color = f'#{hex(int(r*255))[2:]}{hex(int(g*255))[2:]}{hex(int(b*255))[2:]}'
        self._section_color = QtGui.QColor(hex_color)

        self._rect = QtCore.QRectF(0, 0, len(self.section)*self._bar_width, height)
        self._backgroud_color = QtGui.QColor('#222222')
        self._repeat_background_color = QtGui.QColor('#101010')
        self._main_note_color = QtGui.QColor('#aaaaaa')
        self._second_note_color = QtGui.QColor('#666666')

        self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)

        self._dragged = False 
Example 55
Project: PyQt-multifunctional-uart-helper   Author: IronSublimate   File: Wave.py    MIT License 5 votes vote down vote up
def add_new_data(self, data: dict):
        self.x += self.time.msec()
        self.time.start()
        if self.x > 10000:
            self.ax.setRange(self.x - 10000, self.x)
        for key in data:
            try:
                value = float(data[key])
            except ValueError:
                continue
            if value > self.ymax:
                self.ymax = value
                self.ay.setRange(self.ymin, self.ymax)
            elif value < self.ymin:
                self.ymin = value
                self.ay.setRange(self.ymin, self.ymax)
            if key in self.lines:
                if self.lines[key].__len__() >= 32:
                    # self.lines[key].replace(0,self.x, value)
                    self.lines[key].remove(0)
                # else:
                self.lines[key].append(self.x, value)
            else:
                # ls = QSplineSeries(self)
                ls = QLineSeries(self)
                ls.append(self.x, value)
                ls.setColor(QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
                ls.setName(key)
                self.chart().addSeries(ls)
                self.chart().setAxisX(self.ax, ls)
                self.chart().setAxisY(self.ay, ls)
                self.lines[key] = ls 
Example 56
Project: pyaudiorestoration   Author: HENDRIX-ZT2   File: difeq_gui.py    GNU General Public License v2.0 5 votes vote down vote up
def update_color(self, eq_name):
		item = self.listWidget.findItems(eq_name, QtCore.Qt.MatchFixedString)[-1]
		#don't include the first (blue) -> reserved for the bold line
		item.setForeground( QtGui.QColor(self.colors[self.names.index(eq_name)+1]) ) 
Example 57
Project: MeiTingTrunk   Author: Xunius   File: _MainFrameLibTreeSlots.py    GNU General Public License v3.0 5 votes vote down vote up
def removeFolderHighlights(self):

        ori_color=QBrush(QColor(255,255,255))
        root=self.libtree.invisibleRootItem()
        for item in iterTreeWidgetItems(self.libtree, root):
            item.setBackground(0, ori_color)

        return 
Example 58
Project: Lector   Author: BasioMeusPuga   File: definitionsdialog.py    GNU General Public License v3.0 5 votes vote down vote up
def color_background(self, set_initial=False):
        if set_initial:
            background = self.parent.settings['dialog_background']
        else:
            self.previous_position = self.pos()
            self.parent.get_color()
            background = self.parent.settings['dialog_background']

        # Calculate inverse color for the background so that
        # the text doesn't look blank
        r, g, b, alpha = background.getRgb()
        inv_average = 255 - (r + g + b) // 3
        if 100 < inv_average < 150:
            inv_average = 255

        foreground = QtGui.QColor(
            inv_average, inv_average, inv_average, alpha)

        self.setStyleSheet(
            "QDialog {{background-color: {0}}}".format(background.name()))
        self.definitionView.setStyleSheet(
            "QTextBrowser {{color:{0}; background-color: {1}}}".format(
                foreground.name(), background.name()))

        if not set_initial:
            self.show() 
Example 59
Project: Lector   Author: BasioMeusPuga   File: settings.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent):
        self.parent = parent
        self.settings = QtCore.QSettings('Lector', 'Lector')

        default_profile1 = {
            'font': 'Noto Sans Fallback',
            'foreground': QtGui.QColor().fromRgb(0, 0, 0),
            'background': QtGui.QColor().fromRgb(216, 216, 216),
            'padding': 150,
            'font_size': 30,
            'line_spacing': 110,
            'text_alignment': 'justify'}

        default_profile2 = {
            'font': 'Roboto',
            'foreground': QtGui.QColor().fromRgb(194, 194, 194),
            'background': QtGui.QColor().fromRgb(22, 22, 22),
            'padding': 150,
            'font_size': 30,
            'line_spacing': 110,
            'text_alignment': 'justify'}

        default_profile3 = {
            'font': 'Clear Sans',
            'foreground': QtGui.QColor().fromRgb(101, 123, 131),
            'background': QtGui.QColor().fromRgb(0, 43, 54),
            'padding': 150,
            'font_size': 30,
            'line_spacing': 110,
            'text_alignment': 'justify'}

        self.default_profiles = [
            default_profile1, default_profile2, default_profile3]

        self.default_comic_profile = {
            'padding': 100,  # pixel padding on either size
            'background': QtGui.QColor().fromRgb(0, 0, 0),
            'zoom_mode': 'bestFit'} 
Example 60
Project: SpriteMator   Author: rafaelvasco   File: utils.py    Apache License 2.0 5 votes vote down vote up
def generate_random_color(hue=None, sat=None, val=None):
    hue = random.randint(0, 255) if hue is None else hue
    sat = random.randint(0, 255) if sat is None else sat
    val = random.randint(0, 255) if val is None else val

    color = QColor()
    color.setHsv(hue, sat, val)

    return color


# -------------------------------------------------------- 
Example 61
Project: SpriteMator   Author: rafaelvasco   File: animation_manager_widget.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):

        super(FrameStrip, self).__init__()

        self._sprite = None

        self._frameList = None

        self._frameSize = 70

        self._maxFramesOnView = 6

        self._framePadding = 4

        self._horizontalShift = 0

        self._pen = QPen(QColor(0, 179, 255))
        self._pen.setCapStyle(Qt.SquareCap)
        self._pen.setJoinStyle(Qt.MiterJoin)
        self._pen.setWidth(4.0)

        self.setContentsMargins(0, 0, 0, 0)

        self.setMinimumSize(self._frameSize + self._framePadding * 2,
                            self._frameSize + self._framePadding * 2)
        self.setMaximumHeight(self._frameSize + self._framePadding * 2)

        self._checkerTile = ResourcesCache.get("CheckerTileLight") 
Example 62
Project: SpriteMator   Author: rafaelvasco   File: canvas_widget.py    Apache License 2.0 5 votes vote down vote up
def _init_canvas_state(self):

        self._pixelSize = 1
        self._primaryColor = QColor('black')
        self._secondaryColor = QColor('white')
        self._currentTool = self.find_tool_by_name('Pen')
        self._primaryInk = self.find_ink_by_name('Solid')
        self._secondaryInk = self.find_ink_by_name('Eraser')

        self.onion_skin_enabled = False

        self.backlight_enabled = True 
Example 63
Project: SpriteMator   Author: rafaelvasco   File: tools.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, canvas):
        super(Manipulator, self).__init__(canvas)

        self._name = 'Manipulator'
        self._load_icon(":/icons/ico_sel_move", ":/icons/ico_sel_move_hover")
        self._cursor = QPixmap(":/images/mover_cursor")

        self._pressMousePos = QPoint()
        self._lastMousePos = QPoint()
        self._curMousePos = QPoint()
        self._selectionRectangle = QRect()
        self._selectionRectColor = QColor(255, 255, 255, 50)
        self._selectionRectDashOffset = 0
        self._selectionImage = None
        self._cutOnSelection = True
        self._doEraseOnSelectionMove = False

        self._selectionBorderPen = QPen()
        self._selectionBorderPen.setWidth(0)
        self._selectionBorderPen.setStyle(Qt.DashLine)
        self._selectionBorderPen.setColor(Qt.white)

        self._selectionRectNodesPen = QPen()
        self._selectionRectNodesPen.setWidth(0)
        self._selectionRectNodesPen.setColor(Qt.white)

        self._state = ManipulatorState.Idle 
Example 64
Project: SpriteMator   Author: rafaelvasco   File: application.py    Apache License 2.0 5 votes vote down vote up
def _load_assets():

        # Fonts #

        QFontDatabase.addApplicationFont(":/fonts/font_nokia")
        QFontDatabase.addApplicationFont(":/fonts/font_flx")

        default_font = QFont("Nokia Cellphone FC")
        default_font.setPointSize(12)

        small_font = QFont("flxpixl")
        small_font.setPointSize(12)

        ResourcesCache.register_resource("BigFont", default_font)
        ResourcesCache.register_resource("SmallFont", small_font)

        # Pixmaps #

        checker_tile_light = utils.generate_checkerboard_tile(8, QColor(238, 238, 238),
                                                              QColor(255, 255, 255))
        checker_tile_dark = utils.generate_checkerboard_tile(8, QColor(59, 59, 59),
                                                             QColor(63, 63, 63))

        ResourcesCache.register_resource("CheckerTileLight", checker_tile_light)
        ResourcesCache.register_resource("CheckerTileDark", checker_tile_dark)

        tool_cursor_1 = QPixmap(':/images/tool_cursor_1')

        ResourcesCache.register_resource('ToolCursor1', tool_cursor_1) 
Example 65
Project: eddy   Author: obdasystems   File: view.py    GNU General Public License v3.0 5 votes vote down vote up
def setGridSize(self, size):
        """
        Sets the grid size.
        """
        action = self.session.action('toggle_grid')
        size = clamp(size, 0)
        if size <= 0 or not action.isChecked():
            brush = QtGui.QBrush(QtCore.Qt.NoBrush)
        else:
            image = QtGui.QImage(size, size, QtGui.QImage.Format_RGB32)
            image.fill(QtCore.Qt.white)
            painter = QtGui.QPainter(image)
            painter.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor(80, 80, 80, 255)), 1, QtCore.Qt.SolidLine))
            painter.drawPoint(QtCore.QPointF(0, 0))
            painter.end()
            brush = QtGui.QBrush(image)
        self.setBackgroundBrush(brush) 
Example 66
Project: eddy   Author: obdasystems   File: log.py    GNU General Public License v3.0 5 votes vote down vote up
def fmt(color):
        """
        Return a QTextCharFormat with the given attributes.
        """
        _color = QtGui.QColor()
        _color.setNamedColor(color)
        _format = QtGui.QTextCharFormat()
        _format.setForeground(_color)
        return _format 
Example 67
Project: eddy   Author: obdasystems   File: attribute.py    GNU General Public License v3.0 5 votes vote down vote up
def updateNode(self, functional=None, **kwargs):
        """
        Update the current node.
        :type functional: bool
        """
        if functional is None:
            functional = self.isFunctional()

        # FUNCTIONAL POLYGON (SHAPE)
        path1 = QtGui.QPainterPath()
        path1.addEllipse(self.polygon.geometry())
        path2 = QtGui.QPainterPath()
        path2.addEllipse(QtCore.QRectF(-7, -7, 14, 14))
        self.fpolygon.setGeometry(path1.subtracted(path2))

        # FUNCTIONAL POLYGON (PEN & BRUSH)
        pen = QtGui.QPen(QtCore.Qt.NoPen)
        brush = QtGui.QBrush(QtCore.Qt.NoBrush)
        if functional:
            pen = QtGui.QPen(QtGui.QBrush(QtGui.QColor(0, 0, 0, 255)), 1.1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)
            brush = QtGui.QBrush(QtGui.QColor(252, 252, 252, 255))
        self.fpolygon.setPen(pen)
        self.fpolygon.setBrush(brush)

        # SELECTION + BACKGROUND + CACHE REFRESH
        super().updateNode(**kwargs) 
Example 68
Project: hpimon   Author: jjnurminen   File: hpimon.py    MIT License 5 votes vote down vote up
def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.begin(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setBrush(QtGui.QColor(self.color))
        painter.drawEllipse(0, 0, self.diam, self.diam)
        painter.end() 
Example 69
Project: Anki-TouchScreen   Author: krassowski   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def ts_change_color():
    """
    Open color picker and set chosen color to text (in content)
    """
    global ts_color
    qcolor_old = QColor(ts_color)
    qcolor = QColorDialog.getColor(qcolor_old)
    if qcolor.isValid():
        ts_color = qcolor.name()
        execute_js("color = '" + ts_color + "'; update_pen_settings()")
        ts_refresh() 
Example 70
Project: openocd-svd   Author: esynr3z   File: ui_widgets.py    MIT License 4 votes vote down vote up
def __init__(self, svd_periph):
        QWidget.__init__(self)
        self.svd = svd_periph
        self.setObjectName(self.svd["name"])
        # vertical layout inside
        self.vert_layout = QVBoxLayout(self)
        self.vert_layout.setContentsMargins(6, 6, 6, 6)
        self.vert_layout.setSpacing(6)
        # label with peripheral description and read all button
        self.header = QWidget(self)
        self.horiz_layout = QHBoxLayout(self.header)
        self.lab_periph_descr = QLabel(self.header)
        self.lab_periph_descr.setText(self.svd["description"])
        self.lab_periph_descr.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse |
                                                      QtCore.Qt.TextSelectableByMouse)
        self.horiz_layout.addWidget(self.lab_periph_descr)
        self.btn_readall = QPushButton(self.header)
        self.btn_readall.setText("Read all")
        self.btn_readall.setMaximumSize(QtCore.QSize(100, 20))
        self.btn_readall.clicked.connect(self.handle_btn_readall_clicked)
        self.horiz_layout.addWidget(self.btn_readall)
        self.vert_layout.addWidget(self.header)
        # tree widget for displaying regs
        reg_col = 0
        val_col = 1
        self.tree_regs = QTreeWidget(self)
        self.tree_regs.itemSelectionChanged.connect(self.handle_tree_selection_changed)
        self.tree_regs.headerItem().setText(reg_col, "Register")
        self.tree_regs.setColumnWidth(reg_col, 200)
        self.tree_regs.headerItem().setText(val_col, "Value")
        for reg in self.svd["regs"]:
            item0 = QTreeWidgetItem(self.tree_regs)
            item0.svd = reg
            item0.setText(reg_col, reg["name"])
            background = QColor(240, 240, 240)
            item0.setBackground(0, background)
            item0.setBackground(1, background)
            reg_edit = RegEdit(reg)
            self.tree_regs.setItemWidget(item0, val_col, reg_edit)
            self.tree_regs.addTopLevelItem(item0)
            for field in reg["fields"]:
                item1 = QTreeWidgetItem(item0)
                item1.svd = field
                item1.setText(reg_col, field["name"])
                self.tree_regs.setItemWidget(item1, val_col, reg_edit.fields[field["name"]])
                item0.addChild(item1)
        self.vert_layout.addWidget(self.tree_regs)
        # label with register/field description
        self.lab_info = QLabel(self)
        self.lab_info.setMaximumSize(QtCore.QSize(16777215, 40))
        self.lab_info.setMinimumSize(QtCore.QSize(16777215, 40))
        self.lab_info.setText("")
        self.lab_info.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse |
                                              QtCore.Qt.TextSelectableByMouse)
        self.vert_layout.addWidget(self.lab_info)

    # -- Slots -- 
Example 71
Project: dcc   Author: amimo   File: DisasmViewMode.py    Apache License 2.0 4 votes vote down vote up
def _write_operands(self, asm, qp, cemu, offset):
        qp.setPen(QtGui.QPen(QtGui.QColor(192, 192, 192), 1, QtCore.Qt.SolidLine))

        operands = asm.get_operands(offset)
        for operand in operands:
            qp.save()

            if operand[0] == dvm.OPERAND_REGISTER:
                qp.setPen(QtGui.QPen(QtGui.QColor('white')))
                cemu.write("%s" % operand[1])

            elif operand[0] == dvm.OPERAND_LITERAL:
                qp.setPen(QtGui.QPen(QtGui.QColor('yellow')))
                cemu.write("%s" % operand[1])

            elif operand[0] == dvm.OPERAND_RAW:
                qp.setPen(QtGui.QPen(QtGui.QColor('red')))
                cemu.write("%s" % operand[1])

            elif operand[0] == dvm.OPERAND_OFFSET:
                qp.setPen(QtGui.QPen(QtGui.QColor('purple')))
                cemu.write("%s" % operand[1])

            elif operand[0] & dvm.OPERAND_KIND:
                if operand[0] == (dvm.OPERAND_KIND + dvm.KIND_STRING):
                    qp.setPen(QtGui.QPen(QtGui.QColor('red')))
                    cemu.write("%s" % operand[1])

                elif operand[0] == (dvm.OPERAND_KIND + dvm.KIND_METH):
                    qp.setPen(QtGui.QPen(QtGui.QColor('cyan')))
                    cemu.write("%s" % operand[1])

                elif operand[0] == (dvm.OPERAND_KIND + dvm.KIND_FIELD):
                    qp.setPen(QtGui.QPen(QtGui.QColor('green')))
                    cemu.write("%s" % operand[1])

                elif operand[0] == (dvm.OPERAND_KIND + dvm.KIND_TYPE):
                    qp.setPen(QtGui.QPen(QtGui.QColor('blue')))
                    cemu.write("%s" % operand[1])

            cemu.write(" ")
            qp.restore() 
Example 72
Project: dcc   Author: amimo   File: binwindow.py    Apache License 2.0 4 votes vote down vote up
def _search(self, data, text, start, previous=False):

        self._lastText = text
        if text == '':
            return -1

        if not previous:
            idx1 = data.find(text, start)
            text1 = '\0'.join(text)

            idx2 = data.find(text1, start)

            idx = idx1
            if idx1 == -1:
                idx = idx2
            else:
                if idx2 < idx1 and idx2 != -1:
                    idx = idx2

        else:
            idx1 = data.rfind(text, 0, start)
            text1 = '\0'.join(text)

            idx2 = data.rfind(text1, 0, start)

            idx = idx1

            if idx1 == -1:
                idx = idx2
            else:
                if idx2 > idx1 and idx2 != -1:
                    idx = idx2

        if idx > -1:
            self._lastIdx = idx

        if idx > -1:
            self._viewMode.selector.addSelection((idx, idx + len(text), QtGui.QBrush(QtGui.QColor(125, 0, 100)), 0.8),
                                                 type=TextSelection.SelectionType.NORMAL)
            self._viewMode.goTo(idx)

        return idx 
Example 73
Project: dcc   Author: amimo   File: binwindow.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, parent, source, title):
        super(binWidget, self).__init__()
        Observable.__init__(self)
        self.parent = parent

        self.title = title
        self.active = False
        # offset for text window
        # self.data = mapped
        self.dataOffset = 0

        self.dataModel = source
        self.cursor = Cursor(0, 0)

        self.themes = {
            'font': QtGui.QFont('Monaco', 9, QtGui.QFont.Light),
            'background': QtGui.QColor(0x00, 0x2b, 0x36),
            'background_cursor': QtGui.QColor(255, 255, 0),
            'selection': QtGui.QColor(125, 255, 0),
            'pen': QtGui.QColor(0xb5, 0x89, 0x00)
        }

        self.multipleViewModes = []
        for view_mode in self.dataModel.GetViews():
            v = view_mode(self.themes, self.size().width(), self.size().height(), self.dataModel, self.cursor, self)
            textDecorator = HighlightASCII(TextDecorator(v))

            v.setTransformationEngine(textDecorator)

            self.multipleViewModes.append(v)

        self.viewMode = self.multipleViewModes[0]

        self.Banners = Banners()

        self.Banners.add(FileAddrBanner(self.themes, self.dataModel, self.viewMode))
        self.Banners.add(TopBanner(self.themes, self.dataModel, self.viewMode))
        self.Banners.add(BottomBanner(self.themes, self.dataModel, self.viewMode))

        self.offsetWindow_h = 0
        self.offsetWindow_v = 0
        self.searchable = Searchable(self.dataModel, self.viewMode)

        self.initUI()

        self.searchWindow = SearchWindow(self, None, self.searchable)

        self.addHandler(self.searchable)
        self.addHandler(self.Banners)

        self.notify(self.viewMode) 
Example 74
Project: Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader   Author: HA6Bots   File: videoeditor.py    MIT License 4 votes vote down vote up
def updateDisplay(self, keep=None):
        self.scriptWrapper.saveScriptWrapper()
        self.getCurrentWidget(self.mainCommentIndex, self.childCommentIndex).setForeground(0, QtGui.QBrush(QtGui.QColor("blue")))
        comment_wrapper = self.scriptWrapper.getCommentData(self.mainCommentIndex, self.childCommentIndex)
        comment_text = comment_wrapper.text
        comment_author = comment_wrapper.author
        comment_upvotes = comment_wrapper.upvotes

        self.updateTextView(comment_wrapper)
        self.textView.setText("Text View: %s"%(self.getCurrentWidget(self.mainCommentIndex, self.childCommentIndex).text(0)))
        self.author.setText("Author: %s"%comment_author)
        self.upvotes.setText("Upvotes: %s"%comment_upvotes)
        self.wordscomment.setText("Words: %s"%len(comment_text.split(" ")))
        self.characterscomment.setText("Characters: %s"%len(comment_text))
        self.commentthreads.setText("Comment Threads: %s"%self.scriptWrapper.getEditedCommentThreadsAmount())
        self.commentamount.setText("Comments: %s"%self.scriptWrapper.getEditedCommentAmount())
        self.totalwords.setText("Total Words: %s"%self.scriptWrapper.getEditedWordCount())
        self.estvidtime.setText("Estimated Video Time: %s"%self.scriptWrapper.getEstimatedVideoTime())
        self.totalcharacters.setText("Total Characters: %s"%self.scriptWrapper.getEditedCharacterCount())
        self.progressBar.setValue((self.scriptWrapper.getEstimatedVideoTime() / settings.recommendedLength) * 100)

        animation_group_on_change = [self.commentamount, self.commentthreads, self.totalwords, self.estvidtime, self.totalaudiolines]
        if keep is True:
            self.animategroup(animation_group_on_change, QtGui.QColor(0, 128, 0))
        elif keep is False:
            self.animategroup(animation_group_on_change, QtGui.QColor(255, 0, 0))

        content2 = [(videoscriptcore.CommentWrapper("user1", "funny main post", 42),
                     videoscriptcore.CommentWrapper("user2", "funny reply", 30),
                     videoscriptcore.CommentWrapper("user3", "more funny reply", 2))]

        try:
            stillframe = standardredditformat.StandardReddit("standardredditformat", self.videoScript.videosettings).stillImage(self.scriptWrapper.getCommentInformation(self.mainCommentIndex, self.childCommentIndex))
            height, width, channel = stillframe.shape
            bytesPerLine = 3 * width
            qImg = QImage(stillframe.data, width, height, bytesPerLine, QImage.Format_RGB888).scaled(self.imageArea.frameGeometry().width(), self.imageArea.frameGeometry().height(), QtCore.Qt.KeepAspectRatio)
            self.imageArea.setPixmap(QPixmap(qImg))
        except Exception:
            self.imageArea.setText("Rendering Error for Post, skipping")
            print("Need to log this comment")
            # [(<manualreview.videoscriptcore.CommentWrapper object at 0x0000000013FE9908>,)]
            self.skipComment()
        self.musicCat.setText("Music Category: %s" % self.videoScript.music_type) 
Example 75
Project: musaic   Author: al165   File: elements.py    GNU General Public License v3.0 4 votes vote down vote up
def drawBackground(self, painter, rect):
        #print('[TrackScene]', 'drawBackground()')
        scene_rect = self.parent().getSceneRect()

        bar_width = self.parent().getBarWidth()
        instrument_height = self.parent().getInstrumentHeight()

        brush = QtGui.QBrush()
        brush.setStyle(Qt.SolidPattern)
        brush.setColor(QtGui.QColor('#151515'))
        painter.fillRect(rect, brush)

        line_pen = QtGui.QPen(QtGui.QColor('#333333'), 1, Qt.SolidLine)
        painter.setPen(line_pen)

        width = max(painter.device().width(), scene_rect.width())
        height = scene_rect.height()
        num_bars = width//bar_width + 1
        num_ins = height//instrument_height + 1

        # draw vertical lines...
        if bar_width <= 10:
            skip = 8
        elif bar_width <= 20:
            skip = 4
        elif bar_width <= 40:
            skip = 2
        else:
            skip = 1

        lines = []
        for i in range(0, int(num_bars), skip):
            x = i*bar_width
            if x >= rect.left() and x <= rect.right():
                lines.append(QtCore.QLineF(x, rect.top(), x, rect.bottom()))
                #painter.drawLine(x, rect.top(), x, rect.bottom())
            painter.drawText(i*bar_width + 5, -10, str(i+1))

        painter.drawLines(lines)

        # draw horizontal lines...
        line_pen.setWidth(3)
        painter.setPen(line_pen)

        for j in range(int(num_ins)):
            y = j*instrument_height
            if y > rect.top() and y <= rect.bottom():
                painter.drawLine(rect.left(), y, rect.right(), y)

        super().drawBackground(painter, rect) 
Example 76
Project: musaic   Author: al165   File: elements.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, instrument, engine, track_view, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Plain)

        self.instrument = instrument
        self._engine = engine
        self._track_view = track_view

        self._selected_index = None
        self._selected_id = None

        control_layout = QtWidgets.QGridLayout()
        control_layout.setSpacing(2)
        control_layout.setContentsMargins(2, 2, 2, 2)

        self._instrument_name = self.instrument.name
        #self._instrument_color = QtGui.QColor('#aa0000')
        control_layout.addWidget(QtWidgets.QLabel(self._instrument_name), 0, 0)

        channel_select = QtWidgets.QSpinBox()
        channel_select.setRange(1, 8)
        channel_select.setValue(self.instrument.chan)
        channel_select.valueChanged.connect(self.changeChannel)
        channel_select.setToolTip('Sets the MIDI output channel')
        control_layout.addWidget(channel_select, 0, 1)

        add_section = QtWidgets.QPushButton('+')
        add_section.setToolTip('Add a new section to track')
        add_section.clicked.connect(self.newSection)
        control_layout.addWidget(add_section, 1, 0, 1, 2)

        generate_all = QtWidgets.QPushButton('gen')
        generate_all.setToolTip('Generate all empty measures in all sections')
        generate_all.clicked.connect(self.generateAll)
        control_layout.addWidget(generate_all, 2, 0)

        regenerate_all = QtWidgets.QPushButton('re-gen')
        regenerate_all.setToolTip('Regenerate all measures in all sections')
        regenerate_all.clicked.connect(lambda x: self.generateAll(True))
        control_layout.addWidget(regenerate_all, 2, 1)

        mute = QtWidgets.QPushButton('mute')
        mute.setCheckable(True)
        mute.setChecked(self.instrument.mute)
        mute.setToolTip('Mute the instrument')
        mute.clicked[bool].connect(self.mute)
        control_layout.addWidget(mute, 3, 0)

        octave = QtWidgets.QComboBox()
        octave.setToolTip('Transpose octave')
        octave.addItems(['+3', '+2', '+1', '--', '-1', '-2', '-3'])
        octave.setCurrentIndex(self.instrument.octave_transpose + 3)
        octave.currentTextChanged.connect(self.changeOctave)
        control_layout.addWidget(octave, 3, 1)

        self.instrument.track.addCallback(lambda x: self._track_view.buildSections(self.instrument.id_))
        self.setLayout(control_layout) 
Example 77
Project: MeiTingTrunk   Author: Xunius   File: doc_table.py    GNU General Public License v3.0 4 votes vote down vote up
def data(self, index, role):
        if not index.isValid():
            return QVariant()

        #if role == Qt.BackgroundRole:
            #if index.row()%2==0:
                #return QBrush(QColor(230,230,249))
                #pass

        if role == Qt.FontRole:
            font=self.settings.value('display/fonts/doc_table',QFont)
            if self.arraydata[index.row()][9] in [None, 'false']:
                font.setBold(True)
            else:
                font.setBold(False)
            return font

        if role==Qt.DisplayRole:
            if index.column() in self.icon_sec_indices:
                return
            elif index.column()==self.headerdata.index('added'):
                added=self.arraydata[index.row()][index.column()]
                if added:
                    # convert time to str
                    added=int(added[:10])
                    added=datetime.fromtimestamp(added)
                    if added.year==datetime.today().year:
                        added=added.strftime('%b-%d')
                    else:
                        added=added.strftime('%b-%d-%y')
                    return QVariant(added)
                else:
                    return
            else:
                return QVariant(self.arraydata[index.row()][index.column()])

        if role==Qt.EditRole:
            return QVariant(self.arraydata[index.row()][index.column()])

        #if role==Qt.TextAlignmentRole:
            #return Qt.AlignCenter
        if index.column() in self.check_sec_indices and role==Qt.CheckStateRole:
            if self.arraydata[index.row()][index.column()].isChecked():
                return Qt.Checked
            else:
                return Qt.Unchecked
        if index.column() in self.icon_sec_indices and role==Qt.DecorationRole:
            if self.arraydata[index.row()][index.column()]:
                return self.icon_section['has_file']
            else:
                return None

        if role != Qt.DisplayRole:
            return QVariant() 
Example 78
Project: Lector   Author: BasioMeusPuga   File: delegates.py    GNU General Public License v3.0 4 votes vote down vote up
def paint(self, painter, option, index):
        # This is a hint for the future
        # Color icon slightly red
        # if option.state & QtWidgets.QStyle.State_Selected:
            # painter.fillRect(option.rect, QtGui.QColor().fromRgb(255, 0, 0, 20))

        option = option.__class__(option)
        file_exists = index.data(QtCore.Qt.UserRole + 5)
        position_percent = index.data(QtCore.Qt.UserRole + 7)

        # The shadow pixmap currently is set to 420 x 600
        # Only draw the cover shadow in case the setting is enabled
        if self.parent.settings['cover_shadows']:
            shadow_pixmap = QtGui.QPixmap()
            shadow_pixmap.load(':/images/gray-shadow.png')
            shadow_pixmap = shadow_pixmap.scaled(160, 230, QtCore.Qt.IgnoreAspectRatio)
            shadow_x = option.rect.topLeft().x() + 10
            shadow_y = option.rect.topLeft().y() - 5
            painter.setOpacity(.7)
            painter.drawPixmap(shadow_x, shadow_y, shadow_pixmap)
            painter.setOpacity(1)

        if not file_exists:
            painter.setOpacity(.7)
            QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
            painter.setOpacity(1)
            read_icon = pie_chart.pixmapper(
                -1, None, self.parent.settings['consider_read_at'], 36)
            x_draw = option.rect.bottomRight().x() - 30
            y_draw = option.rect.bottomRight().y() - 35
            painter.drawPixmap(x_draw, y_draw, read_icon)
            return

        QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)

        if position_percent:
            read_icon = pie_chart.pixmapper(
                position_percent, self.temp_dir, self.parent.settings['consider_read_at'], 36)

            x_draw = option.rect.bottomRight().x() - 30
            y_draw = option.rect.bottomRight().y() - 35
            painter.drawPixmap(x_draw, y_draw, read_icon) 
Example 79
Project: phidl   Author: amccaugh   File: quickplotter.py    MIT License 4 votes vote down vote up
def __init__(self, gridsize_label, position_label, help_label):
        QGraphicsView.__init__(self)

        self.gridsize_label = gridsize_label
        self.position_label = position_label
        self.help_label = help_label

        # Create a QGraphicsScene which this view looks at
        self.scene = QGraphicsScene(self)
        self.scene.setSceneRect(QRectF())
        self.setScene(self.scene)

        # Customize QGraphicsView
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setInteractive(False)
        self.scale(1,-1) # Flips around the Y axis
         # Use OpenGL http://ralsina.me/stories/BBS53.html
#        self.setViewport(QtOpenGL.QGLWidget())
        self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.pen = QPen(QtCore.Qt.black, 0)
        self.portpen = QPen(PORT_COLOR, 3)
        self.portpen.setCosmetic(True) # Makes constant width
        self.portfont = QtGui.QFont('Arial', pointSize = 14)
        self.portfontcolor = PORT_COLOR
        self.subportpen = QPen(SUBPORT_COLOR, 3)
        self.subportpen.setCosmetic(True) # Makes constant width
        self.subportfont = QtGui.QFont('Arial', pointSize = 14)
        self.subportfontcolor = SUBPORT_COLOR

        # Tracking ports

        # Various status variables
        self._mousePressed = None
        self._rb_origin = QPoint()
        self.zoom_factor_total = 1

        # Grid variables
        self.gridpen = QPen(QtCore.Qt.black, 0)
        self.gridpen.setStyle(QtCore.Qt.DotLine)
        self.gridpen.setDashPattern([1,4])
        self.gridpen.setColor(QtGui.QColor(0, 0, 0, 125))
#        self.gridpen = QPen(QtCore.Qt.black, 1)
#        self.gridpen.setCosmetic(True) # Makes constant width
        self.scene_polys = []

        self.initialize() 
Example 80
Project: hexutil   Author: stephanh42   File: example.py    MIT License 4 votes vote down vote up
def paintEvent(self, event):
        # compute center of window
        size = self.size()
        xc = size.width()//2
        yc = size.height()//2
        # bounding box when we translate the origin to be at the center
        bbox = hexutil.Rectangle(-xc, -yc, size.width(), size.height())
        hexgrid = self.hexgrid
        painter = QtGui.QPainter()
        painter.begin(self)
        try:
            # paint background black
            painter.save()
            painter.setPen(QtCore.Qt.NoPen)
            painter.setBrush(QtGui.QColor())
            painter.drawRect(0, 0, size.width(), size.height())
            painter.restore()

            # set up drawing state
            painter.setPen(self.pen)
            painter.setRenderHint(QtGui.QPainter.Antialiasing)
            painter.setRenderHint(QtGui.QPainter.TextAntialiasing)
            painter.setFont(self.font)
            painter.translate(xc, yc)
            # draw each hexagon which is in the window
            for hexagon in hexgrid.hexes_in_rectangle(bbox):
                polygon = QtGui.QPolygon([QtCore.QPoint(*corner) for corner in hexgrid.corners(hexagon)])
                hexagon2 = hexagon + self.player
                tile = self.level.get_seen_tile(hexagon2)
                if tile == ' ':
                    continue
                painter.setBrush(self._tile_brushes[tile])
                painter.drawPolygon(polygon)
                if hexagon2 not in self.fov:
                    painter.setBrush(self.unseen_brush)
                    painter.drawPolygon(polygon)
                if hexagon2 in self.selected_path:
                    painter.setBrush(self.select_brush)
                    painter.drawPolygon(polygon)
                if hexagon2 == self.player:
                    rect = hexgrid.bounding_box(hexagon)
                    rect = QtCore.QRectF(*rect) # convert to Qt RectF
                    painter.drawText(rect, QtCore.Qt.AlignCenter, '@')
        finally:
            painter.end()