Beispiel #1
0
    def add_all_fish(self):
        """
        This function add the name of all known fish (the ones in Pref.txt) to the QListWidget which cintains selected
        fish. This function was copied from the one in SStathab_GUI.py
        """
        items = []
        for index in range(self.list_f.count()):
            items.append(self.list_f.item(index))
        if items:
            for i in range(0, len(items)):
                # avoid to have the same fish multiple times
                if items[i].text() in self.fish_selected:
                    pass
                else:
                    self.selected_aquatic_animal_qtablewidget.addItem(
                        items[i].text())
                    self.fish_selected.append(items[i].text())

                    # order the list (careful QLIstWidget do not order as sort from list)
                    if self.fish_selected:
                        self.fish_selected.sort()
                        self.selected_aquatic_animal_qtablewidget.clear()
                        self.selected_aquatic_animal_qtablewidget.addItems(
                            self.fish_selected)
                        # bold for selected fish
                        font = QFont()
                        font.setItalic(True)
                        for i in range(0, self.list_f.count()):
                            for f in self.fish_selected:
                                if f == self.list_f.item(i).text():
                                    self.list_f.item(i).setFont(font)
    def add_all_fish(self):
        """
        This function add the name of all known fish (the ones in Pref.txt) to the QListWidget. Careful,
        a similar function exists in Fstress_GUI. Modify both if needed.
        """

        items = []
        for index in range(self.list_f.count()):
            items.append(self.list_f.item(index))
        if items:
            for i in range(0, len(items)):
                # avoid to have the same fish multiple times
                if items[i].text() in self.fish_selected:
                    pass
                else:
                    self.list_s.addItem(items[i].text())
                    self.fish_selected.append(items[i].text())

                # order the list (careful QLIstWidget do not order as sort from list)
                if self.fish_selected:
                    self.fish_selected.sort()
                    self.list_s.clear()
                    self.list_s.addItems(self.fish_selected)
                    # bold for selected fish
                    font = QFont()
                    font.setItalic(True)
                    for i in range(0, self.list_f.count()):
                        for f in self.fish_selected:
                            if f == self.list_f.item(i).text():
                                self.list_f.item(i).setFont(font)
 def go_on_button(self, num=None):
     go = QPushButton('go>>')
     font = QFont('宋体', 25)
     font.setItalic(True)
     font.setBold(True)
     go.setFont(font)
     go.setFixedSize(150, 50)
     if num == -1:
         go.clicked.connect(self.width_height_layout_2)
     elif num == 0:
         go.clicked.connect(self.first_layout)
     elif num == 1:
         go.clicked.connect(self.second_layout)
     elif num == 2:
         go.clicked.connect(self.third_layout)
     elif num == 3:
         go.clicked.connect(self.firth_layout)
     elif num == 4:
         go.clicked.connect(self.fifth_layout)
     elif num == 5:
         go.clicked.connect(self.fifth_layout_1)
     elif num == 6:
         go.clicked.connect(self.fifth_layout_2)
     elif num == 7:
         go.clicked.connect(self.sixth_layout)
     elif num == 8:
         go.clicked.connect(self.seventh_layout)
     elif num == 9:
         go.clicked.connect(self.eighth_layout)
     else:
         go.clicked.connect(self.ninth_layout)
     return go
 def label_rbutton(self, content):
     label = QLabel(content)
     font = QFont('Microsoft YaHei UI', 20)
     font.setBold(True)
     font.setItalic(True)
     label.setFont(font)
     return label
Beispiel #5
0
    def data(self, column, role=Qt.DisplayRole):

        data = abstractItem.data(self, column, role)
        E = self.enum

        if role == Qt.DisplayRole or role == Qt.EditRole:
            if data == "" and column == E.revisions:
                return []

            else:
                return data

        elif role == Qt.DecorationRole and column == E.title:
            if self.customIcon():
                return QIcon.fromTheme(self.data(E.customIcon))
            if self.isFolder():
                return QIcon.fromTheme("folder")
            elif self.isText():
                return QIcon.fromTheme("text-x-generic")

        elif role == Qt.CheckStateRole and column == E.compile:
            return Qt.Checked if self.compile() else Qt.Unchecked

        elif role == Qt.FontRole:
            f = QFont()
            if column == E.wordCount and self.isFolder():
                f.setItalic(True)
            elif column == E.goal and self.isFolder() and not self.data(
                    E.setGoal):
                f.setItalic(True)
            if self.isFolder():
                f.setBold(True)
            return f
    def create_res(self):
        tmp = self.simi_base[:]
        for idx, k in enumerate(tmp):
            if k == '':
                tmp[idx] = u'.'
        tmp_sql = "SELECT * FROM `plate_nums` where occupied = 0  and plate_num regexp '{regexp}' limit 15".format(
            regexp=''.join(tmp))
        res = dbOper().query(tmp_sql)

        if not res:
            self.error_plate_format.setText(u"抱歉,查询无结果\n请尝试输入其他条件")
            self.error_plate_format.show()
        else:
            for idx, item in enumerate(res):
                button = QPushButton()
                self.res_box.addWidget(button, idx / 3, idx % 3)
                self.res_box.setAlignment(Qt.AlignHCenter)
                tmp_plate = u'沪' + item['prefix'] + '/ ' + item['plate_num']
                button.setText(tmp_plate)
                res_font = QFont()
                res_font.setPointSize(30)
                res_font.setBold(True)
                res_font.setItalic(False)
                res_font.setWeight(20)
                button.setFont(res_font)
                button.kv = item
                button.clicked.connect(self.after_select)
            self.begin_button.setDisabled(1)
    def data(self, index, role):
        row = index.row()
        column = index.column()

        if role == Qt.DisplayRole:
            text = "({},{})".format(row, column)
            return text
        elif role == Qt.FontRole:
            if row == 0 and column == 0:                # change font only for cell(0,0)
                my_font = QFont()
                my_font.setBold(True)
                my_font.setItalic(True)
                my_font.setUnderline(True)
                return my_font
        elif role == Qt.BackgroundRole:
            if row == 1 and column == 2:                # change background only for cell(1,2)
                my_background = QBrush(Qt.red)
                return my_background
        elif role == Qt.TextAlignmentRole:
            if row == 1 and column == 1:                # change text alignment only for cell(1,1)
                return Qt.AlignRight + Qt.AlignVCenter
        elif role == Qt.CheckStateRole:
            if row == 0 and column == 1:                # add checkbox only for cell(0,1)
                return Qt.Checked
            elif row == 0 and column == 2:              # add checkbox only for cell(0,2)
                return Qt.Unchecked

        return QVariant()                               # see http://doc.qt.io/qt-5/qvariant.html#details
    def __init__(self, label='', line_name='na', required=False, parent=None):
        QWidget.__init__(self)
        self.layout = QHBoxLayout()
        self.qlbl = QLabel(label, self)
        self.added_line = QLineEdit()
        self.added_line.setObjectName(line_name)
        self.layout.addWidget(self.qlbl)
        self.layout.addWidget(self.added_line)

        if required:
            self.required_label = QLabel(self)
            font = QFont()
            font.setFamily("Arial")
            font.setPointSize(9)
            font.setBold(False)
            font.setItalic(False)
            font.setWeight(50)
            self.required_label.setFont(font)
            self.required_label.setScaledContents(True)
            self.required_label.setAlignment(QtCore.Qt.AlignHCenter
                                             | QtCore.Qt.AlignVCenter)
            self.required_label.setIndent(0)

            self.required_label.setText(
                QtCore.QCoreApplication.translate(
                    "USGSContactInfoWidget",
                    "<html><head/><body><p align=\"center\"><span style=\" font-size:18pt; color:#55aaff;\">*</span></p></body></html>"
                ))
            self.layout.addWidget(self.required_label)

        self.layout.setContentsMargins(1, 1, 1, 1)
        self.layout.setSpacing(6)
        self.setLayout(self.layout)
Beispiel #9
0
    def __init__(self, parent=None, xmlelement='QDomElement:None', index=0,
                 edit=False):
        super().__init__(parent)
        self.element = xmlelement
        self.edit = edit
        self.index = index
        self.viewport().index = index
        self.var_dict = dict()
        self.widget_dict = dict()
        self.expr_value = self.element.text()
        if edit:
            self.setReadOnly(True)
            self.viewport().setEnabled(False)

        width = float(
            self.element.attribute("width")) * 7 if self.element.attribute(
            "width") else 0
        height = float(
            self.element.attribute("height")) * 24 if self.element.attribute(
            "height") else 24
        self.resize(width, height)
        font = QFont()
        if self.element.hasAttribute("size"):
            try:
                font.setPointSize(float(self.element.attribute("size")))
            except:
                pass
        if self.element.hasAttribute("style"):
            format = '{:03b}'.format(int(self.element.attribute("style")))
            font.setBold(True if format[0] != '0' else False)
            font.setItalic(True if format[1] != '0' else False)
            font.setUnderline(True if format[2] != '0' else False)
        self.setFont(font)
Beispiel #10
0
 def init_editor(self):
     """"Initializes the editor widget."""
     font = QFont()
     self.tool_bar = QToolBar("Format Actions", self)
     self.cursor_position_changed.connect(self.reload_status)
     self.bold_btn = QToolButton(self)
     self.bold_btn.setText("B")
     font.setBold(True)
     self.bold_btn.setFont(font)
     font.setBold(False)
     self.bold_btn.setCheckable(True)
     self.bold_btn.clicked.connect(self.toggle_bold)
     self.tool_bar.addWidget(self.bold_btn)
     self.italic_btn = QToolButton(self)
     self.italic_btn.setText("I")
     font.setItalic(True)
     self.italic_btn.setFont(font)
     font.setItalic(False)
     self.italic_btn.setCheckable(True)
     self.italic_btn.clicked.connect(self.toggle_italic)
     self.tool_bar.addWidget(self.italic_btn)
     self.underline_btn = QToolButton(self)
     self.underline_btn.setText("U")
     font.setUnderline(True)
     self.underline_btn.setFont(font)
     font.setUnderline(False)
     self.underline_btn.setCheckable(True)
     self.underline_btn.clicked.connect(self.toggle_underline)
     self.tool_bar.addWidget(self.underline_btn)
     self.reload_status()
Beispiel #11
0
    def update_item(self):
        self.setText(0, self.download_info["name"])
        if self.download_info["name"] == u"<old version of your channel>":
            itfont = QFont(self.font(0))
            itfont.setItalic(True)
            self.setFont(0, itfont)
        else:
            self.font(0).setItalic(False)
        self.setText(1, format_size(float(self.download_info["size"])))

        try:
            self.progress_slider.setValue(int(self.download_info["progress"] * 100))
        except RuntimeError:
            self._logger.error("The underlying GUI widget has already been removed.")

        if self.download_info["vod_mode"]:
            self.setText(3, "Streaming")
        else:
            self.setText(3, DLSTATUS_STRINGS[eval(self.download_info["status"])])
        self.setText(4, "%s (%s)" % (self.download_info["num_connected_seeds"], self.download_info["num_seeds"]))
        self.setText(5, "%s (%s)" % (self.download_info["num_connected_peers"], self.download_info["num_peers"]))
        self.setText(6, format_speed(self.download_info["speed_down"]))
        self.setText(7, format_speed(self.download_info["speed_up"]))
        self.setText(8, "%.3f" % float(self.download_info["ratio"]))
        self.setText(9, "yes" if self.download_info["anon_download"] else "no")
        self.setText(10, str(self.download_info["hops"]) if self.download_info["anon_download"] else "-")
        self.setText(12, datetime.fromtimestamp(int(self.download_info["time_added"])).strftime('%Y-%m-%d %H:%M'))

        eta_text = "-"
        if self.get_raw_download_status() == DLSTATUS_DOWNLOADING:
            eta_text = duration_to_string(self.download_info["eta"])
        self.setText(11, eta_text)
