Beispiel #1
0
 def __init__(self):
     super().__init__()
     
     self.setGeometry(600, 200, 420, 320)
     self.setWindowTitle('Help')
     self.setWindowIcon(QIcon(ICON_PATH))
     
     label = QLabel('Press anything on your keyboard to see what it does.')
     self.actionLabel = QLabel('Press something!')
     self.img = QLabel('img', self)
     self.img.setPixmap(QPixmap(HELP_IMG_PATH))
     
     
     grid = QGridLayout()
     grid.setSpacing(4)
     
     grid.addWidget(self.img, 0, 0)
     grid.addWidget(label, 1, 0)
     grid.addWidget(self.actionLabel, 2, 0)
     
     myFont=QFont()
     myFont.setBold(True)
     myFont.setPixelSize(24)
     self.actionLabel.setFont(myFont)
     
     palette = QPalette()
     palette.setColor(QPalette.Foreground,Qt.green)
     self.actionLabel.setPalette(palette)
     
     self.setLayout(grid)
     self.show()
def Splash(self):
    app.processEvents()
    splash = QtWidgets.QSplashScreen(QtGui.QPixmap(":ico/23.png"))

    font = QFont()
    font.setPixelSize(72)
    font.setWeight(QFont.Bold)
    font.setFixedPitch(True)
    splash.setFont(font)

    #splash.setFont(font)
    #splash.showMessage(str(count[0]), QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom, QtCore.Qt.white )
    splash.show()
    for i in range(0, 6):
        time.sleep(1.5)
        splash = QtWidgets.QSplashScreen(QtGui.QPixmap(":ico/23.png"))

        if i <= 4.0:
            splash.showMessage(str(count[i]), QtCore.Qt.AlignHCenter | QtCore.Qt.AlignHCenter | QtCore.Qt.AlignHCenter| QtCore.Qt.WindowStaysOnTopHint, QtCore.Qt.darkRed)
            font = splash.font()
            font.setPixelSize(640)
            font.setWeight(QFont.Bold)
            splash.setFont(font)
            splash.show()
        else:
            QtWidgets.QApplication.processEvents()
        splash.show()
Beispiel #3
0
    def __init__(self, parent=None, command="/bin/bash", font_size=14):
        super().__init__(parent)

        self._columns = 80
        self._rows = 24
        self._char_width = [0] * (self._columns + 1)
        self._char_height = [0] * (self._rows + 1)

        self.setFocusPolicy(Qt.StrongFocus)
        self.setAutoFillBackground(False)
        self.setAttribute(Qt.WA_OpaquePaintEvent, True)
        self.setCursor(Qt.IBeamCursor)
        font_name = "Monospace"

        if sys.platform == 'darwin':
            font_name = "Courier"

        font = QFont(font_name)
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(font_size)
        self.setFont(font)
        self._session = None
        self._last_update = 0
        self._screen = []
        self._text = []
        self._cursor_rect = None
        self._cursor_col = 0
        self._cursor_row = 0
        self._dirty = False
        self._blink = False
        self._press_pos = None
        self._selection = None
        self._clipboard = QApplication.clipboard()
        self._pixmap = None
Beispiel #4
0
    def transform(self, value):
        if not value:
            return None
        style_map = {"normal": QFont.StyleNormal, "italic": QFont.StyleItalic, "oblique": QFont.StyleOblique}
        weight_map = {"normal": QFont.Normal, "bold": QFont.Bold}
        font = QFont()
        font.setStyle(QFont.StyleNormal)
        font.setWeight(QFont.Normal)

        match = self.font_regex.match(value)
        style = match.group("style")
        weight = match.group("weight")
        namedweight = match.group("namedweight")
        size = match.group("size")
        family = match.group("family")
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith("pt"):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith("px"):
                font.setPixelSize(int(size[:-2]))
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', "").replace("'", "")
        font.setFamily(family)
        return font
Beispiel #5
0
def _get_pos_widget(name, backgroundColor, foregroundColor):
    label = QLabel()
    label.setAttribute(Qt.WA_TransparentForMouseEvents, True)

    pixmap = QPixmap(25 * 10, 25 * 10)
    pixmap.fill(backgroundColor)
    painter = QPainter()
    painter.begin(pixmap)
    pen = QPen(foregroundColor)
    painter.setPen(pen)
    painter.setRenderHint(QPainter.Antialiasing)
    font = QFont()
    font.setBold(True)
    font.setPixelSize(25 * 10 - 30)
    path = QPainterPath()
    path.addText(QPointF(50, 25 * 10 - 50), font, name)
    brush = QBrush(foregroundColor)
    painter.setBrush(brush)
    painter.drawPath(path)
    painter.setFont(font)
    painter.end()
    pixmap = pixmap.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation)
    label.setPixmap(pixmap)

    spinbox = DelayedSpinBox(750)
    spinbox.setAlignment(Qt.AlignCenter)
    spinbox.setToolTip("{0} Spin Box".format(name))
    spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons)
    spinbox.setMaximumHeight(20)
    font = spinbox.font()
    font.setPixelSize(14)
    spinbox.setFont(font)
    sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name())
    spinbox.setStyleSheet(sheet)
    return label, spinbox
Beispiel #6
0
def setFontMetrics():
    """ Application must be running before you mess
    too much with Fonts in Qt5
    """
    global SEQUENCEFONT
    global SEQUENCEFONTMETRICS
    global SEQUENCEFONTCHARWIDTH
    global SEQUENCEFONTCHARHEIGHT
    global SEQUENCEFONTEXTRAWIDTH
    global SEQUENCETEXTXCENTERINGOFFSET
    global SEQUENCETEXTYCENTERINGOFFSET
    SEQUENCEFONT = QFont("Monaco")
    if hasattr(QFont, 'Monospace'):
        SEQUENCEFONT.setStyleHint(QFont.Monospace)
    SEQUENCEFONT.setFixedPitch(True)
    SEQUENCEFONTH = int(PATH_BASE_WIDTH / 3.)
    SEQUENCEFONT.setPixelSize(SEQUENCEFONTH)
    SEQUENCEFONTMETRICS = QFontMetricsF(SEQUENCEFONT)
    SEQUENCEFONTCHARWIDTH = SEQUENCEFONTMETRICS.width("A")
    SEQUENCEFONTCHARHEIGHT = SEQUENCEFONTMETRICS.height()
    SEQUENCEFONTEXTRAWIDTH = PATH_BASE_WIDTH - SEQUENCEFONTCHARWIDTH
    SEQUENCEFONT.setLetterSpacing(QFont.AbsoluteSpacing,
                                 SEQUENCEFONTEXTRAWIDTH)
    SEQUENCETEXTXCENTERINGOFFSET = SEQUENCEFONTEXTRAWIDTH / 4.
    SEQUENCETEXTYCENTERINGOFFSET = PATH_BASE_WIDTH * 0.6