Beispiel #12
0
    def __init__(self):
        QMainWindow.__init__(self)
        # self refers to QMainWindow
        self.settings = QSettings('Peppercorn', 'Peppercorn_Note_Pad')
        self.filename = None
        self.file_open = False
        self.te_main = QTextEdit(self)
        self.setWindowTitle("Peppercorn Notepad")
        self.setGeometry(100, 100, 800, 500)
        self.setMinimumSize(200, 200)

        try:
            self.resize(self.settings.value('window size'))
            # print('sized')
            self.move(self.settings.value('window location'))
            # print('moved')
            font = QFont()
            # print('font')
            font.setFamily(self.settings.value('font family'))
            # print(str(self.settings.value('font family')))
            font.setPointSize(int(self.settings.value('font size')))
            # print(self.settings.value('font size'))
            font.setBold(eval(self.settings.value('bold')))
            # print(self.settings.value('bold'))
            font.setItalic(eval(self.settings.value('italics')))
            # print(self.settings.value('italics'))
            font.setUnderline(eval(self.settings.value('underline')))
            # print(self.settings.value('underline'))
            self.te_main.setFont(font)
        except:
            pass
        self.build_ui()
Beispiel #13
0
def update_font(basefont,
                weight=None,
                italic=None,
                underline=None,
                pixelSize=None,
                pointSize=None):
    """
    Return a copy of `basefont` :class:`QFont` with updated properties.
    """
    font = QFont(basefont)

    if weight is not None:
        font.setWeight(weight)

    if italic is not None:
        font.setItalic(italic)

    if underline is not None:
        font.setUnderline(underline)

    if pixelSize is not None:
        font.setPixelSize(pixelSize)

    if pointSize is not None:
        font.setPointSize(pointSize)

    return font
Beispiel #14
0
    def data(self, index, role=None):
        if not index or not index.isValid():
            return False
        languages = index.internalPointer()
        language = languages[index.row()]

        if role == Qt.UserRole:
            return language

        if role == Qt.FontRole:
            if language.is_generic():
                font = QFont()
                font.setItalic(True)
                return font

        if role == Qt.DecorationRole:
            xx = language.xx()
            return QIcon(':/images/flags/{xx}.png'.format(xx=xx)).pixmap(
                QSize(24, 24), QIcon.Normal)

        if role == Qt.DisplayRole:
            if language.is_generic():
                return _(self._unknown_text)
            else:
                return language.name()
        return None
    def setupUi(self, Wait_Screen):
        if Wait_Screen.objectName():
            Wait_Screen.setObjectName(u"Wait_Screen")
        Wait_Screen.resize(641, 251)
        Wait_Screen.setStyleSheet(u"color: rgb(255, 255, 255);\n"
                                  "background-color: rgb(35, 35, 35);")
        self.Label = QLabel(Wait_Screen)
        self.Label.setObjectName(u"Label")
        self.Label.setGeometry(QRect(0, 0, 641, 251))
        font = QFont()
        font.setFamily(u"MS Reference Sans Serif")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.Label.setFont(font)
        self.Label.setStyleSheet(u"QLabel {\n"
                                 "	color: rgb(255, 255, 255);\n"
                                 "	background-color: rgb(35, 35, 35);\n"
                                 "	border: 2px solid;\n"
                                 "	border-color: rgb(255, 255, 255);\n"
                                 "	font: 12pt;\n"
                                 "    font-weight: bold;\n"
                                 "}")
        self.Label.setAlignment(Qt.AlignCenter)

        self.retranslateUi(Wait_Screen)

        QMetaObject.connectSlotsByName(Wait_Screen)
Beispiel #16
0
 def setupUi(self, StartPage_Url):
     StartPage_Url.setObjectName("StartPage_Url")
     self.centralwidget = QWidget(StartPage_Url)
     self.centralwidget.setObjectName("centralwidget")
     self.btn_go = QPushButton(self.centralwidget)
     self.btn_go.setGeometry(QRect(250, 150, 88, 33))
     self.btn_go.setObjectName("btn_go")
     self.btn_go.clicked.connect(lambda: self.TypeFinder())
     self.L_Heading = QLabel(self.centralwidget)
     self.L_Heading.setGeometry(QRect(120, 20, 331, 20))
     font = QFont()
     font.setPointSize(14)
     font.setBold(True)
     font.setItalic(True)
     font.setWeight(75)
     self.L_Heading.setFont(font)
     self.L_Heading.setLayoutDirection(Qt.LeftToRight)
     self.L_Heading.setAutoFillBackground(True)
     self.L_Heading.setObjectName("L_Heading")
     self.groupBox = QGroupBox(self.centralwidget)
     self.groupBox.setGeometry(QRect(20, 200, 231, 111))
     self.groupBox.setObjectName("groupBox_for_typeSelection")
     self.label = QLabel(self.groupBox)
     self.label.setGeometry(QRect(40, 20, 111, 17))
     self.label.setObjectName("Title_label")
     self.label_2 = QLabel(self.groupBox)
     self.label_2.setGeometry(QRect(40, 40, 121, 17))
     self.label_2.setObjectName("label_info")
     self.label_5 = QLabel(self.groupBox)
     self.label_5.setGeometry(QRect(40, 60, 141, 20))
     self.label_5.setObjectName("label_5")
     self.label_3 = QLabel(self.groupBox)
     self.label_3.setGeometry(QRect(40, 80, 141, 20))
     self.label_3.setObjectName("label_3")
     self.label_4 = QLabel(self.centralwidget)
     self.label_4.setGeometry(QRect(200, 310, 451, 20))
     self.label_4.setObjectName("label_info")
     self.url_txtbox = QLineEdit(self.centralwidget)
     self.url_txtbox.setGeometry(QRect(72, 70, 431, 33))
     self.url_txtbox.setObjectName("url_txtbox")
     self.url_txtbox.returnPressed.connect(self.TypeFinder)
     StartPage_Url.setCentralWidget(self.centralwidget)
     self.menubar = QMenuBar(StartPage_Url)
     self.menubar.setGeometry(QRect(0, 0, 586, 25))
     self.menubar.setObjectName("menubar")
     self.menuAbout = QMenu(self.menubar)
     self.menuAbout.setObjectName("menuAbout")
     self.about_opt = QMenu(self.menubar)
     self.about_opt.setObjectName("about_opt")
     StartPage_Url.setMenuBar(self.menubar)
     self.statusbar = QStatusBar(StartPage_Url)
     self.statusbar.setObjectName("statusbar")
     StartPage_Url.setStatusBar(self.statusbar)
     self.pings = QAction(StartPage_Url)
     self.pings.setObjectName("pings")
     self.menuAbout.addAction(self.pings)
     self.pings.triggered.connect(lambda: self.ping())
     self.menubar.addAction(self.menuAbout.menuAction())
     self.retranslateUi(StartPage_Url)
     QMetaObject.connectSlotsByName(StartPage_Url)
    def data(self, index, role):
        row = index.row()
        column = index.column()

        if role == Qt.DisplayRole:
            text = "({},{})".format(row, column)
            return text
        elif role == Qt.FontRole:
            if row == 0 and column == 0:  # change font only for cell(0,0)
                my_font = QFont()
                my_font.setBold(True)
                my_font.setItalic(True)
                my_font.setUnderline(True)
                return my_font
        elif role == Qt.BackgroundRole:
            if row == 1 and column == 2:  # change background only for cell(1,2)
                my_background = QBrush(Qt.red)
                return my_background
        elif role == Qt.TextAlignmentRole:
            if row == 1 and column == 1:  # change text alignment only for cell(1,1)
                return Qt.AlignRight + Qt.AlignVCenter
        elif role == Qt.CheckStateRole:
            if row == 0 and column == 1:  # add checkbox only for cell(0,1)
                return Qt.Checked
            elif row == 0 and column == 2:  # add checkbox only for cell(0,2)
                return Qt.Unchecked

        return QVariant()  # see http://doc.qt.io/qt-5/qvariant.html#details
Beispiel #18
0
    def __init__(self, parent):
        QsciLexerCPP.__init__(self, parent)
        self.setFont(self.parent().Font)
        self.setColor(QColor(0, 0, 0))  # 设置默认的字体颜色
        self.setPaper(QColor(255, 255, 255))  # 设置底色
        self.setColor(QColor("#B0171F"), QsciLexerCPP.Keyword)

        self.setColor(QColor("#008000"), QsciLexerCPP.CommentDoc)  # 文档注释 /**开头的颜色
        self.setColor(QColor("#008000"), QsciLexerCPP.Comment)  # 块注释 的颜色
        self.setColor(QColor("#008000"), QsciLexerCPP.CommentLine)  # 行注释的颜色
        self.setColor(QColor("#007f7f"), QsciLexerCPP.Number)  # 数字 的颜色
        self.setColor(QColor("#ff00ff"), QsciLexerCPP.DoubleQuotedString)  # 双引号字符串的颜色
        self.setColor(QColor("#ff00ff"), QsciLexerCPP.SingleQuotedString)  # 单引号字符的颜色
        self.setColor(QColor("#191970"), QsciLexerCPP.PreProcessor)  # 预编译语句的颜色
        self.setColor(QColor("#be07ff"), QsciLexerCPP.Operator)
        # self.setColor(QColor("#000000"), QsciLexerCPP.Identifier)  #可识别字符的颜色,这个范围很广,包含了关键词,函数名;所以要取消这句
        self.setColor(QColor("#0000FF"), QsciLexerCPP.UnclosedString)  # 未完成输入的字符串的颜色

        font = QFont(self.parent().Font)
        font.setBold(True)
        font.setItalic(True)
        self.setFont(font, QsciLexerCPP.Comment)  # 注释的字体用斜体。
        self.setFont(font, 5)  # 默认的字体加粗。

        font = QFont(self.parent().Font)
Beispiel #19
0
 def data(self, index: QModelIndex, role=Qt.DisplayRole):
     i, j = index.row(), index.column()
     if role == Qt.DisplayRole:
         try:
             lbl = self.message_type[i]
         except IndexError:
             return False
         if j == 0:
             return lbl.name
         elif j == 1:
             return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[0] + 1
         elif j == 2:
             return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[1]
         elif j == 3:
             return lbl.color_index
         elif j == 4:
             return lbl.apply_decoding
     elif role == Qt.TextAlignmentRole:
         return Qt.AlignCenter
     elif role == Qt.FontRole and j == 0:
         font = QFont()
         font.setItalic(self.message_type[i].field_type is None)
         return font
     else:
         return None
Beispiel #20
0
    def update_font_slot(self):
        font = QFont()

        is_bold = self.ui.boldCheckBox.isChecked()
        font.setBold(is_bold)
        self.current_el.is_bold = is_bold

        is_italic = self.ui.italicCheckBox.isChecked()
        font.setItalic(is_italic)
        self.current_el.is_italic = is_italic

        is_underline = self.ui.underlineCheckBox.isChecked()
        font.setUnderline(is_underline)
        self.current_el.is_underline = is_underline

        font_name = self.ui.fontComboBox.currentText()
        self.current_el.font = font_name
        font.setFamily(font_name)

        size = self.ui.sizeSpinBox.value()
        font.setPointSize(size)
        self.current_el.size = size

        self.current_w.setFont(font)
        self.current_w.adjustSize()
Beispiel #21
0
 def __init__(self,
              parent=None,
              xmlelement='QDomElement:None',
              index=0,
              edit=False):
     super().__init__(parent)
     self.element = xmlelement
     self.index = index
     self.edit = edit
     self.var_dict = dict()
     self.widget_dict = dict()
     # self.setStyleSheet("margin:2 2;")
     width = int(self.element.attribute(
         "width")) * 7 if self.element.attribute("width") else 130
     height = int(self.element.attribute(
         "height")) * 24 if self.element.attribute("height") else 24
     self.resize(width, height)
     font = QFont()
     if self.element.hasAttribute("size"):
         try:
             font.setPointSize(float(self.element.attribute("size")))
         except:
             pass
     if self.element.hasAttribute("style"):
         format = '{:03b}'.format(int(self.element.attribute("style")))
         font.setBold(True if format[0] != '0' else False)
         font.setItalic(True if format[1] != '0' else False)
         font.setUnderline(True if format[2] != '0' else False)
     self.setFont(font)
     if not edit:
         self.setEditable(False if self.element.attribute("edit", "0") ==
                          "0" else True)
     self.currentTextChanged.connect(self.on_currentTextChanged)
     self.currentIndexChanged.connect(self.on_currentIndexChanged)
Beispiel #22
0
    def __applyMonokaiPython(self, lexerName):
        defaultFont = QFont("Roboto Mono", self.__defaultFontSize, -1, False)
        colors = [
            "#ffffff", "#888877", "#ae81ff", "#ffff88", "#ffff88", "#ff3377",
            "#ffff88", "#ffff88", "#aaff33", "#aaff47", "#ff3377", "#ffffff",
            "#888877", "#f8f8f0", "#ffe892", "#aa88ff"
        ]

        lexer = PreferencesLexer(lexerName)

        for i in range(0, 15):
            lexer.setPaper(QColor(Qt.black), i)
            lexer.setFont(defaultFont, i)
            lexer.setColor(QColor(colors[i]), i)

        # specific values now
        # comment
        defaultFont.setItalic(True)
        lexer.setFont(defaultFont, 1)
        defaultFont.setItalic(False)

        # class name
        defaultFont.setUnderline(True)
        lexer.setFont(defaultFont, 8)

        # Unclosed string
        lexer.setPaper(QColor("#f92672"), 13)
        lexer.setEolFill(True, 13)

        lexer.writeSettings(Preferences.Prefs.settings, "Scintilla")
Beispiel #23
0
    def __update_tree_modules(self, current):
        modules = current['modules'] if 'modules' in current else {}
        model = QStandardItemModel()
        parent_item = model.invisibleRootItem()  # type: QStandardItem

        for m in sorted(modules):
            text_item = QStandardItem(m)
            text_item.setEditable(False)
            text_item.setCheckState(
                Qt.Checked if json.loads(modules[m].lower()) else Qt.Unchecked)

            # NOTE: some modules name their parameters differently than themselves
            if json.loads(modules[m].lower()) and m in current:
                for i in sorted(current[m]):
                    item = QStandardItem(i + " = " + current[m][i])
                    item.setEditable(False)
                    font = QFont()
                    font.setItalic(True)
                    item.setFont(font)
                    text_item.appendRow(item)

            parent_item.appendRow(text_item)

        model.setHeaderData(0, Qt.Horizontal, "Modules")
        self.ui.modules.setModel(model)
Beispiel #24
0
    def __init__(self):
        super().__init__()


        geom = QApplication.desktop().availableGeometry()
        self.setGeometry(QRect(round(geom.width()*0.05),
                               round(geom.height()*0.05),
                               round(min(geom.width()*0.98, self.CONTROL_AREA_WIDTH+10)),
                               round(min(geom.height()*0.95, 100))))

        self.setMaximumHeight(self.geometry().height())
        self.setMaximumWidth(self.geometry().width())

        self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH)


        label = gui.label(self.controlArea, self, "From Oasys Surface To Shadow Surface")
        font = QFont(label.font())
        font.setBold(True)
        font.setItalic(True)
        font.setPixelSize(14)
        label.setFont(font)
        palette = QPalette(label.palette()) # make a copy of the palette
        palette.setColor(QPalette.Foreground, QColor('Dark Blue'))
        label.setPalette(palette) # assign new palette

        gui.separator(self.controlArea, 10)

        gui.button(self.controlArea, self, "Convert", callback=self.convert_surface, height=45)
Beispiel #25
0
    def _configure_widget(self, el, widget):
        w, h = widget.geometry().width(), widget.geometry().height()
        widget.setGeometry(
            QRect(round(el.ratio_x * self.screen_w),
                  round(el.ratio_y * self.screen_h), w, h))

        font = QFont()
        font.setFamily(el.font)

        if el.color:
            utils.set_widget_stylesheet(widget, f'color: {el.color}')
        if el.size:
            font.setPointSize(el.size)
        if el.is_bold:
            font.setBold(True)
        if el.is_italic:
            font.setItalic(True)
        if el.is_underline:
            font.setUnderline(True)
        if el.shadow_blur or el.shadow_offset:
            eff = QGraphicsDropShadowEffect()
            eff.setBlurRadius(el.shadow_blur)
            eff.setOffset(el.shadow_offset)
            widget.setGraphicsEffect(eff)
        if el.shadow_offset or el.shadow_blur:
            eff = QGraphicsDropShadowEffect()
            eff.setBlurRadius(el.shadow_blur)
            eff.setOffset(el.shadow_offset)
            widget.setGraphicsEffect(eff)
        widget.setFont(font)
        widget.adjustSize()
Beispiel #26
0
    def __init__(self, parent=None):
        """Constructor."""
        super(SetColumnsDialog, self).__init__(parent)
        #self.setupUi(self)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)
        self.resize(900, 700)

        # attributes
        self.filename = None

        self.progress = QProgressBar(self)
        self.progress.setGeometry(20, 550, 480, 20)
        self.progress.setRange(0, 0)
        self.progress.setVisible(False)

        self.progressInfo = QLabel(self)
        self.progressInfo.setText("Generando el reporte, por favor espere...")
        self.progressInfo.move(20, 570)
        newfont = QFont("Arial", 10)
        newfont.setItalic(True)
        self.progressInfo.setFont(newfont)
        self.progressInfo.setVisible(False)
    def actionItalic(self):

        myFont = QFont()

        myFont.setItalic(True)

        self.textEdit.setFont(myFont)
Beispiel #28
0
    def __init__(self):
        super().__init__()

        button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal")

        button = gui.button(button_box, self, "Run Retrace", callback=self.retrace)
        font = QFont(button.font())
        font.setBold(True)
        button.setFont(font)
        palette = QPalette(button.palette()) # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Blue'))
        button.setPalette(palette) # assign new palette
        button.setFixedHeight(45)

        button = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings)
        font = QFont(button.font())
        font.setItalic(True)
        button.setFont(font)
        palette = QPalette(button.palette()) # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Red'))
        button.setPalette(palette) # assign new palette
        button.setFixedHeight(45)
        button.setFixedWidth(150)

        gui.separator(self.controlArea)

        box = oasysgui.widgetBox(self.controlArea, "", orientation="vertical", width=self.CONTROL_AREA_WIDTH-5, height=550)

        main_box = oasysgui.widgetBox(box, "Shadow Beam Retrace", orientation="vertical", width=self.CONTROL_AREA_WIDTH-5, height=70)

        self.le_retrace_distance = oasysgui.lineEdit(main_box, self, "retrace_distance", "Retrace to ", labelWidth=280, valueType=float, orientation="horizontal")
Beispiel #29
0
 def data(self, index: QModelIndex, role=Qt.DisplayRole):
     i, j = index.row(), index.column()
     if role == Qt.DisplayRole:
         try:
             lbl = self.message_type[i]
         except IndexError:
             return False
         if j == 0:
             return lbl.name
         elif j == 1:
             return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[0] + 1
         elif j == 2:
             return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[1]
         elif j == 3:
             return lbl.color_index
         elif j == 4:
             return lbl.apply_decoding
     elif role == Qt.TextAlignmentRole:
         return Qt.AlignCenter
     elif role == Qt.FontRole and j == 0:
         font = QFont()
         font.setItalic(self.message_type[i].type is None)
         return font
     else:
         return None
 def __adjustItemFeatures(self, itm, rule):
     """
     Private method to adjust an item.
     
     @param itm item to be adjusted (QTreeWidgetItem)
     @param rule rule for the adjustment (AdBlockRule)
     """
     if not rule.isEnabled():
         font = QFont()
         font.setItalic(True)
         itm.setForeground(0, QColor(Qt.gray))
         
         if not rule.isComment() and not rule.isHeader():
             itm.setFlags(itm.flags() | Qt.ItemIsUserCheckable)
             itm.setCheckState(0, Qt.Unchecked)
             itm.setFont(0, font)
         
         return
     
     itm.setFlags(itm.flags() | Qt.ItemIsUserCheckable)
     itm.setCheckState(0, Qt.Checked)
     
     if rule.isCSSRule():
         itm.setForeground(0, QColor(Qt.darkBlue))
         itm.setFont(0, QFont())
     elif rule.isException():
         itm.setForeground(0, QColor(Qt.darkGreen))
         itm.setFont(0, QFont())
     else:
         itm.setForeground(0, QColor())
         itm.setFont(0, QFont())
Beispiel #31
0
    def getFontFromCmnd(self, fontinfo):
        '''
        Returns a QFont based on the information in the dictionary
        fontinfo.

        Recognized keys in the font dictionary are:
            "family": font family name (string)
            "size": text size in points (1/72 inches)
            "italic": italicize? (False/True)
            "bold": make bold? (False/True)
            "underline": underline?  (False/True)
        '''
        try:
            myfont = QFont(fontinfo["family"])
        except KeyError:
            myfont = self.__viewer.font()
        try:
            myfont.setPointSizeF(fontinfo["size"])
        except KeyError:
            pass
        try:
            myfont.setItalic(fontinfo["italic"])
        except KeyError:
            pass
        try:
            myfont.setBold(fontinfo["bold"])
        except KeyError:
            pass
        try:
            myfont.setUnderline(fontinfo["underline"])
        except KeyError:
            pass
        return myfont
Beispiel #32
0
    def data(self, column, role=Qt.DisplayRole):

        data = abstractItem.data(self, column, role)
        E = self.enum

        if role == Qt.DisplayRole or role == Qt.EditRole:
            if data == "" and column == E.revisions:
                return []

            else:
                return data

        elif role == Qt.DecorationRole and column == E.title:
            if self.customIcon():
                return QIcon.fromTheme(self.data(E.customIcon))
            if self.isFolder():
                return QIcon.fromTheme("folder")
            elif self.isText():
                return QIcon.fromTheme("text-x-generic")

        elif role == Qt.CheckStateRole and column == E.compile:
            return Qt.Checked if self.compile() else Qt.Unchecked

        elif role == Qt.FontRole:
            f = QFont()
            if column == E.wordCount and self.isFolder():
                f.setItalic(True)
            elif column == E.goal and self.isFolder() and not self.data(E.setGoal):
                f.setItalic(True)
            if self.isFolder():
                f.setBold(True)
            return f
Beispiel #33
0
    def data(self, index, role=None):
        if not index.isValid():
            return None
        provider_state = self.provider_state_at_index(index.row())

        if provider_state is None:
            if role == Qt.FontRole:
                font = QFont()
                font.setItalic(True)
                return font
            elif role == Qt.DisplayRole:
                return self._general_text
        else:
            if role == Qt.UserRole:
                return provider_state
            elif role == Qt.DecorationRole:
                path = provider_state.provider.get_icon()
                if path:
                    return QIcon(path)
                else:
                    return None
            elif role == Qt.TextColorRole:
                if not provider_state.getEnabled():
                    color = QColor(Qt.lightGray)
                    return color
            elif role == Qt.DisplayRole:
                return provider_state.provider.get_name()

        return None