Beispiel #7
0
    def draw_markings(self, painter):
        painter.save()
        painter.translate(self.width()/2, self.height()/2)
        scale = min((self.width() - self._margins)/120.0, (self.height() - self._margins)/120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(12)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(self.palette().color(QPalette.WindowText))

        i = 0
        while i < 360:
            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(-metrics.width(self._point_text[i])/2.0, -52, self._point_text[i])
            else:
                painter.drawLine(0, -45, 0, -50)

            painter.rotate(15)
            i += 15

        painter.restore()
Beispiel #8
0
 def __init__(self, parent=None, command="/bin/bash",
              font_name="Monospace", font_size=18):
     super(TerminalWidget, self).__init__(parent)
     self.parent().setTabOrder(self, self)
     self.setFocusPolicy(Qt.WheelFocus)
     self.setAutoFillBackground(False)
     self.setAttribute(Qt.WA_OpaquePaintEvent, True)
     self.setCursor(Qt.IBeamCursor)
     font = QFont(font_name)
     font.setPixelSize(font_size)
     self.setFont(font)
     self._session = None
     self._last_update = None
     self._screen = []
     self._text = []
     self._cursor_rect = None
     self._cursor_col = 0
     self._cursor_row = 0
     self._dirty = False
     self._blink = False
     self._press_pos = None
     self._selection = None
     self._clipboard = QApplication.clipboard()
     QApplication.instance().lastWindowClosed.connect(Session.close_all)
     if command:
         self.execute()
Beispiel #9
0
    def set_style(self, style):
        super().set_style(style)

        font = QFont(style.font)
        font.setPixelSize(48)
        self.header.setBrush(style.midcolor)
        self.header.setFont(font)

        font = QFont(style.font)
        font.setPixelSize(32)

        self.header_line.setPen(style.foreground_color)

        self.cursor.setBrush(style.midcolor)
        self.cursor.setPen(QPen(Qt.NoPen))

        for widget in self.weekdays:
            widget.setFont(font)
            widget.setBrush(style.foreground_color)

        for widget in self.days:
            widget.setFont(font)
            widget.setBrush(self.style.foreground_color)

        self.layout()
Beispiel #10
0
    def buttonFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        font.setPixelSize(11)
        font.setFamily('Verdana')

        return font
Beispiel #11
0
    def seed_img(self, is_seed = True):

        if is_seed:
            try:
                cseed = self.get_seed()
            except UserCancelled:
                return
            except InvalidPassword as e:
                self.d.show_error(str(e))
                return
            if not cseed:
                self.d.show_message(_("This wallet has no seed"))
                return
            txt = cseed.upper()
        else:
            txt = self.txt.upper()

        img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
        bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
        bitmap.fill(Qt.white)
        painter = QPainter()
        painter.begin(bitmap)
        QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf') )
        if len(txt) < 102 :
            fontsize = 15
            linespace = 15
            max_letters = 17
            max_lines = 6
            max_words = 3
        else:
            fontsize = 12
            linespace = 10
            max_letters = 21
            max_lines = 9
            max_words = int(max_letters/4)

        font = QFont('Source Sans Pro', fontsize, QFont.Bold)
        font.setLetterSpacing(QFont.PercentageSpacing, 100)
        font.setPixelSize(fontsize)
        painter.setFont(font)
        seed_array = txt.split(' ')

        for n in range(max_lines):
            nwords = max_words
            temp_seed = seed_array[:nwords]
            while len(' '.join(map(str, temp_seed))) > max_letters:
               nwords = nwords - 1
               temp_seed = seed_array[:nwords]
            painter.drawText(QRect(0, linespace*n , self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
            del seed_array[:nwords]

        painter.end()
        img = bitmap.toImage()
        if (self.rawnoise == False):
            self.make_rawnoise()

        self.make_cypherseed(img, self.rawnoise, False, is_seed)
        return img
Beispiel #12
0
    def headingFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        font.setPixelSize(23)
        font.setBold(True)
        font.setFamily('Verdana')

        return font;
Beispiel #13
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        style_map = {
            'normal': QFont.StyleNormal,
            'italic': QFont.StyleItalic,
            'oblique': QFont.StyleOblique,
        }
        weight_map = {
            'normal': QFont.Normal,
            'bold': QFont.Bold,
        }
        font = QFont()
        font.setStyle(QFont.StyleNormal)
        font.setWeight(QFont.Normal)

        match = self.font_regex.match(value)
        if not match:  # pragma: no cover
            # This should never happen, as the regex always matches everything
            # as family.
            raise configexc.ValidationError(value, "must be a valid font")

        style = match.group('style')
        weight = match.group('weight')
        namedweight = match.group('namedweight')
        size = match.group('size')
        family = match.group('family')
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith('pt'):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith('px'):
                font.setPixelSize(int(size[:-2]))
            else:
                # This should never happen as the regex only lets pt/px
                # through.
                raise ValueError("Unexpected size unit in {!r}!".format(
                    size))  # pragma: no cover
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', '').replace("'", '')
        if family == 'monospace':
            family = self.monospace_fonts
        font.setFamily(family)
        return font
Beispiel #14
0
    def createUnlinkedBar(self):
        pushed_bin = 0
        slipping_bin = 0
        others = 0
        try:
            total_bins = self.total_bins
            scanner_linked_rfid = self.scanner_linked_rfid
            unlinked_bins = total_bins - scanner_linked_rfid
            slipping_bin = len(self.slipping.index)
            pushed_bin = len(self.pushed.index)
            others = unlinked_bins-pushed_bin-slipping_bin

        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        series = QPieSeries()
        series.setHoleSize(0.35)
        series.append("Pushed", pushed_bin)
        series.append("Slipping", slipping_bin)
        series.append("Others", others)
        slices = series.slices()[0]
        slices.setLabelVisible()
        slices.setLabel("{0} {1:.2f}".format("Pushed", 100*slices.percentage()))

        slices1 = series.slices()[1]
        slices1.setLabelVisible()
        slices1.setLabel("{0} {1:.2f}".format("Slipping", 100*slices1.percentage()))

        # set exploded slice
        if pushed_bin > slipping_bin:
            slices.setExploded()
        else:
            slices1.setExploded()

        slices2 = series.slices()[2]
        slices2.setLabelVisible()
        slices2.setLabel("{0} {1:.2f}".format("Others", 100*slices2.percentage()))

        chart = QChart()
        chart.setTheme(QChart.ChartThemeBlueCerulean)
        chart.legend().hide()
        font = QFont()
        font.setPixelSize(16)

        chart.setTitleFont(font)
        chart.setTitle("Unlinked Details")        
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        return chartView
Beispiel #15
0
    def contentFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        if sys.platform == "darwin":
            font.setPixelSize(14)
            font.setFamily("Arial")
        else:
            font.setPixelSize(13)
            font.setFamily("Verdana")

        return font
	def __init__(self):
		self.recreatePath = True
		self.path = None
		self.timer = QTimer()
		self.timer.timeout.connect(self.timeout)
		super().__init__()
		self.setFrameStyle(QFrame.Panel | QFrame.Sunken)
		self.setCursor(Qt.CrossCursor)

		font = QFont(self.font())
		font.setPixelSize(self.width()*0.25)
		self.path = QPainterPath()
Beispiel #17
0
    def setupFileList(self):
        self.listWidget = QListWidget(self)

        font = QFont(self.sidebar_font_type)
        font.setPixelSize(self.sidebar_font_pixel_size)
        font.setFixedPitch(True)
        self.listWidget.setFont(font)
        self.listWidget.move(0, 0)
        self.listWidget.resize(self.listWidth, self.editorHeight)
        self.listWidget.addItems(
            self.experiment.getCurrentExperimentalSystemFilenames())
        self.listWidget.currentItemChanged.connect(self.onCurrentItemChanged)
Beispiel #18
0
    def contentFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        if sys.platform == 'darwin':
            font.setPixelSize(14)
            font.setFamily('Arial')
        else:
            font.setPixelSize(13)
            font.setFamily('Verdana')

        return font
Beispiel #19
0
    def beforeDelayDistribution(self):
        min_num, max_num = 0, 100
        max_count = 0
        total_stopped_time = []
        try:
            total_stopped_time = self.tm.total_stopped_time
            max_num = max(total_stopped_time)
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = total_stopped_time
        # count = [0] * (int(max_num) + 1)        # choose the largest num as length of count

        # for num in total_stopped_time:
        #     count[int(num)] += 1            # update every number's count

        max_count = max(count)
        setBar = QBarSet('stop time')
        setBar.append(count)
        brush = QBrush(QColor(0x57B1FD))
        pen = QPen(QColor(0x57B1FD))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        series = QBarSeries()
        series.append(setBar)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Stop time Distribution (before)')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        axisX = QValueAxis()
        axisX.setRange(min_num, max_num + 20)
        chart.setAxisX(axisX, series)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 20)
        chart.setAxisY(axisY, series)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView
Beispiel #20
0
    def __init__(self, title, center=False):
        super().__init__(title)

        font = QFont(self.font())
        font.setBold(True)
        font.setPixelSize(15)
        self.setFont(font)

        # if center:
        #	self.setAlignment(Qt.AlignCenter)

        self.setMaximumHeight(22)
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
     painter.setBrush(QBrush(Qt.white))
     self.draw_field(painter)
     font = QFont()
     font.setPixelSize(14)
     painter.setFont(font)
     self.draw_subformation(painter)
     font.setPixelSize(24)
     painter.setFont(font)
     self.draw_defense(painter)
Beispiel #22
0
    def createSummaryBar(self):
        # self.dp.dfinal

        series = QPieSeries()
        labelfont = QFont()
        labelfont.setPixelSize(11)
        try:
            series.append("Linked", len(self.linked.index))
            series.append("Unlinked", len(self.unlinked.index))
            # slices = QPieSlice()
            slices1 = series.slices()[1]
            slices1.setExploded()
            slices1.setLabelVisible()
            slices1.setPen(QPen(QColor(0x57B1FD), 2))
            slices1.setBrush(QBrush(QColor(0xfdb157)))
            slices1.setLabelPosition(QPieSlice.LabelOutside)
            slices1.setLabel(
                ("{0} {1:.2f}%").format("Unlinked",
                                        100 * slices1.percentage()))
            slices1.setLabelFont(labelfont)

            # slices.setPen(QPen(Qt.darkGreen, 2))
            # slices.setBrush(QBrush(QColor(0xfdb157)))
        except AttributeError:
            self.statusbar.showMessage('Data not ready')
            series.append("Total", 1)

        slices = series.slices()[0]

        slices.setBrush(QBrush(QColor(0x57B1FD)))
        # slices.setLabel(("%1%").format(100*slices.percentage(), 0, 'f', 1))
        # slices.setLabelPosition(QPieSlice.LabelInsideHorizontal)
        if len(series.slices()
               ) == 2:  # display "linked" label only at data was processed
            slices.setLabelVisible()
            slices.setLabel(("{0} {1:.2f}%").format("Linked",
                                                    100 * slices.percentage()))
            slices.setLabelFont(labelfont)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("Total")
        chart.legend().hide()

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        return chartView
Beispiel #23
0
 def data(self, index, role):
     if index.isValid() or (0 <= index.row() < len(self.listItemData)):
         if role == Qt.DisplayRole:
             return QVariant(self.listItemData[index.row()])
         elif role == Qt.TextAlignmentRole:
             return QVariant(int(Qt.AlignLeft | Qt.AlignVCenter))
         elif role == Qt.FontRole:
             font = QFont()
             font.setPixelSize(20)
             return QVariant(font)
     else:
         return QVariant()
Beispiel #24
0
    def contentFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        if sys.platform == 'darwin':
            font.setPixelSize(14)
            font.setFamily('Arial')
        else:
            font.setPixelSize(13)
            font.setFamily('Verdana')

        return font
Beispiel #25
0
    def CreateItems(self):
        self.lblPort = QLabel('串  口')
        self.lblBaud = QLabel('波特率')
        self.lblParity = QLabel('校验位')
        self.lblWordLen = QLabel('数据位')
        self.lblStopBits = QLabel('停止位')

        self.cmbPort = QComboBox()
        self.cmbBaud = QComboBox()
        self.cmbParity = QComboBox()
        self.cmbWordLen = QComboBox()
        self.cmbStopBits = QComboBox()

        self.btnOpenPort = QPushButton('打开串口')
        self.btnClosePort = QPushButton('关闭串口')
        # self.btnOpenPort.setFont(QFont('Arial', 15))
        self.btnOpenPort.setFixedHeight(35)
        self.btnClosePort.setFixedHeight(35)
        font = QFont()
        font.setPixelSize(15)
        self.btnOpenPort.setFont(font)
        self.btnClosePort.setFont(font)

        self.chcHexRecv = QCheckBox('十六进制接收')
        self.chcWrap = QCheckBox('自动换行')
        self.chcAutoClear = QCheckBox('自动清空')
        self.chcAutoSave = QCheckBox('自动保存')

        self.btnClear = QPushButton('清空')

        self.lblAddr = QLabel('地址:')
        self.txtAddr = QLineEdit()
        self.btnSaveAs = QPushButton('选择...')

        self.chcHexSend = QCheckBox('十六进制发送')
        self.chcAutoSend = QCheckBox('自动发送')
        self.txtAutoSend = QLineEdit()
        self.lblAutoSend = QLabel('秒')
        intValidAutoSend = QIntValidator(0, 999, self)
        self.txtAutoSend.setValidator(intValidAutoSend)

        self.txtRecv = QPlainTextEdit()
        # self.txtRecv.verticalScrollBar().setValue(self.txtRecv.verticalScrollBar().maximum())
        self.vscrlRecv = self.txtRecv.verticalScrollBar()
        # print(vscrlRecv.maximum())

        self.txtSend = QPlainTextEdit()
        self.btnSend = QPushButton('发送')
        self.txtSend.setFixedHeight(100)
        self.btnSend.setFixedHeight(35)

        self.tmrSend = QTimer()
Beispiel #26
0
    def drawGraph(self, qp):
        qp.setPen(Qt.black)
        qp.setBrush(Qt.black)

        for i, node in enumerate(self.nodes):

            qpoint = QPoint(node.x, node.y)

            if i == self.selected_node_idx:
                qp.setBrush(Qt.red)
            elif i in self.drag_idx:
                qp.setBrush(Qt.blue)

            qp.drawEllipse(qpoint, self.pt_radius*2, self.pt_radius*2)

            qp.setBrush(Qt.black)
                
        for _, edges in self.edges.items():
            for edge in edges:
                dx = edge.v2.x - edge.v1.x
                dy = edge.v2.y - edge.v1.y
                weight = str(int(abs(edge)))
                qp.drawLine(edge.v1.x, edge.v1.y, edge.v2.x, edge.v2.y)
                font = QFont("Helvetica")
                font.setPixelSize(13.5)
                qp.setFont(font)
                qp.drawText(dx/2 + edge.v1.x, dy/2 + edge.v1.y, weight)
                if edge.direction:
                    qp.setPen(Qt.green)
                    tip = self.__calculateTip(edge)
                    coef = self.arrow_size_coef
                    qp.drawPolygon(QPoint(edge.v2.x, edge.v2.y),
                                       QPoint(edge.v2.x + coef*tip[0][0], edge.v2.y + coef*tip[0][1]),
                                       QPoint(edge.v2.x + coef*tip[1][0], edge.v2.y + coef*tip[1][1]))
                    qp.setPen(Qt.black)

        if self.path_edges:
            path_nodes = []
            for _ in self.path_edges:
                for node in self.nodes:
                    if _ == id(node):
                        path_nodes.append(node)
                
            for i in range(len(path_nodes)):
                if i == len(path_nodes)-1:
                    break
                qPen = QPen()
                qPen.setColor(Qt.yellow)
                qPen.setWidth(2)
                qp.setPen(qPen)
                qp.drawLine(path_nodes[i].x, path_nodes[i].y, path_nodes[i+1].x, path_nodes[i+1].y)
                qp.setPen(Qt.black)
Beispiel #27
0
    def init_data(self):
        self.navigation.setIconSize(QSize(18, 18))
        font = QFont()
        font.setPixelSize(13)
        local_item = QListWidgetItem(self.navigation)
        local_item.setData(Qt.UserRole,
                           self.music_list_service.get_local_music())
        local_item.setIcon(QIcon("./resource/image/歌单0.png"))
        local_item.setText("本地音乐")
        local_item.setFont(font)

        self.navigation.addItem(local_item)

        # item1 = QListWidgetItem()
        # item1.setText("创建的歌单")
        # item1.setFlags(Qt.NoItemFlags)
        # self.navigation.addItem(item1)

        music_list_icon = QIcon("./resource/image/歌单1.png")

        item = QListWidgetItem()
        item.setIcon(music_list_icon)
        item.setFont(font)
        item.setText('菜单1')
        item.setData(Qt.UserRole, 1)
        self.navigation.addItem(item)

        item = QListWidgetItem()
        item.setIcon(music_list_icon)
        item.setFont(font)
        item.setText('菜单2')
        item.setData(Qt.UserRole, 2)
        self.navigation.addItem(item)

        # mls = list(filter(lambda ml: ml.id != MusicList.DEFAULT_ID, self.music_list_service.list_(MusicList())))
        # music_list_icon = QIcon("./resource/image/歌单1.png")
        # for music_list in mls:
        #     item = QListWidgetItem()
        #     item.setIcon(music_list_icon)
        #     item.setFont(font)
        #     item.setText(music_list.name)
        #     item.setData(Qt.UserRole, music_list)
        #     self.navigation.addItem(item)

        # 启动时默认选中第一个歌单
        self.navigation.setCurrentRow(0)
        cur_id = self.navigation.currentItem().data(Qt.UserRole).id

        self.update_music_list(cur_id)

        self.stacked_view.setCurrentWidget(self.music_list_detail)
        self.musics_table.setColumnCount(5)
Beispiel #28
0
    def setupEditor(self):
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)

        font.setPixelSize(self.font_pixel_size)

        if self.use_leading_space:
            line_height = QFontMetrics(font).lineSpacing()
        else:
            line_height = QFontMetrics(font).height()
        self.editorHeight = (self.height_in_characters * line_height) + 2 + \
                             self.margin_pixel_size + \
                             self.padding_top + \
                             self.padding_bottom

        # Selecting the tracker device
        self.editor = None
        csv_filename = self.experiment.participant_id + "_" + self.experiment.current_system_id
        if self.tracking_device == "eye tracker":
            if self.draw_gaze:
                self.editor = EyeTrackerDrawGazeTextEdit(csv_filename, self)
            else:
                self.editor = EyeTrackerTextEdit(csv_filename, self)
            self.et.plugg(self.editor)
        elif self.tracking_device == "mouse":
            self.editor = MouseTrackerTextEdit(csv_filename, self)
        else:
            raise Exception(
                "You should especify your tracker device: 'eye tracker' or 'mouse'."
            )

        self.editor.current_task_id = self.experiment.current_task_id
        self.editor.setFont(font)
        self.editor.move(self.listWidth, 0)
        self.editor.resize(self.editorWidth, self.editorHeight)
        self.editor.setStyleSheet(
            "QTextEdit {padding-left: %s; padding-top: %s; padding-bottom: %s; padding-right: %s}"
            % (self.padding_left, self.padding_top, self.padding_bottom,
               self.padding_right))
        self.editor.document().setDocumentMargin(self.margin_pixel_size)
        self.editor.setReadOnly(True)
        if self.hide_scroll_bar:
            self.editor.verticalScrollBar().setStyleSheet(
                "QScrollBar:vertical {width: 0px;}")

        self.highlighter = Highlighter(self.keywords,
                                       self.keywords_paradigm_bold,
                                       self.keywords_paradigm_italic,
                                       self.editor.document())

        self.reportCodeViewerProperties(font)
Beispiel #29
0
    def font(self, prefix, size):
        """Returns QFont corresponding to the given prefix and size

        Arguments
        ---------
        prefix: str
            prefix string of the loaded font
        size: int
            size for the font
        """
        font = QFont(self.fontname[prefix])
        font.setPixelSize(size)
        return font
Beispiel #30
0
    def font(self, prefix, size):
        """Returns QFont corresponding to the given prefix and size

        Arguments
        ---------
        prefix: str
            prefix string of the loaded font
        size: int
            size for the font
        """
        font = QFont(self.fontname[prefix])
        font.setPixelSize(size)
        return font
Beispiel #31
0
def font_from_dict(font_dict, font=None):
    if font is None:
        font = QFont()
    else:
        font = QFont(font)

    if "family" in font_dict:
        font.setFamily(font_dict["family"])

    if "size" in font_dict:
        font.setPixelSize(font_dict["size"])

    return font
Beispiel #32
0
    def widgets(self):
        font = QFont("Times New Roman")
        font.setPixelSize(20)

        self.start = QPushButton("Start", self)
        self.start.setFont(font)
        self.start.setGeometry(100, 100, 100, 50)
        self.start.clicked.connect(self.doAnimation_1)

        self.frame = QFrame(self)
        self.frame.setStyleSheet("background-color:darkGreen;")
        self.frame.setFrameStyle(QFrame.Panel | QFrame.Raised)
        self.frame.setGeometry(250, 100, 100, 100)
Beispiel #33
0
    def paintEvent(self, event):
        p1 = 10
        p2 = 20
        if self.single_line:
            self.lyric.setGeometry(p1, p2,
                                   self.width() - 2 * p1,
                                   self.height() - p1 - p2)
            self.lyric.setAlignment(Qt.AlignCenter)
            self.lyric2.hide()
        else:
            w = self.width() - 2 * p1
            h = (self.height() - p1 - p2) / 2
            self.lyric.setGeometry(p1, p2, w, h)
            self.lyric.setAlignment(Qt.AlignLeft)
            self.lyric2.setGeometry(p1, p2 + h, w, h)
            self.lyric2.setAlignment(Qt.AlignRight)
            self.lyric2.show()
        font = QFont()
        font.setPixelSize(self.lyric.height() * 0.8)
        self.lyric.setFont(font)
        self.lyric2.setFont(font)

        if not self.lock:
            if self.enter:
                self.setCursor(Qt.OpenHandCursor)
                painter = QPainter(self)
                path = QPainterPath()
                rect = QRectF(0, 0, self.width(), self.height())
                path.addRoundedRect(rect, 10, 10)
                painter.fillPath(path, QColor(0, 0, 0, 55))
                pen = QPen()
                pen.setWidth(2)
                pen.setColor(QColor(255, 255, 255, 180))
                painter.setPen(pen)
                painter.drawRoundedRect(self.rect(), 10, 10)
                painter.drawRoundedRect(3, 3,
                                        self.width() - 6,
                                        self.height() - 6, 8, 8)

        sgw = self.size_grip.width()
        sgh = self.size_grip.height()
        sw = self.width()
        sh = self.height()
        self.size_grip.setGeometry(sw - sgw - 6, sh - sgh - 6, sgw, sgh)

        Configuration.config['ui']['lyric']['x'] = self.pos().x()
        Configuration.config['ui']['lyric']['y'] = self.pos().y()
        Configuration.config['ui']['lyric']['w'] = self.width()
        Configuration.config['ui']['lyric']['h'] = self.height()
        Configuration.config['ui']['lyric']['single'] = self.single_line
        Configuration.save_config()
Beispiel #34
0
    def setupShapes(self):
        truck = QPainterPath()
        truck.setFillRule(Qt.WindingFill)
        truck.moveTo(0.0, 87.0)
        truck.lineTo(0.0, 60.0)
        truck.lineTo(10.0, 60.0)
        truck.lineTo(35.0, 35.0)
        truck.lineTo(100.0, 35.0)
        truck.lineTo(100.0, 87.0)
        truck.lineTo(0.0, 87.0)
        truck.moveTo(17.0, 60.0)
        truck.lineTo(55.0, 60.0)
        truck.lineTo(55.0, 40.0)
        truck.lineTo(37.0, 40.0)
        truck.lineTo(17.0, 60.0)
        truck.addEllipse(17.0, 75.0, 25.0, 25.0)
        truck.addEllipse(63.0, 75.0, 25.0, 25.0)

        clock = QPainterPath()
        clock.addEllipse(-50.0, -50.0, 100.0, 100.0)
        clock.addEllipse(-48.0, -48.0, 96.0, 96.0)
        clock.moveTo(0.0, 0.0)
        clock.lineTo(-2.0, -2.0)
        clock.lineTo(0.0, -42.0)
        clock.lineTo(2.0, -2.0)
        clock.lineTo(0.0, 0.0)
        clock.moveTo(0.0, 0.0)
        clock.lineTo(2.732, -0.732)
        clock.lineTo(24.495, 14.142)
        clock.lineTo(0.732, 2.732)
        clock.lineTo(0.0, 0.0)

        house = QPainterPath()
        house.moveTo(-45.0, -20.0)
        house.lineTo(0.0, -45.0)
        house.lineTo(45.0, -20.0)
        house.lineTo(45.0, 45.0)
        house.lineTo(-45.0, 45.0)
        house.lineTo(-45.0, -20.0)
        house.addRect(15.0, 5.0, 20.0, 35.0)
        house.addRect(-35.0, -15.0, 25.0, 25.0)

        text = QPainterPath()
        font = QFont()
        font.setPixelSize(50)
        fontBoundingRect = QFontMetrics(font).boundingRect("Qt")
        text.addText(-QPointF(fontBoundingRect.center()), font, "Qt")

        self.shapes = (clock, house, text, truck)

        self.shapeComboBox.activated.connect(self.shapeSelected)
    def paintEvent(self, event):
        """绘制按钮"""
        super(SwitchButton, self).paintEvent(event)
        # 创建绘制器并设置抗锯齿和图片流畅转换
        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing
                               | QPainter.SmoothPixmapTransform)
        # 定义字体样式
        font = QFont('Microsoft YaHei')
        font.setPixelSize(14)
        painter.setFont(font)

        # 开关为开的状态
        if self.state:
            # 绘制背景
            painter.setPen(Qt.Qt.NoPen)
            brush = QBrush(QColor('#3A5FCD'))
            painter.setBrush(brush)
            painter.drawRoundedRect(0, 0, self.width(), self.height(),
                                    self.height() // 2,
                                    self.height() // 2)

            # 绘制圆圈
            painter.setPen(Qt.Qt.NoPen)
            brush.setColor(QColor('#ffffff'))
            painter.setBrush(brush)
            painter.drawRoundedRect(43, 3, 24, 24, 12, 12)

            # 绘制文本
            painter.setPen(QPen(QColor('#ffffff')))
            painter.setBrush(Qt.Qt.NoBrush)
            painter.drawText(QRect(18, 4, 50, 20), Qt.Qt.AlignLeft, '开')
        # 开关为关的状态
        else:
            # 绘制背景
            painter.setPen(Qt.Qt.NoPen)
            brush = QBrush(QColor('#FFFFFF'))
            painter.setBrush(brush)
            painter.drawRoundedRect(0, 0, self.width(), self.height(),
                                    self.height() // 2,
                                    self.height() // 2)

            # 绘制圆圈
            pen = QPen(QColor('#999999'))
            pen.setWidth(1)
            painter.setPen(pen)
            painter.drawRoundedRect(3, 3, 24, 24, 12, 12)

            # 绘制文本
            painter.setBrush(Qt.Qt.NoBrush)
            painter.drawText(QRect(38, 4, 50, 20), Qt.Qt.AlignLeft, '关')
Beispiel #36
0
    def setupShapes(self):
        truck = QPainterPath()
        truck.setFillRule(Qt.WindingFill)
        truck.moveTo(0.0, 87.0)
        truck.lineTo(0.0, 60.0)
        truck.lineTo(10.0, 60.0)
        truck.lineTo(35.0, 35.0)
        truck.lineTo(100.0, 35.0)
        truck.lineTo(100.0, 87.0)
        truck.lineTo(0.0, 87.0)
        truck.moveTo(17.0, 60.0)
        truck.lineTo(55.0, 60.0)
        truck.lineTo(55.0, 40.0)
        truck.lineTo(37.0, 40.0)
        truck.lineTo(17.0, 60.0)
        truck.addEllipse(17.0, 75.0, 25.0, 25.0)
        truck.addEllipse(63.0, 75.0, 25.0, 25.0)

        clock = QPainterPath()
        clock.addEllipse(-50.0, -50.0, 100.0, 100.0)
        clock.addEllipse(-48.0, -48.0, 96.0, 96.0)
        clock.moveTo(0.0, 0.0)
        clock.lineTo(-2.0, -2.0)
        clock.lineTo(0.0, -42.0)
        clock.lineTo(2.0, -2.0)
        clock.lineTo(0.0, 0.0)
        clock.moveTo(0.0, 0.0)
        clock.lineTo(2.732, -0.732)
        clock.lineTo(24.495, 14.142)
        clock.lineTo(0.732, 2.732)
        clock.lineTo(0.0, 0.0)

        house = QPainterPath()
        house.moveTo(-45.0, -20.0)
        house.lineTo(0.0, -45.0)
        house.lineTo(45.0, -20.0)
        house.lineTo(45.0, 45.0)
        house.lineTo(-45.0, 45.0)
        house.lineTo(-45.0, -20.0)
        house.addRect(15.0, 5.0, 20.0, 35.0)
        house.addRect(-35.0, -15.0, 25.0, 25.0)

        text = QPainterPath()
        font = QFont()
        font.setPixelSize(50)
        fontBoundingRect = QFontMetrics(font).boundingRect("Qt")
        text.addText(-QPointF(fontBoundingRect.center()), font, "Qt")

        self.shapes = (clock, house, text, truck)

        self.shapeComboBox.activated.connect(self.shapeSelected)
Beispiel #37
0
 def __init__(self, txt, fontsize=10, legal=True):
     super().__init__()
     if legal:
         self.setDefaultTextColor(Qt.blue)
     else:
         self.setDefaultTextColor(Qt.lightGray)
     self.setPlainText(txt)
     font = QFont("Helvetica")
     font.setPixelSize(fontsize)
     self.setFont(font)
     self.setFlag(QGraphicsItem.ItemIsMovable)
     self.setTextInteractionFlags(Qt.NoTextInteraction)
     # If displaying png-rendered-latex, store the original text here
     self._tex_src_cache = None
Beispiel #38
0
    def paint(self, painter, option, widget):
        painter.setPen(QPen(Qt.black, 2))
        painter.setBrush(QColor(245, 245, 255, 220))
        painter.setClipRect(self.boundingRect())
        painter.drawRoundedRect(3, -100 + 3, 400 - 6, 250 - 6, 25.0, 25.0)

        textRect = self.boundingRect().adjusted(10, 10, -10, -10)
        flags = int(Qt.AlignTop | Qt.AlignLeft) | Qt.TextWordWrap

        font = QFont()
        font.setPixelSize(18)
        painter.setPen(Qt.black)
        painter.setFont(font)
        painter.drawText(textRect, flags, self.text)
    def tickerFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        if sys.platform == 'darwin':
            font.setPixelSize(11)
            font.setBold(True)
            font.setFamily('Arial')
        else:
            font.setPixelSize(10)
            font.setBold(True)
            font.setFamily('sans serif')

        return font
Beispiel #40
0
    def draw_text(self, painter, x, y, width, height, text):
        # painter.drawText(QRect(x * width, y * height, width, height), Qt.AlignCenter or Qt.TextWordWrap, text)

        # large size font
        if len(text) <= 10 :
            painter.drawText(QRect(x * width + int(width / 2 - height / 2 + 20), y * height + 40,
                                   height - 40, height - 80), Qt.AlignCenter or Qt.TextWordWrap, text)

        # medium size font
        elif len(text) > 10 and len(text) < 15:
            font = QFont ()
            font.setPixelSize(40)
            painter.setFont(font)

            painter.drawText(QRect(x * width + int(width / 2 - height / 2 + 20 ), y * height+40,
                                   height-40, height-80), Qt.AlignCenter, text)
            font.setPixelSize(50)
            painter.setFont(font)

        # small size font
        else:
            font = QFont()
            font.setPixelSize(30)
            painter.setFont(font)

            painter.drawText(QRect(x * width + int(width / 2 - height / 2 + 20), y * height + 40,
                                   height - 40, height - 80), Qt.AlignCenter or Qt.TextWordWrap, text)
            font.setPixelSize(50)
            painter.setFont(font)
Beispiel #41
0
    def tickerFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

        if sys.platform == 'darwin':
            font.setPixelSize(11)
            font.setBold(True)
            font.setFamily('Arial')
        else:
            font.setPixelSize(10)
            font.setBold(True)
            font.setFamily('sans serif')

        return font
    def getFont_Ion(self) -> QFont:
        """
        Initializes the font character for the ion(s).

        Returns
        -------
        QFont
            The font is Courier and of size 10

        """
        font = QFont("Courier")
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(10)
        return font
Beispiel #43
0
 def paintEvent(self, e):
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(QPen())
     brush = QBrush(QColor.fromRgb(0xFF, 0xFF, 0xCC))
     painter.setBrush(brush)
     painter.drawRect(QRect(0, 0, e.rect().width(), e.rect().height()))
     font = QFont()
     font.setFamily("Courier")
     font.setBold(True)
     font.setPixelSize(20)
     painter.setFont(font)
     painter.setPen(QPen(Qt.black))
     painter.drawText(e.rect(), Qt.AlignCenter, self.text)
Beispiel #44
0
    def __init__(self, enter_edit_taste_func, name_coffee, id=None, old_taste=None):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle(name_coffee)
        self.name_label.setText(name_coffee)
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        self.buttonBox.clicked.connect(self.click_btn_box)
        self.enter_edit_taste_func = enter_edit_taste_func
        self.id = id

        font = QFont()
        font.setPixelSize(16)
        self.plainTextEdit.setFont(font)
        self.plainTextEdit.setPlainText(old_taste)
 def __init__(self):
     super(HistoryChart, self).__init__()
     self.pen = QColor(Qt.black)
     self.categories = ["'" + str(i) for i in range(82, 90)]
     font = QFont()
     font.setPixelSize(10)
     self.axisX = QBarCategoryAxis()
     self.axisX.setLabelsFont(font)
     self.axisX.append(self.categories)
     self.addAxis(self.axisX, Qt.AlignBottom)
     self.legend().setVisible(False)
     self.layout().setContentsMargins(0, 0, 0, 0)
     self.setMargins(QMargins(5, 5, 5, 5))
     self.setBackgroundRoundness(0)
Beispiel #46
0
    def paint(self, painter, option, widget):
        painter.setPen(QPen(Qt.black, 2))
        painter.setBrush(QColor(245, 245, 255, 220))
        painter.setClipRect(self.boundingRect())
        painter.drawRoundedRect(3, -100 + 3, 400 - 6, 250 - 6, 25.0, 25.0)

        textRect = self.boundingRect().adjusted(10, 10, -10, -10)
        flags = int(Qt.AlignTop | Qt.AlignLeft) | Qt.TextWordWrap

        font = QFont()
        font.setPixelSize(18)
        painter.setPen(Qt.black)
        painter.setFont(font)
        painter.drawText(textRect, flags, self.text)
Beispiel #47
0
 def initUI(self):
     # init
     self.setSelectionMode(QAbstractItemView.SingleSelection)
     self.setDragEnabled(True)
     self.setStyleSheet(
         "QTreeWidget::item:hover{color: lightgrey; background-color: rgb(60,150,225)}"
         "QTreeWidget::item:selected{color: lightgrey; background-color:rgb(80,130,255)}"
         "QTreeWidget{color: lightgrey; background-color: rgb(30, 30, 30)}")
     self.headerItem().setText(0, "模块")
     self.header().setVisible(False)
     font = QFont()
     font.setFamily('文泉驿微米黑')
     font.setPixelSize(24)
     self.setFont(font)
Beispiel #48
0
    def getSvg(self):
        font = QFont(self.font.family())
        font.setBold(self.font.bold())
        font.setItalic(self.font.italic())
        font.setPixelSize(self.font.pointSize() * 1.25)
        fm = QFontMetrics(font)
        self.width = fm.width(self.text) + 2
        self.height = fm.height()

        svg = "<svg width=\"" + str(self.width) + "\" "
        svg += "height=\"" + str(self.height) + "\" >"
        svg += self.getTextTag("")
        svg += "</svg>"
        return svg
    def __init__(self, parent):
        super().__init__(parent)

        font = QFont("monospace")
        font.setPixelSize(27)
        self.setFont(font)
        self.qtcb_set_char.connect(self.set_char_slot)

        self.setText(" ")
        self.setFixedSize(23, 45)


        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(self.backgroundRole(), Qt.blue)
        palette.setColor(self.foregroundRole(), Qt.white)
        self.setPalette(palette)
Beispiel #50
0
 def createAxisLabelPixmap(self):
     pixmap = QPixmap(250, 250)
     pixmap.fill(self.backgroundColor)
     painter = QPainter()
     painter.begin(pixmap)
     font = QFont()
     font.setBold(True)
     font.setPixelSize(250 - 30)
     path = QPainterPath()
     path.addText(QPointF(50, 250 - 50), font, self.axis)
     brush = QBrush(self.foregroundColor)
     painter.setBrush(brush)
     painter.drawPath(path)
     painter.setFont(font)
     painter.end()
     pixmap = pixmap.scaled(QSize(self.labelsWidth, self.labelsheight), Qt.KeepAspectRatio, Qt.SmoothTransformation)
     return pixmap
Beispiel #51
0
 def __init__(self, xy, extra=None, parent=None):
     super().__init__(xy, parent, extra)
     s = 1
     if extra[3] != '':
         s = int(extra[3])
     self.setwh((3*s, 1*s))
     for i in range(len(extra) - 1):
         if extra[i] != '':
             self.color[i] = extra[i]
     self.template = self.template % (self.rgbToHex(self.color[1]), '%H:%M', self.rgbToHex(self.color[2]), '%S')
     self.setcolort(self.color[0])
     font = QFont('monospace')
     font.setPixelSize(.77 * s * UNIT)
     self.setFont(font)
     self.setAlignment(Qt.AlignBottom | Qt.AlignHCenter)
     self.tmr.timeout.connect(self.update)
     self.tmr.start(500)
     self.update()
Beispiel #52
0
    def create_font_array(self, char_height=62, pixel_margin=1, font_family='Courier', font_weight=50):
        # Load font and get the dimensions of one character (assuming monospaced font)
        f = QFont(font_family)
        f.setPixelSize(char_height)
        f.setWeight(font_weight)
        fm = QFontMetrics(f, QImage())

        char_width = char_height = 0
        char_y = 999

        for i in range(32, 127):
            bb = fm.boundingRect(chr(i))
            char_width = max(char_width, bb.width())
            char_height = max(char_height, bb.height())
            char_y = min(char_y, bb.y())

        imgsize = (char_width + 2 * pixel_margin, char_height + 2 * pixel_margin)
        self.char_ar = float(imgsize[1]) / imgsize[0]

        # init the image and the painter that will draw the characters to each image
        img = QImage(imgsize[0], imgsize[1], QImage.Format_ARGB32)
        ptr = c_void_p(int(img.constBits()))
        painter = QPainter(img)
        painter.setFont(f)
        painter.setPen(QColor(255, 255, 255, 255))

        # Set-up the texture array
        self.tex_id = gl.glGenTextures(1)
        gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.tex_id)
        gl.glTexImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, gl.GL_RGBA8, imgsize[0], imgsize[1], 127 - 32, 0, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, None)
        gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
        gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
        gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER)
        gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER)
        # We're using the ASCII range 32-126; space, uppercase, lower case, numbers, brackets, punctuation marks
        for i in range(32, 127):
            img.fill(0)
            painter.drawText(pixel_margin, pixel_margin - char_y, chr(i))
            gl.glTexSubImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, 0, 0, i - 32, imgsize[0], imgsize[1], 1, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, ptr)

        # We're done, close the painter, and return the texture ID, char width and char height
        painter.end()