Beispiel #34
0
    def help_dialog(self):

        self.helpDialog = QDialog()
        self.helpDialog.setObjectName("self.helpDialog")
        self.helpDialog.setWindowModality(Qt.ApplicationModal)
        self.helpDialog.setFixedSize(362, 151)
        icon = QIcon()
        icon.addPixmap(QPixmap("../resource/logo.png"), QIcon.Normal,
                       QIcon.Off)
        self.helpDialog.setWindowIcon(icon)
        self.helpDialog.setLayoutDirection(Qt.LeftToRight)
        self.helpDialog.setAutoFillBackground(False)
        self.helpDialog.setSizeGripEnabled(False)
        self.helpDialog.setModal(False)
        self.docButton = QPushButton(self.helpDialog)
        self.docButton.setGeometry(QRect(200, 100, 111, 41))
        icon1 = QIcon()
        icon1.addPixmap(QPixmap("../resource/Doc.png"), QIcon.Normal,
                        QIcon.Off)
        self.docButton.setIcon(icon1)
        self.docButton.setObjectName("docButton")
        self.tubeButton = QPushButton(self.helpDialog)
        self.tubeButton.setGeometry(QRect(50, 100, 111, 41))
        icon2 = QIcon()
        icon2.addPixmap(QPixmap("../resource/YouTube.png"), QIcon.Normal,
                        QIcon.Off)
        self.tubeButton.setIcon(icon2)
        self.tubeButton.setObjectName("tubeButton")
        self.label = QLabel(self.helpDialog)
        self.label.setGeometry(QRect(20, 10, 331, 21))
        font = QFont()
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QLabel(self.helpDialog)
        self.label_2.setGeometry(QRect(20, 30, 321, 21))
        font = QFont()
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_3 = QLabel(self.helpDialog)
        self.label_3.setGeometry(QRect(20, 50, 321, 20))
        font = QFont()
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.label_4 = QLabel(self.helpDialog)
        self.label_4.setGeometry(QRect(30, 80, 211, 17))
        font = QFont()
        font.setPointSize(8)
        font.setItalic(True)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")

        self.retranslate_help_ui(self.helpDialog)
        QMetaObject.connectSlotsByName(self.helpDialog)
        self.docButton.clicked.connect(self.open_github)

        self.helpDialog.exec_()
 def set_font_style(self, family, size, form):
     font = QFont()
     font.setFamily(family)
     font.setPointSize(size)
     boldFlag, italicFlag = self.interprete_font_form(form)
     font.setBold(boldFlag)
     font.setItalic(italicFlag)
     self.setFont(font)
Beispiel #36
0
 def paintNodeName(self, painter):
     if self.nodeNameDisplayed == '':
         self.setNodeName()
     
     font = QFont("Arial", 12)
     font.setItalic(True)
     painter.setFont(font)
     rect = QRectF(0, 0, self.nodeBodyWidth, self.nodeBodyHeight)
     painter.drawText(rect, Qt.AlignCenter, self.nodeNameDisplayed)
Beispiel #37
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            publication_col = CertifiersTableModel.columns_ids.index('publication')
            publication_index = self.sourceModel().index(source_index.row(), publication_col)
            expiration_col = CertifiersTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)
            written_col = CertifiersTableModel.columns_ids.index('written')
            written_index = self.sourceModel().index(source_index.row(), written_col)

            publication_data = self.sourceModel().data(publication_index, Qt.DisplayRole)
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            written_data = self.sourceModel().data(written_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            warning_expiration_time = int((expiration_data - publication_data) / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if role == Qt.DisplayRole:
                if source_index.column() == CertifiersTableModel.columns_ids.index('expiration'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == CertifiersTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == CertifiersTableModel.columns_ids.index('pubkey'):
                    return source_data

            if role == Qt.FontRole:
                font = QFont()
                if not written_data:
                    font.setItalic(True)
                return font

            if role == Qt.ForegroundRole:
                if current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    return QColor("darkorange").darker(120)

            return source_data
Beispiel #38
0
    def createEditor(self, parent, option, index):
        self.updateRects(option, index)

        bgColor = self.bgColors.get(index, "white")

        if self.mainLineRect.contains(self.lastPos):
            # One line summary
            self.editing = Outline.summarySentence
            edt = QLineEdit(parent)
            edt.setFocusPolicy(Qt.StrongFocus)
            edt.setFrame(False)
            f = QFont(option.font)
            if self.newStyle():
                f.setBold(True)
            else:
                f.setItalic(True)
                edt.setAlignment(Qt.AlignCenter)
            edt.setPlaceholderText(self.tr("One line summary"))
            edt.setFont(f)
            edt.setStyleSheet("background: {}; color: black;".format(bgColor))
            return edt

        elif self.titleRect.contains(self.lastPos):
            # Title
            self.editing = Outline.title
            edt = QLineEdit(parent)
            edt.setFocusPolicy(Qt.StrongFocus)
            edt.setFrame(False)
            f = QFont(option.font)
            if self.newStyle():
                f.setPointSize(f.pointSize() + 4)
            else:
                edt.setAlignment(Qt.AlignCenter)
            f.setBold(True)
            edt.setFont(f)
            edt.setStyleSheet("background: {}; color: black;".format(bgColor))
            # edt.setGeometry(self.titleRect)
            return edt

        else:  # self.mainTextRect.contains(self.lastPos):
            # Summary
            self.editing = Outline.summaryFull
            edt = QPlainTextEdit(parent)
            edt.setFocusPolicy(Qt.StrongFocus)
            edt.setFrameShape(QFrame.NoFrame)
            try:
                # QPlainTextEdit.setPlaceholderText was introduced in Qt 5.3
                edt.setPlaceholderText(self.tr("Full summary"))
            except AttributeError:
                pass
            edt.setStyleSheet("background: {}; color: black;".format(bgColor))
            return edt
Beispiel #39
0
    def __init__(self):
        QsciLexerPython.__init__(self)
        for key, attrib in self.default_style.items():
            value = self.token_id[key]
            self.setColor(QColor(attrib[1]), value)
            self.setEolFill(True, value)
            self.setPaper(QColor(attrib[5]), value)
            self.setPaper(QColor(attrib[5]), value)

            font = QFont(attrib[0], attrib[2])
            font.setBold(attrib[3])
            font.setItalic(attrib[4])
            self.setFont(font, value)
        self.setDefaultPaper(QColor("#ffffff"))
Beispiel #40
0
 def setItemTextFormat(item, f):
     font = QFont(data.font)
     if f.hasProperty(QTextFormat.ForegroundBrush):
         item.setForeground(0, f.foreground().color())
     else:
         item.setForeground(0, data.baseColors['text'])
     if f.hasProperty(QTextFormat.BackgroundBrush):
         item.setBackground(0, f.background().color())
     else:
         item.setBackground(0, QBrush())
     font.setWeight(f.fontWeight())
     font.setItalic(f.fontItalic())
     font.setUnderline(f.fontUnderline())
     item.setFont(0, font)
Beispiel #41
0
 def __init__ (self, font):
     basefont = font
     boldfont = QFont(basefont)
     boldfont.setBold(True)
     italicfont = QFont(basefont)
     italicfont.setItalic(True)
     self.basefont = basefont
     self.boldfont = boldfont
     self.italicfont = italicfont
     
     basemetrics = QFontMetrics(basefont)
     self.basemetrics = basemetrics
     baseem = basemetrics.height()
     baseen = baseem // 2
     
     boldmetrics = QFontMetrics(boldfont)
     self.boldheight = boldmetrics.height()
     
     nodemargin = baseen*3//5
     itemmargin = baseen//2
     activemargin = baseen*3//4
     selectmargin = activemargin//2
     self.nodemargin = nodemargin
     self.itemmargin = itemmargin
     self.activemargin = activemargin
     self.selectmargin = selectmargin
     self.shadowoffset = selectmargin
     
     self.nodemargins = QMarginsF(*(nodemargin,)*4)
     self.banknodemargins = QMarginsF(*(nodemargin//2,)*4)
     self.itemmargins = QMarginsF(*(itemmargin,)*4)
     self.activemargins = QMarginsF(*(selectmargin//2,)*4)
     self.selectmargins = QMarginsF(*(selectmargin//2,)*4)
     
     self.nodetextwidth = basemetrics.averageCharWidth()*40
     
     nodewidth = self.nodetextwidth + 2*(activemargin+nodemargin+itemmargin)
     self.nodewidth = nodewidth
     
     rankgap = 7*activemargin
     self.rankgap = rankgap
     self.rankwidth = rankgap + nodewidth
     
     rowgap = 3*activemargin
     self.rowgap = rowgap
     
     # Edge style
     self.pensize = self.shadowoffset
     self.arrowsize = self.pensize * 3.5
Beispiel #42
0
    def createWidgets(self):
        self.title = QLabel("Welcome!")
        titleFont = QFont()
        titleFont.setPointSize(36)
        titleFont.setItalic(True)
        self.title.setFont(titleFont)

        self.subtitle = QLabel("Before we begin the experiment, please fill the following details. Those details will be kept completely confidential and used for the sole purpose of the experiment.")
        self.subtitle.setWordWrap(True)

        self.idLabel = QLabel("&Identification number")
        self.idLineEdit = QLineEdit()
        # TODO add validation
        regexp = QRegExp('^\d{8,9}$')
        validator = QRegExpValidator(regexp)
        self.idLineEdit.setValidator(validator)
        self.idLabel.setBuddy(self.idLineEdit)

        self.ageLabel = QLabel("&Age:")
        self.ageSpinBox = QSpinBox()
        self.ageSpinBox.setRange(16, 80)
        self.ageSpinBox.setValue(20)
        self.ageLabel.setBuddy(self.ageSpinBox)

        self.genderLabel = QLabel("&Gender:")
        self.maleRadioButton = QRadioButton("Male")
        self.femaleRadioButton = QRadioButton("Female")
        self.genderButtonGroup = QButtonGroup()
        self.genderButtonGroup.addButton(self.maleRadioButton, 1)
        self.genderButtonGroup.addButton(self.femaleRadioButton, 2)
        self.genderLayout = QHBoxLayout()
        self.genderLayout.addWidget(self.maleRadioButton)
        self.genderLayout.addWidget(self.femaleRadioButton)
        self.genderLabel.setBuddy(self.maleRadioButton)

        self.fieldLabel = QLabel("Primary &field of studies:")
        field_list = ["--- Please select ---",
                      "Industrial Engineering",
                      "Electrical Engineering",
                      "Electrical Engineering & Computer Science",
                      "Electrical Engineering & Physics",
                      "Mechanical Engineering",
                      "Biomedical Engineering",
                      "Environmental Engineering"]
        self.fieldComboBox = QComboBox()
        self.fieldComboBox.addItems(field_list)
        self.fieldLabel.setBuddy(self.fieldComboBox)
    def data(self, index, role=Qt.DisplayRole):
        row = index.row()
        if row >= len(self.message_type):
            return

        label = self.message_type[row]

        if role == Qt.DisplayRole:
            return label.name
        elif role == Qt.CheckStateRole:
            return label.show
        elif role == Qt.BackgroundColorRole:
            return constants.LABEL_COLORS[label.color_index]
        elif role == Qt.FontRole:
            font = QFont()
            font.setItalic(label.field_type is None)
            return font
Beispiel #44
0
def tuple_to_qfont(tup):
    """
    Create a QFont from tuple:
        (family [string], size [int], italic [bool], bold [bool])
    """
    if not isinstance(tup, tuple) or len(tup) != 4 \
       or not font_is_installed(tup[0]) \
       or not isinstance(tup[1], int) \
       or not isinstance(tup[2], bool) \
       or not isinstance(tup[3], bool):
        return None
    font = QFont()
    family, size, italic, bold = tup
    font.setFamily(family)
    font.setPointSize(size)
    font.setItalic(italic)
    font.setBold(bold)
    return font
Beispiel #45
0
    def data(self, column, role=Qt.DisplayRole):

        # print("Data: ", column, role)

        if role == Qt.DisplayRole or role == Qt.EditRole:
            # if column == Outline.compile.value:
            # return self.data(column, Qt.CheckStateRole)

            if Outline(column) in self._data:
                return self._data[Outline(column)]

            elif column == Outline.revisions.value:
                return []

            else:
                return ""

        elif role == Qt.DecorationRole and column == Outline.title.value:
            if self.isFolder():
                return QIcon.fromTheme("folder")
            elif self.isMD():
                return QIcon.fromTheme("text-x-generic")

                # elif role == Qt.ForegroundRole:
                # if self.isCompile() in [0, "0"]:
                # return QBrush(Qt.gray)

        elif role == Qt.CheckStateRole and column == Outline.compile.value:
            # print(self.title(), self.compile())
            # if self._data[Outline(column)] and not self.compile():
            # return Qt.PartiallyChecked
            # else:
            return self._data[Outline(column)]

        elif role == Qt.FontRole:
            f = QFont()
            if column == Outline.wordCount.value and self.isFolder():
                f.setItalic(True)
            elif column == Outline.goal.value and self.isFolder() and self.data(Outline.setGoal) == None:
                f.setItalic(True)
            if self.isFolder():
                f.setBold(True)
            return f
Beispiel #46
0
    def apply_to(cls, lexer):
        # Apply a font for all styles
        font = QFont(DEFAULT_FONT, DEFAULT_FONT_SIZE)
        font.setBold(False)
        font.setItalic(False)
        lexer.setFont(font)

        for name, font in cls.__dict__.items():
            if not isinstance(font, Font):
                continue
            style_num = getattr(lexer, name)
            lexer.setColor(QColor(font.color), style_num)
            lexer.setEolFill(True, style_num)
            lexer.setPaper(QColor(font.paper), style_num)
            if font.bold or font.italic:
                f = QFont(DEFAULT_FONT, DEFAULT_FONT_SIZE)
                f.setBold(font.bold)
                f.setItalic(font.italic)
                lexer.setFont(f, style_num)
Beispiel #47
0
    def data(self, index: QModelIndex, role=Qt.DisplayRole):
        if not index.isValid():
            return None

        i = index.row()
        j = index.column()
        if role == Qt.DisplayRole and self.display_data:
            try:
                alignment_offset = self.get_alignment_offset_at(i)
                if j < alignment_offset:
                    return self.ALIGNMENT_CHAR

                if self.proto_view == 0:
                    return self.display_data[i][j - alignment_offset]
                elif self.proto_view == 1:
                    return "{0:x}".format(self.display_data[i][j - alignment_offset])
                elif self.proto_view == 2:
                    return chr(self.display_data[i][j - alignment_offset])
            except IndexError:
                return None

        elif role == Qt.TextAlignmentRole:
            if i in self.first_messages:
                return Qt.AlignHCenter + Qt.AlignBottom
            else:
                return Qt.AlignCenter

        elif role == Qt.BackgroundColorRole:
            return self.background_colors[i, j]

        elif role == Qt.FontRole:
            font = QFont()
            font.setBold(self.bold_fonts[i, j])
            font.setItalic(self.italic_fonts[i, j])
            return font

        elif role == Qt.TextColorRole:
            return self.text_colors[i, j]

        elif role == Qt.ToolTipRole:
            return self.get_tooltip(i, j)
        else:
            return None
Beispiel #48
0
    def createEditor(self, parent, option, index):
        self.updateRects(option, index)

        if self.mainLineRect.contains(self.lastPos):
            # One line summary
            self.editing = Outline.summarySentence
            edt = QLineEdit(parent)
            edt.setFocusPolicy(Qt.StrongFocus)
            edt.setFrame(False)
            edt.setAlignment(Qt.AlignCenter)
            edt.setPlaceholderText(self.tr("One line summary"))
            f = QFont(option.font)
            f.setItalic(True)
            edt.setFont(f)
            return edt

        elif self.titleRect.contains(self.lastPos):
            # Title
            self.editing = Outline.title
            edt = QLineEdit(parent)
            edt.setFocusPolicy(Qt.StrongFocus)
            edt.setFrame(False)
            f = QFont(option.font)
            # f.setPointSize(f.pointSize() + 1)
            f.setBold(True)
            edt.setFont(f)
            edt.setAlignment(Qt.AlignCenter)
            # edt.setGeometry(self.titleRect)
            return edt

        else:  # self.mainTextRect.contains(self.lastPos):
            # Summary
            self.editing = Outline.summaryFull
            edt = QPlainTextEdit(parent)
            edt.setFocusPolicy(Qt.StrongFocus)
            edt.setFrameShape(QFrame.NoFrame)
            try:
                # QPlainTextEdit.setPlaceholderText was introduced in Qt 5.3
                edt.setPlaceholderText(self.tr("Full summary"))
            except AttributeError:
                pass
            return edt
Beispiel #49
0
 def defaultFont(self, style):
     """
     Public method to get the default font for a style.
     
     @param style style number (integer)
     @return font (QFont)
     """
     if style in [PYGMENTS_COMMENT, PYGMENTS_PREPROCESSOR,
                  PYGMENTS_MULTILINECOMMENT]:
         if Utilities.isWindowsPlatform():
             f = QFont("Comic Sans MS", 9)
         else:
             f = QFont("Bitstream Vera Serif", 9)
         if style == PYGMENTS_PREPROCESSOR:
             f.setItalic(True)
         return f
     
     if style in [PYGMENTS_STRING, PYGMENTS_CHAR]:
         if Utilities.isWindowsPlatform():
             return QFont("Comic Sans MS", 10)
         else:
             return QFont("Bitstream Vera Serif", 10)
     
     if style in [PYGMENTS_KEYWORD, PYGMENTS_OPERATOR, PYGMENTS_WORD,
                  PYGMENTS_BUILTIN, PYGMENTS_ATTRIBUTE, PYGMENTS_FUNCTION,
                  PYGMENTS_CLASS, PYGMENTS_NAMESPACE, PYGMENTS_EXCEPTION,
                  PYGMENTS_ENTITY, PYGMENTS_TAG, PYGMENTS_SCALAR,
                  PYGMENTS_ESCAPE, PYGMENTS_HEADING, PYGMENTS_SUBHEADING,
                  PYGMENTS_STRONG, PYGMENTS_PROMPT]:
         f = LexerContainer.defaultFont(self, style)
         f.setBold(True)
         return f
     
     if style in [PYGMENTS_DOCSTRING, PYGMENTS_EMPHASIZE]:
         f = LexerContainer.defaultFont(self, style)
         f.setItalic(True)
         return f
     
     return LexerContainer.defaultFont(self, style)
Beispiel #50
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                if source_data is not "":
                    amount_ref = self.account.units_to_diff_ref(source_data,
                                                                self.community)
                    # if referential type is quantitative...
                    if self.account.ref_type() == 'q':
                        # display int values
                        return QLocale().toString(float(amount_ref), 'f', 0)
                    else:
                        # display float values
                        return QLocale().toString(amount_ref, 'f', 6)

        if role == Qt.FontRole:
            font = QFont()
            if state_data == Transfer.AWAITING:
                font.setItalic(True)
            elif state_data == Transfer.REFUSED:
                font.setItalic(True)
            elif state_data == Transfer.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == Transfer.REFUSED:
                return QColor(Qt.red)
            elif state_data == Transfer.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)

        return source_data
Beispiel #51
0
    def paint(self, p, option, index):
        # QStyledItemDelegate.paint(self, p, option, index)
        if not index.isValid():
            return

        item = index.internalPointer()
        self.updateRects(option, index)
        colors = outlineItemColors(item)

        style = qApp.style()

        def _rotate(angle):
            p.translate(self.mainRect.center())
            p.rotate(angle)
            p.translate(-self.mainRect.center())

        # Draw background
        cg = QPalette.ColorGroup(QPalette.Normal if option.state & QStyle.State_Enabled else QPalette.Disabled)
        if cg == QPalette.Normal and not option.state & QStyle.State_Active:
            cg = QPalette.Inactive

            # Selection
        if option.state & QStyle.State_Selected:
            p.save()
            p.setBrush(option.palette.brush(cg, QPalette.Highlight))
            p.setPen(Qt.NoPen)
            p.drawRoundedRect(option.rect, 12, 12)
            p.restore()

            # Stack
        if item.isFolder() and item.childCount() > 0:
            p.save()
            p.setBrush(Qt.white)
            for i in reversed(range(3)):
                p.drawRoundedRect(self.itemRect.adjusted(2 * i, 2 * i, -2 * i, 2 * i), 10, 10)

            p.restore()

            # Background
        itemRect = self.itemRect
        p.save()
        if settings.viewSettings["Cork"]["Background"] != "Nothing":
            c = colors[settings.viewSettings["Cork"]["Background"]]
            col = mixColors(c, QColor(Qt.white), .2)
            p.setBrush(col)
        else:
            p.setBrush(Qt.white)
        pen = p.pen()
        pen.setWidth(2)
        p.setPen(pen)
        p.drawRoundedRect(itemRect, 10, 10)
        p.restore()

        # Title bar
        topRect = self.topRect
        p.save()
        if item.isFolder():
            color = QColor(Qt.darkGreen)
        else:
            color = QColor(Qt.blue).lighter(175)
        p.setPen(Qt.NoPen)
        p.setBrush(color)
        p.setClipRegion(QRegion(topRect))
        p.drawRoundedRect(itemRect, 10, 10)
        # p.drawRect(topRect)
        p.restore()

        # Label color
        if settings.viewSettings["Cork"]["Corner"] != "Nothing":
            p.save()
            color = colors[settings.viewSettings["Cork"]["Corner"]]
            p.setPen(Qt.NoPen)
            p.setBrush(color)
            p.setClipRegion(QRegion(self.labelRect))
            p.drawRoundedRect(itemRect, 10, 10)
            # p.drawRect(topRect)
            p.restore()
            p.drawLine(self.labelRect.topLeft(), self.labelRect.bottomLeft())

            # One line summary background
        lineSummary = item.data(Outline.summarySentance.value)
        fullSummary = item.data(Outline.summaryFull.value)
        if lineSummary or not fullSummary:
            m = self.margin
            r = self.mainLineRect.adjusted(-m, -m, m, m / 2)
            p.save()
            p.setPen(Qt.NoPen)
            p.setBrush(QColor("#EEE"))
            p.drawRect(r)
            p.restore()

            # Border
        p.save()
        p.setBrush(Qt.NoBrush)
        pen = p.pen()
        pen.setWidth(2)
        if settings.viewSettings["Cork"]["Border"] != "Nothing":
            col = colors[settings.viewSettings["Cork"]["Border"]]
            if col == Qt.transparent:
                col = Qt.black
            pen.setColor(col)
        p.setPen(pen)
        p.drawRoundedRect(itemRect, 10, 10)
        p.restore()

        # Draw the icon
        iconRect = self.iconRect
        mode = QIcon.Normal
        if not option.state & style.State_Enabled:
            mode = QIcon.Disabled
        elif option.state & style.State_Selected:
            mode = QIcon.Selected
        # index.data(Qt.DecorationRole).paint(p, iconRect, option.decorationAlignment, mode)
        icon = index.data(Qt.DecorationRole).pixmap(iconRect.size())
        if settings.viewSettings["Cork"]["Icon"] != "Nothing":
            color = colors[settings.viewSettings["Cork"]["Icon"]]
            colorifyPixmap(icon, color)
        QIcon(icon).paint(p, iconRect, option.decorationAlignment, mode)

        # Draw title
        p.save()
        text = index.data()
        titleRect = self.titleRect
        if text:
            if settings.viewSettings["Cork"]["Text"] != "Nothing":
                col = colors[settings.viewSettings["Cork"]["Text"]]
                if col == Qt.transparent:
                    col = Qt.black
                p.setPen(col)
            f = QFont(option.font)
            # f.setPointSize(f.pointSize() + 1)
            f.setBold(True)
            p.setFont(f)
            fm = QFontMetrics(f)
            elidedText = fm.elidedText(text, Qt.ElideRight, titleRect.width())
            p.drawText(titleRect, Qt.AlignCenter, elidedText)
        p.restore()

        # Draw the line
        bottomRect = self.bottomRect
        p.save()
        # p.drawLine(itemRect.x(), iconRect.bottom() + margin,
        # itemRect.right(), iconRect.bottom() + margin)
        p.drawLine(bottomRect.topLeft(), bottomRect.topRight())
        p.restore()

        # Lines
        if True:
            p.save()
            p.setPen(QColor("#EEE"))
            fm = QFontMetrics(option.font)
            h = fm.lineSpacing()
            l = self.mainTextRect.topLeft() + QPoint(0, h)
            while self.mainTextRect.contains(l):
                p.drawLine(l, QPoint(self.mainTextRect.right(), l.y()))
                l.setY(l.y() + h)
            p.restore()

        # Draw status
        mainRect = self.mainRect
        status = item.data(Outline.status.value)
        if status:
            it = mainWindow().mdlStatus.item(int(status), 0)
            if it != None:
                p.save()
                p.setClipRegion(QRegion(mainRect))
                f = p.font()
                f.setPointSize(f.pointSize() + 12)
                f.setBold(True)
                p.setFont(f)
                p.setPen(QColor(Qt.red).lighter(175))
                _rotate(-35)
                p.drawText(mainRect, Qt.AlignCenter, it.text())
                p.restore()

                # Draw Summary
                # One line
        if lineSummary:
            p.save()
            f = QFont(option.font)
            f.setItalic(True)
            p.setFont(f)
            fm = QFontMetrics(f)
            elidedText = fm.elidedText(lineSummary, Qt.ElideRight, self.mainLineRect.width())
            p.drawText(self.mainLineRect, Qt.AlignCenter, elidedText)
            p.restore()

            # Full summary
        if fullSummary:
            p.setFont(option.font)
            p.drawText(self.mainTextRect, Qt.TextWordWrap, fullSummary)
Beispiel #52
0
    def setupTextActions(self):
        tb = QToolBar(self)
        tb.setWindowTitle("Format Actions")
        self.addToolBar(tb)

        menu = QMenu("F&ormat", self)
        self.menuBar().addMenu(menu)

        self.actionTextBold = QAction(
                QIcon.fromTheme('format-text-bold',
                        QIcon(rsrcPath + '/textbold.png')),
                "&Bold", self, priority=QAction.LowPriority,
                shortcut=Qt.CTRL + Qt.Key_B, triggered=self.textBold,
                checkable=True)
        bold = QFont()
        bold.setBold(True)
        self.actionTextBold.setFont(bold)
        tb.addAction(self.actionTextBold)
        menu.addAction(self.actionTextBold)

        self.actionTextItalic = QAction(
                QIcon.fromTheme('format-text-italic',
                        QIcon(rsrcPath + '/textitalic.png')),
                "&Italic", self, priority=QAction.LowPriority,
                shortcut=Qt.CTRL + Qt.Key_I, triggered=self.textItalic,
                checkable=True)
        italic = QFont()
        italic.setItalic(True)
        self.actionTextItalic.setFont(italic)
        tb.addAction(self.actionTextItalic)
        menu.addAction(self.actionTextItalic)

        self.actionTextUnderline = QAction(
                QIcon.fromTheme('format-text-underline',
                        QIcon(rsrcPath + '/textunder.png')),
                "&Underline", self, priority=QAction.LowPriority,
                shortcut=Qt.CTRL + Qt.Key_U, triggered=self.textUnderline,
                checkable=True)
        underline = QFont()
        underline.setUnderline(True)
        self.actionTextUnderline.setFont(underline)
        tb.addAction(self.actionTextUnderline)
        menu.addAction(self.actionTextUnderline)

        menu.addSeparator()

        grp = QActionGroup(self, triggered=self.textAlign)

        # Make sure the alignLeft is always left of the alignRight.
        if QApplication.isLeftToRight():
            self.actionAlignLeft = QAction(
                    QIcon.fromTheme('format-justify-left',
                            QIcon(rsrcPath + '/textleft.png')),
                    "&Left", grp)
            self.actionAlignCenter = QAction(
                    QIcon.fromTheme('format-justify-center',
                            QIcon(rsrcPath + '/textcenter.png')),
                    "C&enter", grp)
            self.actionAlignRight = QAction(
                    QIcon.fromTheme('format-justify-right',
                            QIcon(rsrcPath + '/textright.png')),
                    "&Right", grp)
        else:
            self.actionAlignRight = QAction(
                    QIcon.fromTheme('format-justify-right',
                            QIcon(rsrcPath + '/textright.png')),
                    "&Right", grp)
            self.actionAlignCenter = QAction(
                    QIcon.fromTheme('format-justify-center',
                            QIcon(rsrcPath + '/textcenter.png')),
                    "C&enter", grp)
            self.actionAlignLeft = QAction(
                    QIcon.fromTheme('format-justify-left',
                            QIcon(rsrcPath + '/textleft.png')),
                    "&Left", grp)
 
        self.actionAlignJustify = QAction(
                QIcon.fromTheme('format-justify-fill',
                        QIcon(rsrcPath + '/textjustify.png')),
                "&Justify", grp)

        self.actionAlignLeft.setShortcut(Qt.CTRL + Qt.Key_L)
        self.actionAlignLeft.setCheckable(True)
        self.actionAlignLeft.setPriority(QAction.LowPriority)

        self.actionAlignCenter.setShortcut(Qt.CTRL + Qt.Key_E)
        self.actionAlignCenter.setCheckable(True)
        self.actionAlignCenter.setPriority(QAction.LowPriority)

        self.actionAlignRight.setShortcut(Qt.CTRL + Qt.Key_R)
        self.actionAlignRight.setCheckable(True)
        self.actionAlignRight.setPriority(QAction.LowPriority)

        self.actionAlignJustify.setShortcut(Qt.CTRL + Qt.Key_J)
        self.actionAlignJustify.setCheckable(True)
        self.actionAlignJustify.setPriority(QAction.LowPriority)

        tb.addActions(grp.actions())
        menu.addActions(grp.actions())
        menu.addSeparator()

        pix = QPixmap(16, 16)
        pix.fill(Qt.black)
        self.actionTextColor = QAction(QIcon(pix), "&Color...", self,
                triggered=self.textColor)
        tb.addAction(self.actionTextColor)
        menu.addAction(self.actionTextColor)

        tb = QToolBar(self)
        tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea)
        tb.setWindowTitle("Format Actions")
        self.addToolBarBreak(Qt.TopToolBarArea)
        self.addToolBar(tb)

        comboStyle = QComboBox(tb)
        tb.addWidget(comboStyle)
        comboStyle.addItem("Standard")
        comboStyle.addItem("Bullet List (Disc)")
        comboStyle.addItem("Bullet List (Circle)")
        comboStyle.addItem("Bullet List (Square)")
        comboStyle.addItem("Ordered List (Decimal)")
        comboStyle.addItem("Ordered List (Alpha lower)")
        comboStyle.addItem("Ordered List (Alpha upper)")
        comboStyle.addItem("Ordered List (Roman lower)")
        comboStyle.addItem("Ordered List (Roman upper)")
        comboStyle.activated.connect(self.textStyle)

        self.comboFont = QFontComboBox(tb)
        tb.addWidget(self.comboFont)
        self.comboFont.activated[str].connect(self.textFamily)

        self.comboSize = QComboBox(tb)
        self.comboSize.setObjectName("comboSize")
        tb.addWidget(self.comboSize)
        self.comboSize.setEditable(True)

        db = QFontDatabase()
        for size in db.standardSizes():
            self.comboSize.addItem("%s" % (size))

        self.comboSize.activated[str].connect(self.textSize)
        self.comboSize.setCurrentIndex(
                self.comboSize.findText(
                        "%s" % (QApplication.font().pointSize())))
Beispiel #53
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 #54
0
class SubtitleItemText(QGraphicsTextItem):

    def __init__(self, parent = None):
        super().__init__()
        self.parent = parent

        self.font = QFont(settings().value("Subtitle/font") or "Noto Serif", 20)
        self.setDefaultTextColor(settings().value("Subtitle/color") or QColor("white"))
        self.setFont(self.font)

    def settingsChanged(self):
        self.font = QFont(settings().value("Subtitle/font") or "Noto Serif", 20)
        self.setDefaultTextColor(settings().value("Subtitle/color") or QColor("white"))
        self.setFont(self.font)

    def paint(self, painter, op, wi):
        if self.toPlainText() != "":
            painter.setBrush(settings().value("Player/subtitle_background") or QColor(0, 0, 0, 130))
            painter.setPen(settings().value("Player/subtitle_background") or QColor(0, 0, 0, 130))
            x, y, w, h = self.boundingRect().x(), self.boundingRect().y()+5, self.boundingRect().width(), self.boundingRect().height()-5
            painter.drawRect(x, y, w, h)
        super().paint(painter, op, wi)

    def addSubtitle(self, subtitle):
        self.subtitle_file = subtitle
        self.subtitle_list = SubtitleParse(subtitle, settings().value("Subtitle/codec") or "ISO 8859-9").parse()

    def reParse(self, codec):
        self.subtitle_list = SubtitleParse(self.subtitle_file, codec).parse()

    def subtitleControl(self, content):
        srt = content.canonicalUrl().toLocalFile().split(".")
        srt.pop(-1)
        srt.append("srt")
        srt = ".".join(srt)
        if QFile.exists(srt):
            self.subtitle_file = srt
            self.subtitle_list = SubtitleParse(srt, settings().value("Subtitle/codec") or "ISO 8859-9").parse()
        else:
            self.subtitle_list = None


    compile = re.compile(r"<(\w{1})><(\w{1})>(\w.+)<\/\w{1}><\/\w{1}>", re.S)
    def subtitleItemParse(self, subtitle):
        sub = self.compile.search(subtitle)

        if sub:
            self.font.setItalic(True)
            self.font.setBold(True)
            self.setFont(self.font)
            self.setPlainText(sub.groups()[2])

        elif subtitle.startswith("<b>"):
            self.font.setBold(True)
            self.font.setItalic(False)
            self.setFont(self.font)
            self.setPlainText(subtitle[3:].split("<")[0])

        elif subtitle.startswith("<i>"):
            self.font.setItalic(True)
            self.font.setBold(False)
            self.setFont(self.font)
            self.setPlainText(subtitle[3:-4].split("<")[0])

        else:
            self.font.setBold(False)
            self.font.setItalic(False)
            self.setFont(self.font)
            self.setPlainText(subtitle)

        self.setPos((self.parent.size().width() - self.document().size().width()) / 2, self.parent.size().height() - 150)


    def positionValue(self, pos):
        if self.subtitle_list:
            for ctime, ltime, subtitle in self.subtitle_list:
                if pos - ctime >= 100 and ltime - pos >= 100:
                    self.subtitleItemParse(subtitle)
                    break

                else:
                    self.setPlainText("")
Beispiel #55
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = IdentitiesTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_UNKNOWN = 2
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data == 0:
                status = STATUS_UNKNOWN
            elif expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (IdentitiesTableModel.columns_ids.index('renewed'),
                                             IdentitiesTableModel.columns_ids.index('expiration')):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.LongFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('pubkey'):
                    return source_data
                if source_index.column() == IdentitiesTableModel.columns_ids.index('block'):
                    return str(source_data)[:20]

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                elif status == STATUS_UNKNOWN:
                    return QColor(Qt.black)
                else:
                    return QColor(Qt.blue)

            if role == Qt.FontRole and status == STATUS_UNKNOWN:
                font = QFont()
                font.setItalic(True)
                return font

            if role == Qt.DecorationRole and source_index.column() == IdentitiesTableModel.columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Beispiel #56
0
class DPlayerUI(QWidget):
    def __init__(self):
        """Initializes core and ui"""
        super().__init__()

        self.playerCore = DPlayerCore()
        self.player = self.playerCore.player
        self.playlist = self.playerCore.playlist
        self.initUI()
        self.connectSignals()

    def initUI(self):
        """Initialize user interface - buttons, sliders, labels, playlist."""
        self.grid = QGridLayout()

        self.initButtons()
        self.initVolumeSlider()
        self.initPositionSlider()
        self.initDurationLabel()
        self.initPlaylist()
        self.initSongLabel()

        self.setLayout(self.grid)
        self.setGeometry(0, 0, 700, 700)
        self.setWindowTitle('DPlayer')
        self.setWindowIcon(QIcon('icons/logo.png'))
        self.center()
        self.show()

    def connectSignals(self):
        """Connect player signals to functions."""
        self.player.durationChanged.connect(self.durationChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.stateChanged.connect(self.stateChanged)
        self.player.currentMediaChanged.connect(self.songChanged)

    def initButtons(self):
        """Create, set and connect buttons."""
        self.buttons = {}
        self.buttonNames = ['stop', 'previous', 'play', 'next', 'mute',
                            'addFiles', 'addFolder', 'shuffle',
                            'repeatPlaylist', 'repeatSong', 'Save playlist',
                            'Load playlist', 'Clear playlist', 'Find lyrics',
                            'Find info', 'Login', 'Logout', 'Love', 'Unlove']
        shortcuts = ['q', 'w', 'e', 'r', 't', 'a', 's', 'd', 'f', 'g', 'z',
                     'x', 'c', 'v', 'b', 'o', 'p', 'k', 'l']

        for name, cut in zip(self.buttonNames, shortcuts):
            button = QPushButton(self)
            button.setToolTip(name)
            button.setShortcut(QKeySequence(cut))
            self.buttons[name] = button

        for name in self.buttonNames[:10]:
            self.buttons[name].setIcon(QIcon('icons/{}.png'.format(name)))
            self.buttons[name].setIconSize(QSize(20, 20))

        for name, position in zip(self.buttonNames[:5], range(5)):
            self.grid.addWidget(self.buttons[name], 1, position)

        self.buttons['stop'].clicked.connect(self.stopClicked)
        self.buttons['previous'].clicked.connect(self.previousClicked)
        self.previousButtonClicked = False
        self.buttons['play'].clicked.connect(self.playClicked)
        self.buttons['play'].setFocus()
        self.buttons['next'].clicked.connect(self.nextClicked)
        self.buttons['mute'].clicked.connect(self.muteClicked)
        self.buttons['mute'].setIcon(QIcon('icons/volumeMiddle.png'))

        for name, position in zip(self.buttonNames[5:], range(5)):
            self.grid.addWidget(self.buttons[name], 3, position)

        self.buttons['addFiles'].clicked.connect(self.addFiles)
        self.buttons['addFolder'].clicked.connect(self.addFolder)
        self.buttons['shuffle'].clicked[bool].connect(self.playerCore.shuffle)
        self.buttons['shuffle'].setCheckable(True)
        self.buttons['repeatPlaylist'].clicked[bool].connect(
            self.playerCore.repeatPlaylist)
        self.buttons['repeatPlaylist'].setCheckable(True)
        self.buttons['repeatSong'].clicked[bool].connect(
            self.playerCore.repeatSong)
        self.buttons['repeatSong'].setCheckable(True)

        for name, position in zip(self.buttonNames[10:15], range(5)):
            self.buttons[name].setIcon(QIcon('icons/{}.png'.format(name)))
            self.buttons[name].setIconSize(QSize(120, 20))
            self.grid.addWidget(self.buttons[name], 4, position)

        self.buttons['Save playlist'].clicked.connect(self.savePlaylist)
        self.buttons['Load playlist'].clicked.connect(self.loadPlaylist)
        self.buttons['Clear playlist'].clicked.connect(self.clearPlaylist)
        self.buttons['Find lyrics'].clicked.connect(self.findLyrics)
        self.buttons['Find info'].clicked.connect(self.findInfo)

        self.lastFMbuttons = QDialogButtonBox()
        self.lastFMbuttons.setOrientation(Qt.Vertical)
        for name, position in zip(self.buttonNames[15:], range(4)):
            self.buttons[name].setIcon(QIcon('icons/{}.png'.format(name)))
            self.buttons[name].setIconSize(QSize(120, 20))
            self.lastFMbuttons.addButton(self.buttons[name],
                                         QDialogButtonBox.ActionRole)
        self.grid.addWidget(self.lastFMbuttons, 2, 4, Qt.AlignCenter)

        # self.userLabel = QLabel('Username:\n')
        # self.userLabel.setBuddy(self.buttons['Login'])
        # self.grid.addWidget(
        #     self.userLabel, 2, 4, Qt.AlignTop | Qt.AlignHCenter)
        self.buttons['Login'].clicked.connect(self.login)
        self.buttons['Logout'].clicked.connect(self.logout)
        self.buttons['Love'].clicked.connect(self.love)
        self.buttons['Unlove'].clicked.connect(self.unlove)

    def previousClicked(self):
        """Play previous song."""
        self.playerCore.songChanged = True
        self.previousButtonClicked = True
        self.playerCore.previous()
        self.stateChanged()

    def stopClicked(self):
        """Stop the player. Set icon to play button."""
        self.playerCore.stop()
        self.buttons['play'].setIcon(QIcon('icons/play.png'))
        self.buttons['play'].setToolTip('play')
        self.songLabel.setText('')

    def playClicked(self):
        """Play / Pause the player. Set icon to play button."""
        if self.player.state() in (QMediaPlayer.StoppedState,
                                   QMediaPlayer.PausedState):
            self.playerCore.play()
            if self.player.state() == QMediaPlayer.PlayingState:
                self.buttons['play'].setIcon(QIcon('icons/pause.png'))
                self.buttons['play'].setToolTip('pause')
        else:   # QMediaPlayer.PlayingState
            self.playerCore.pause()
            self.buttons['play'].setIcon(QIcon('icons/play.png'))
            self.buttons['play'].setToolTip('play')

        self.songLabel.setText('{} - {}'.format(
            self.playlistTable.item(self.currentPlaying, 0).text(),
            self.playlistTable.item(self.currentPlaying, 1).text()))

    def nextClicked(self):
        """Play next song."""
        self.playerCore.next()
        self.stateChanged()

    def muteClicked(self):
        """Mute / Unmute the player. Set volume slider position."""
        if self.playerCore.isMuted():
            self.playerCore.unmute()
            self.volumeChanged(self.currentVolume)
        else:
            self.playerCore.mute()
            self.volumeChanged(0)

    def addFiles(self):
        """Choose files (*.mp3) to add to the playlist."""
        fileNames, _ = QFileDialog.getOpenFileNames(
            self, 'Add songs', filter='Music (*.mp3 *.ogg *.flac *wav)')
        self.playerCore.add(fileNames)
        self.addClicked(fileNames)

    def addFolder(self):
        """Choose folder to add to the playlist."""
        directory = QFileDialog.getExistingDirectory(self, 'Add a folder')
        self.getFromDir(directory)

    def getFromDir(self, directory):
        """Extract files from directory and add them to the playlist."""
        if not directory:
            return

        dirContent = os.listdir(directory)
        fileNames = []
        for file in dirContent:
            path = '{}/{}'.format(directory, file)
            if os.path.isfile(path) and \
                    path[len(path) - 4:] in ['.mp3', '.ogg', 'flac', '.wav']:
                fileNames.append(path)
            elif os.path.isdir(path):
                self.getFromDir(path)
        self.playerCore.add(fileNames)
        self.addClicked(fileNames)

    def addClicked(self, fileNames):
        """Fill the playlist with fileNames' info."""
        if fileNames is None:
            return
        self.playlistTable.setSortingEnabled(False)
        songsToAdd = len(fileNames)
        for name, row in zip(fileNames, range(songsToAdd)):
            currentRow = row + self.playlist.mediaCount() - songsToAdd
            self.playlistTable.insertRow(currentRow)

            artist = self.playerCore.getArtist(name)[0]
            title = self.playerCore.getTitle(name)[0]
            album = self.playerCore.getAlbum(name)[0]
            seconds = self.playerCore.getDuration(name)
            duration = QTime(0, seconds // 60, seconds % 60)
            duration = duration.toString('mm:ss')

            rowInfo = [artist, title, album, duration]
            for info, index in zip(rowInfo, range(4)):
                cell = QTableWidgetItem(info)
                self.playlistTable.setItem(currentRow, index, cell)
                font = QFont(info, weight=QFont.Normal)
                cell.setFont(font)
                cell.setTextAlignment(Qt.AlignCenter)
        self.playlistTable.setSortingEnabled(True)

        for index in range(4):
            self.playlistTable.resizeColumnToContents(index)

    def initVolumeSlider(self):
        """Initialize volume slider."""
        self.volumeSlider = QSlider(Qt.Vertical, self)
        self.volumeSlider.setRange(0, 100)
        self.currentVolume = 70
        self.volumeSlider.setValue(self.currentVolume)
        self.volumeSlider.setToolTip('volume: {}'.format(self.currentVolume))
        self.volumeSlider.valueChanged[int].connect(self.volumeChanged)
        self.grid.addWidget(self.volumeSlider, 0, 4, Qt.AlignHCenter)
        self.playerCore.setVolume(self.currentVolume)

    def volumeChanged(self, value):
        """Set player's volume to value. Set icon for sound."""
        self.playerCore.setVolume(value)

        if value == 0:
            self.buttons['mute'].setIcon(QIcon('icons/mute.png'))
        elif value <= 35:
            self.buttons['mute'].setIcon(QIcon('icons/volumeMin.png'))
        elif value <= 70:
            self.buttons['mute'].setIcon(QIcon('icons/volumeMiddle.png'))
        else:   # value <= 100
            self.buttons['mute'].setIcon(QIcon('icons/volumeMax.png'))

        self.volumeSlider.setValue(value)
        self.volumeSlider.setToolTip('volume: {}'.format(value))

        if self.playerCore.isMuted():
            self.buttons['mute'].setToolTip('unmute')
        else:
            self.currentVolume = value
            self.buttons['mute'].setToolTip('mute')

    def initPositionSlider(self):
        """Initialize position slider."""
        self.positionSlider = QSlider(Qt.Horizontal, self)
        self.positionSlider.setValue(0)
        self.positionSlider.valueChanged[int].connect(self.position)
        self.positionSliderClicked = False
        self.grid.addWidget(self.positionSlider, 0, 0, 1, 3, Qt.AlignBottom)

    def initDurationLabel(self):
        """Initialize duration label."""
        self.durationLabel = QLabel('00:00 / 00:00')
        self.grid.addWidget(self.durationLabel, 0, 3, Qt.AlignBottom)

    def durationChanged(self, value):
        """Set the maximum of position slider to value when song is changed."""
        self.positionSlider.setMaximum(value)

    def songChanged(self, _):
        """Handle UI when song changes."""
        if self.doubleClicked or self.playlist.mediaCount() == 0:
            self.doubleClicked = False
            return

        self.lastPlayed = self.currentPlaying
        self.currentPlaying = self.playlist.currentIndex()

        if self.currentPlaying >= 0:
            self.setStyle(self.currentPlaying, QFont.Bold)
            self.songLabel.setText('{} - {}'.format(
                self.playlistTable.item(self.currentPlaying, 0).text(),
                self.playlistTable.item(self.currentPlaying, 1).text()))

        self.playlistTable.scrollToItem(
            self.playlistTable.item(self.currentPlaying, 0))

        if self.lastPlayed >= 0 and self.lastPlayed != self.currentPlaying:
            self.setStyle(self.lastPlayed, QFont.Normal)

        for index in range(4):
            self.playlistTable.resizeColumnToContents(index)

        self.previousButtonClicked = False

    def setStyle(self, row, style):
        """Set row's font to style."""
        for idx in range(4):
                text = self.playlistTable.item(row, idx).text()
                font = QFont(text, weight=style)
                self.playlistTable.item(row, idx).setFont(font)

    def position(self, value):
        """Set the position of player at value."""
        if not self.positionSliderClicked:
            self.positionSliderClicked = True
            self.player.setPosition(value)

    def positionChanged(self, value):
        """Update duration label according to value."""
        if not self.positionSliderClicked:
            self.positionSliderClicked = True
            self.positionSlider.setValue(value)
        self.positionSliderClicked = False

        songIndex = self.playlist.currentIndex()
        if songIndex >= 0:
            duration = self.playlistTable.item(
                self.playlist.currentIndex(), 3).text()
            currentSeconds = value // 1000
            currentTime = QTime(0, currentSeconds // 60, currentSeconds % 60)

            time = '{} / {}'.format(
                currentTime.toString('mm:ss'), duration)
        else:
            time = '00:00 / 00:00'

        self.durationLabel.setText(time)

    def stateChanged(self):
        """Check if stopped to update UI."""
        if self.player.state() == QMediaPlayer.StoppedState:
            self.stopClicked()

    def initSongLabel(self):
        """Initialize song label."""
        self.songLabel = QLabel()
        self.songLabel.setAlignment(Qt.AlignCenter)
        self.font = QFont()
        self.font.setBold(True)
        self.font.setItalic(True)
        self.font.setCapitalization(QFont.AllUppercase)
        self.font.setPixelSize(20)
        self.songLabel.setFont(self.font)
        self.grid.addWidget(self.songLabel, 0, 0, 1, 4, Qt.AlignVCenter)

    def initPlaylist(self):
        """Initialize song playlist."""
        self.playlistTable = QTableWidget()

        self.playlistTable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.playlistTable.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.playlistTable.setSortingEnabled(True)

        self.playlistTable.setTabKeyNavigation(False)
        self.playlistTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.playlistTable.setAlternatingRowColors(True)

        self.playlistTable.setVerticalScrollMode(
            QAbstractItemView.ScrollPerPixel)
        self.playlistTable.setHorizontalScrollMode(
            QAbstractItemView.ScrollPerPixel)

        self.playlistTable.itemDoubleClicked.connect(self.doubleClicked)
        self.doubleClicked = False
        self.lastPlayed = -1
        self.currentPlaying = -1
        delete = QShortcut(
            QKeySequence.Delete, self.playlistTable, self.deleteSongs)
        delete.setContext(Qt.WidgetShortcut)

        self.playlistTable.setColumnCount(4)
        self.playlistTable.setHorizontalHeaderLabels(
            ['Artist', 'Title', 'Album', 'Duration'])

        # False - ascending order, True - descending
        self.descendingOrder = [False] * 4
        self.playlistTable.horizontalHeader().sectionClicked.connect(
            self.toSort)

        self.windows = []

        names = []
        for index in range(self.playlist.mediaCount()):
            names.append(self.playlist.media(index).canonicalUrl().path())
        self.addClicked(names)

        self.grid.addWidget(self.playlistTable, 2, 0, 1, 4)
        self.grid.setRowStretch(2, 1)

    def doubleClicked(self, item):
        """Play song at item's row."""
        self.doubleClicked = True
        self.lastPlayed = self.playlist.currentIndex()
        if self.lastPlayed >= 0:
            self.setStyle(self.lastPlayed, QFont.Normal)

        self.currentPlaying = item.row()
        self.playerCore.songChanged = True

        self.playlist.setCurrentIndex(self.currentPlaying)
        self.setStyle(self.currentPlaying, QFont.Bold)
        self.stopClicked()
        self.playClicked()
        self.songLabel.setText('{} - {}'.format(
            self.playlistTable.item(self.currentPlaying, 0).text(),
            self.playlistTable.item(self.currentPlaying, 1).text()))

        for index in range(4):
            self.playlistTable.resizeColumnToContents(index)

    def toSort(self, column):
        """Sort music by column."""
        if self.lastPlayed >= 0:
            self.setStyle(self.lastPlayed, QFont.Normal)
        self.playerCore.sort(column, self.descendingOrder[column])
        self.descendingOrder[column] = bool(1 - self.descendingOrder[column])
        for index in range(4):
            if index != column:
                self.descendingOrder[index] = False

    def deleteSongs(self):
        """Delete selected songs."""
        selectedSongs = self.playlistTable.selectedIndexes()
        indexes = [index.row() for index in selectedSongs]
        toBeRemoved = sorted(indexes[::4], reverse=True)

        currentIndex = self.playlist.currentIndex()
        if currentIndex >= 0:
            self.setStyle(currentIndex, QFont.Normal)

        self.playerCore.remove(toBeRemoved)

        for index in toBeRemoved:
            self.playlistTable.removeRow(index)

        if self.playlistTable.rowCount() == 0:
            return

        currentIndex = self.playlist.currentIndex()
        if currentIndex >= 0:
            self.setStyle(self.playlist.currentIndex(), QFont.Bold)
            self.songLabel.setText('{} - {}'.format(
                self.playlistTable.item(self.currentPlaying, 0).text(),
                self.playlistTable.item(self.currentPlaying, 1).text()))

        for index in range(4):
            self.playlistTable.resizeColumnToContents(index)

    def savePlaylist(self):
        """Save playlist."""
        url, _ = QFileDialog.getSaveFileUrl(self, 'Save playlist')
        self.playerCore.savePlaylist(url)

    def loadPlaylist(self):
        """Load playlist."""
        url, _ = QFileDialog.getOpenFileUrl(
            self, 'Load playlist', filter='Playlists (*.m3u)')

        count = self.playlist.mediaCount()
        self.playerCore.loadPlaylist(url)

        names = []
        for index in range(count, self.playlist.mediaCount()):
            names.append(self.playlist.media(index).canonicalUrl().path())
        self.addClicked(names)

    def clearPlaylist(self):
        """Remove all music from playlist."""
        self.playlistTable.setRowCount(0)
        self.playerCore.clearPlaylist()

    def closeEvent(self, event):
        """Saves current playlist and quits."""
        self.playerCore.savePlaylist(QUrl(
            'file://{}/lastListened.m3u'.format(os.getcwd())))
        event.accept()

    def findLyrics(self):
        """Finds and shows lyrics for selected song(s)."""
        songs = self.playlistTable.selectedIndexes()[::4]
        if not songs:
            return

        for index in songs:
            name = '{} - {}'.format(self.playerCore.musicOrder[index.row()][1],
                                    self.playerCore.musicOrder[index.row()][2])
            lyrics = 'Lyrics:\n\n{}'.format(
                self.playerCore.findLyrics(index.row()))
            self.windows.append(Window(name, lyrics))

        for window in self.windows:
            if window.isClosed:
                self.windows.remove(window)

    def findInfo(self):
        """Opens window with info for selected album at the table."""
        albums = self.playlistTable.selectedIndexes()[::4]
        if not albums:
            return

        for index in albums:
            info = self.playerCore.findInfo(index.row())
            text = '\n'.join(info)
            self.windows.append(Window('Info', text))

    def login(self):
        """Opens window for user to log in lastFM."""
        self.loginWindow = LoginDialog(self.playerCore)

    def logout(self):
        """Logs out current user"""
        if self.playerCore.network is None:
            return
        self.logoutWindow = Window('Logout', 'GoodBye, {}!'.format(
            self.playerCore.username))
        self.playerCore.logout()

    def love(self):
        """Loves selected songs in lastFM."""
        if self.playerCore.network is None:
            self.errorWindow = Window('Error', 'You shoud login first.')
            return
        songs = self.playlistTable.selectedIndexes()[::4]
        if not songs:
            return
        loved = []
        for index in songs:
            loved.append(self.playerCore.loveTrack(index.row()))
        if all(loved):
            self.successWindow = Window('Success', 'Songs loved!')
        else:
            self.errorWindow = Window(
                'Error', 'Something went wrong! Try again later.')

    def unlove(self):
        """Unloves selected songs in lastFM."""
        if self.playerCore.network is None:
            self.errorWindow = Window('Error', 'You shoud login first.')
            return
        songs = self.playlistTable.selectedIndexes()[::4]
        if not songs:
            return

        for index in songs:
            self.playerCore.unloveTrack(index.row())

    def center(self):
        """Position player application at the center of the screen."""
        # rectangle specifying the geometry of the widget
        rectangle = self.frameGeometry()
        # screen resolution -> center point
        centerPoint = QDesktopWidget().availableGeometry().center()
        # set the center of the rectangle to the center of the screen
        rectangle.moveCenter(centerPoint)
        # move the top-left point of the application window to the top-left
        # point of the rectangle
        self.move(rectangle.topLeft())
Beispiel #57
0
    def load(self, path: str, is_first_call: bool = True) -> None:
        if path == self._path:
            return

        with open(os.path.join(path, "theme.json"), encoding = "utf-8") as f:
            Logger.log("d", "Loading theme file: %s", os.path.join(path, "theme.json"))
            data = json.load(f)

        # Iteratively load inherited themes
        try:
            theme_id = data["metadata"]["inherits"]
            self.load(Resources.getPath(Resources.Themes, theme_id), is_first_call = False)
        except FileNotFoundError:
            Logger.log("e", "Could not find inherited theme %s", theme_id)
        except KeyError:
            pass  # No metadata or no inherits keyword in the theme.json file

        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

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

        if "fonts" in data:
            system_font_size = QCoreApplication.instance().font().pointSize()
            for name, font in data["fonts"].items():
                q_font = QFont()
                q_font.setFamily(font.get("family", QCoreApplication.instance().font().family()))

                if font.get("bold"):
                    q_font.setBold(font.get("bold", False))
                else:
                    q_font.setWeight(font.get("weight", 50))

                q_font.setLetterSpacing(QFont.AbsoluteSpacing, font.get("letterSpacing", 0))
                q_font.setItalic(font.get("italic", False))
                q_font.setPointSize(int(font.get("size", 1) * system_font_size))
                q_font.setCapitalization(QFont.AllUppercase if font.get("capitalize", False) else QFont.MixedCase)

                self._fonts[name] = q_font

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

                self._sizes[name] = s

        iconsdir = os.path.join(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(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))

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

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

        Logger.log("d", "Loaded theme %s", path)
        self._path = path

        # only emit the theme loaded signal once after all the themes in the inheritance chain have been loaded
        if is_first_call:
            self.themeLoaded.emit()
Beispiel #58
0
    def load(self, path):
        if path == self._path:
            return

        self._path = path

        with open(os.path.join(self._path, "theme.json")) as f:
            Logger.log("d", "Loading theme file: %s", os.path.join(self._path, "theme.json"))
            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()
                f.setFamily(font.get("family", QCoreApplication.instance().font().family()))

                f.setBold(font.get("bold", False))
                f.setLetterSpacing(QFont.AbsoluteSpacing, font.get("letterSpacing", 0))
                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(round(size[0] * self._em_width))
                s.setHeight(round(size[1] * self._em_height))

                self._sizes[name] = s

        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))

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

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

        Logger.log("d", "Loaded theme %s", self._path)
        self.themeLoaded.emit()
Beispiel #59
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                return source_data

        if role == Qt.FontRole:
            font = QFont()
            if state_data == TransferState.AWAITING or state_data == TransferState.VALIDATING:
                font.setItalic(True)
            elif state_data == TransferState.REFUSED:
                font.setItalic(True)
            elif state_data == TransferState.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == TransferState.REFUSED:
                return QColor(Qt.red)
            elif state_data == TransferState.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)

            if state_data == TransferState.VALIDATING or state_data == TransferState.AWAITING:
                block_col = model.columns_types.index('block_number')
                block_index = model.index(source_index.row(), block_col)
                block_data = model.data(block_index, Qt.DisplayRole)

                current_confirmations = 0
                if state_data == TransferState.VALIDATING:
                    current_blockid_number = self.community.network.current_blockid.number
                    if current_blockid_number:
                        current_confirmations = current_blockid_number - block_data
                elif state_data == TransferState.AWAITING:
                    current_confirmations = 0

                max_confirmations = self.sourceModel().max_confirmations()

                if self.app.preferences['expert_mode']:
                    return self.tr("{0} / {1} confirmations").format(current_confirmations, max_confirmations)
                else:
                    confirmation = current_confirmations / max_confirmations * 100
                    confirmation = 100 if confirmation > 100 else confirmation
                    return self.tr("Confirming... {0} %").format(QLocale().toString(float(confirmation), 'f', 0))

            return None

        return source_data