Beispiel #53
0
 def __init__(self, xy, parent=None, extra=None):
     super().__init__(xy, parent, extra)
     self.setWordWrap(True)
     self.setIndent(UNIT / 10)
     font = QFont('sans-serif')
     #font.setStretch(QFont.SemiCondensed)
     font.setPixelSize(.24 * UNIT)
     self.setFont(font)
     if extra[0] != '':
         self.color = extra[0]
     self.setcolort(self.color)
     if extra[1] != '':
         self.cityid = extra[1]
     if extra[2] != '':
         self.dt = int(extra[2])
     if extra[3] != '':
         self.dr = int(extra[3])
     self.setwh((self.dr * 2, (self.dt // self.dr) * 2))
     self.tmr.timeout.connect(self.update)
     self.tmr.start(60 * 60 * 1000)
     self.update()
Beispiel #54
0
 def __init__(self, xy, parent=None, extra=None):
     super().__init__(xy, parent, extra)
     if len(self.extra) == 4:
         self.d, self.exe, self.ico, self.name = self.extra
     elif len(self.extra) == 3:
         self.d, self.exe, self.ico = self.extra
         self.name = self.exe.split()[0]
     self.setwh((self.d, self.d))
     icon = None
     if self.ico.split('.')[-1] == 'svg' or self.ico.split('.')[-1] == 'svgz':
         icon = QImage(int(self.d * UNIT / 2), int(self.d * UNIT / 2), QImage.Format_ARGB32)
         icon.fill(QColor(120, 120, 120, 0))
         renderer = QSvgRenderer(self.ico)
         painter = QPainter(icon)
         renderer.render(painter)
         del painter
     else:
         icon = QImage(self.ico)
     iconm = icon.scaled(2, 2)
     b1 = (QColor(iconm.pixel(0, 0)).getRgb(),
           QColor(iconm.pixel(0, 1)).getRgb(),
           QColor(iconm.pixel(1, 0)).getRgb(),
           QColor(iconm.pixel(1, 1)).getRgb(),)
     b = (0, 0, 0)
     for c in b1:
         b = (b[0] + c[0] // 4, b[1] + c[1] // 4, b[2] + c[2] // 4)
     self.setcolor(b)
     scale = min(icon.height(), icon.width(), self.d * UNIT / 2)
     self.setPixmap(QPixmap(icon).scaledToHeight(scale, Qt.SmoothTransformation))
     if self.d > 1:
         font = QFont('sans')
         # font.setStretch(QFont.SemiExpanded)
         font.setPixelSize(UNIT / 4)
         nametext = QLabel(parent=self)
         nametext.setFont(font)
         nametext.move(UNIT / 10, self.height() - UNIT / 10 - nametext.height() / 2)
         nametext.setAlignment(Qt.AlignBottom | Qt.AlignCenter)
         nametext.setIndent(self.d * UNIT / 20)
         nametext.setText('<font color=white>%s</font>' % self.name)
Beispiel #55
0
class Helper(object):
    def __init__(self):
        gradient = QLinearGradient(QPointF(50, -20), QPointF(80, 20))
        gradient.setColorAt(0.0, Qt.white)
        gradient.setColorAt(1.0, QColor(0xa6, 0xce, 0x39))

        self.background = QBrush(QColor(64, 32, 64))
        self.circleBrush = QBrush(gradient)
        self.circlePen = QPen(Qt.black)
        self.circlePen.setWidth(1)
        self.textPen = QPen(Qt.white)
        self.textFont = QFont()
        self.textFont.setPixelSize(50)

    def paint(self, painter, event, elapsed):
        painter.fillRect(event.rect(), self.background)
        painter.translate(100, 100)

        painter.save()
        painter.setBrush(self.circleBrush)
        painter.setPen(self.circlePen)
        painter.rotate(elapsed * 0.030)

        r = elapsed / 1000.0
        n = 30
        for i in range(n):
            painter.rotate(30)
            radius = 0 + 120.0*((i+r)/n)
            circleRadius = 1 + ((i+r)/n)*20
            painter.drawEllipse(QRectF(radius, -circleRadius,
                    circleRadius*2, circleRadius*2))

        painter.restore()

        painter.setPen(self.textPen)
        painter.setFont(self.textFont)
        painter.drawText(QRect(-50, -50, 100, 100), Qt.AlignCenter, "Qt")
Beispiel #56
0
    def drawContents(self, painter):
        if self._to_stop:
            return

        painter.save()
        painter.setPen(QColor(255, 255, 255, 255))
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.Antialiasing, True)

        version = Application.getInstance().getVersion().split("-")
        buildtype = Application.getInstance().getBuildType()
        if buildtype:
            version[0] += " (%s)" % buildtype

        # draw version text
        font = QFont()  # Using system-default font here
        font.setPixelSize(37)
        painter.setFont(font)
        painter.drawText(215, 66, 330 * self._scale, 230 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[0])
        if len(version) > 1:
            font.setPixelSize(16)
            painter.setFont(font)
            painter.setPen(QColor(200, 200, 200, 255))
            painter.drawText(247, 105, 330 * self._scale, 255 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[1])
        painter.setPen(QColor(255, 255, 255, 255))

        # draw the loading image
        pen = QPen()
        pen.setWidth(6 * self._scale)
        pen.setColor(QColor(32, 166, 219, 255))
        painter.setPen(pen)
        painter.drawArc(60, 150, 32 * self._scale, 32 * self._scale, self._loading_image_rotation_angle * 16, 300 * 16)

        # draw message text
        if self._current_message:
            font = QFont()  # Using system-default font here
            font.setPixelSize(13)
            pen = QPen()
            pen.setColor(QColor(255, 255, 255, 255))
            painter.setPen(pen)
            painter.setFont(font)
            painter.drawText(100, 128, 170, 64,
                             Qt.AlignLeft | Qt.AlignVCenter | Qt.TextWordWrap,
                             self._current_message)

        painter.restore()
        super().drawContents(painter)
Beispiel #57
0
    def set_style(self, style):
        super().set_style(style)

        self.seconds.setBrush(style.foreground_color)
        self.time.setBrush(style.foreground_color)
        self.date.setBrush(style.foreground_color)

        font = QFont(style.font)
        font.setPixelSize(192 * 0.5)
        self.seconds.setFont(font)

        font = QFont(style.font)
        font.setPixelSize(192 * 0.75)
        self.time.setFont(font)

        font = QFont(style.font)
        font.setPixelSize(56)
        self.date.setFont(font)
        self.layout()
Beispiel #58
0
    def set_style(self, style):
        super().set_style(style)

        font = QFont(style.font)
        font.setPixelSize(24)
        self.time.setFont(font)
        self.label.setFont(font)

        font = QFont(style.font)
        font.setPixelSize(192 / 2)
        self.time.setFont(font)

        font = QFont(style.font)
        font.setPixelSize(192 / 2 * 0.6)
        self.seconds.setFont(font)

        self.label.setBrush(self.style.foreground_color)
        self.time.setBrush(self.style.foreground_color)
        self.seconds.setBrush(self.style.foreground_color)

        self.layout()
Beispiel #59
0
    def load(self, path):
        self._path = path

        with open(os.path.join(self._path, "theme.json")) as f:
            data = json.load(f)

        self._initializeDefaults()

        if "colors" in data:
            for name, color in data["colors"].items():
                c = QColor(color[0], color[1], color[2], color[3])
                self._colors[name] = c

        fontsdir = os.path.join(self._path, "fonts")
        if os.path.isdir(fontsdir):
            for file in os.listdir(fontsdir):
                if "ttf" in file:
                    QFontDatabase.addApplicationFont(os.path.join(fontsdir, file))

        if "fonts" in data:
            for name, font in data["fonts"].items():
                f = QFont()

                if not sys.platform == "win32":
                    # Excluding windows here as a workaround for bad font rendering
                    f.setFamily(font.get("family", QCoreApplication.instance().font().family()))

                f.setStyleName(font.get("style", "Regular"))
                f.setBold(font.get("bold", False))
                f.setItalic(font.get("italic", False))
                f.setPixelSize(font.get("size", 1) * self._em_height)
                f.setCapitalization(QFont.AllUppercase if font.get("capitalize", False) else QFont.MixedCase)

                self._fonts[name] = f

        if "sizes" in data:
            for name, size in data["sizes"].items():
                s = QSizeF()
                s.setWidth(size[0] * self._em_width)
                s.setHeight(size[1] * self._em_height)

                self._sizes[name] = s

        styles = os.path.join(self._path, "styles.qml")
        if os.path.isfile(styles):
            c = QQmlComponent(self._engine, styles)
            self._styles = c.create()

            if c.isError():
                for error in c.errors():
                    Logger.log("e", error.toString())

        iconsdir = os.path.join(self._path, "icons")
        if os.path.isdir(iconsdir):
            for icon in os.listdir(iconsdir):
                name = os.path.splitext(icon)[0]
                self._icons[name] = QUrl.fromLocalFile(os.path.join(iconsdir, icon))

        imagesdir = os.path.join(self._path, "images")
        if os.path.isdir(imagesdir):
            for image in os.listdir(imagesdir):
                name = os.path.splitext(image)[0]
                self._images[name] = QUrl.fromLocalFile(os.path.join(imagesdir, image))

        Logger.log("d", "Loaded theme %s", self._path)
        self.themeLoaded.emit()
Beispiel #60
0
 def setup_fonts(self):
     font = QFont("mono")
     font.setStyleHint(QFont.Monospace)
     font.setPixelSize(12)
     self.setFont(font)