Beispiel #1
0
    def __init__(self, parent=None):
        super(CodeEditor, self).__init__(parent)
        self.numArea = LineNumArea(self)

        # Binding signals to slots
        self.blockCountChanged.connect(self.updateNumWidth)
        self.updateRequest.connect(self.updateNum)
        self.cursorPositionChanged.connect(self.highlightLine)
        self.textChanged.connect(self.highlightCode)

        # editor config
        font = QFont()
        font.setFamily("Courier")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(12)
        self.setFont(font)
        metrics = QFontMetrics(font)
        self.setTabStopWidth(4 * metrics.width('a'))  # tab width

        # highlighter
        self.highlighter = Highlighter(self.document())

        # init
        self.updateNumWidth(0)
        self.highlightLine()
Beispiel #2
0
    def transform(self, value):
        if not value:
            return None
        style_map = {"normal": QFont.StyleNormal, "italic": QFont.StyleItalic, "oblique": QFont.StyleOblique}
        weight_map = {"normal": QFont.Normal, "bold": QFont.Bold}
        font = QFont()
        font.setStyle(QFont.StyleNormal)
        font.setWeight(QFont.Normal)

        match = self.font_regex.match(value)
        style = match.group("style")
        weight = match.group("weight")
        namedweight = match.group("namedweight")
        size = match.group("size")
        family = match.group("family")
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith("pt"):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith("px"):
                font.setPixelSize(int(size[:-2]))
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', "").replace("'", "")
        font.setFamily(family)
        return font
    def __init__(self, parent=None, text=None, EditorHighlighterClass=PythonHighlighter, indenter=PythonCodeIndenter):
        QPlainTextEdit.__init__(self, parent)
        self.setFrameStyle(QFrame.NoFrame)
        self.setTabStopWidth(4)
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        font = QFont()
        font.setFamily("lucidasanstypewriter")
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.highlighter = EditorHighlighterClass(self)
        if text:
            self.setPlainText(text)
        self.frame_style = self.frameStyle()
        self.draw_line = True
        self.print_width = self.fontMetrics().width("x" * 78)
        self.line_pen = QPen(QColor("lightgrey"))
        self.last_row = self.last_col = -1
        self.last_block = None
        self.highlight_line = True
        self.highlight_color = self.palette().highlight().color().light(175)
        self.highlight_brush = QBrush(QColor(self.highlight_color))
        self.cursorPositionChanged.connect(self.onCursorPositionChanged)
        self.indenter = indenter(RopeEditorWrapper(self))
        # True if you want to catch Emacs keys in actions
        self.disable_shortcuts = False

        self.prj = get_no_project()
        self.prj.root = None
        self.calltip = CallTip(self)
        self.autocomplete = AutoComplete(self)
Beispiel #4
0
	def __init__(self, parent = None, message = None, itemType = "log"):
		QListWidgetItem.__init__(self)
		self.itemType = itemType

		if (itemType == "log"):
			self.setText("--- " + str(message))
		elif (itemType == "in"):
			self.setText("<<< " + str(message))
		elif (itemType == "out"):
			self.setText(">>> " + str(message))
		else:
			self.setText(str(message))

		font = QFont()
		font.setFamily("Monospace")
		if (itemType == "in") or (itemType == "out"):
			font.setBold(True)
			font.setWeight(75)
		else:
			font.setBold(False)
			font.setWeight(50)
		self.setFont(font)

		brush = QBrush(QColor(0, 0, 0))
		if (itemType == "in"):
			brush = QBrush(QColor(0, 0, 85))
		elif (itemType == "out"):
			brush = QBrush(QColor(0, 85, 0))
		brush.setStyle(Qt.NoBrush)
		self.setForeground(brush)
Beispiel #5
0
    def buttonFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

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

        return font
 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)
    def __init__(self, *args, **kwargs):
        if "windowtype" in kwargs:
            self.windowname = kwargs["windowtype"]
            del kwargs["windowtype"]
        else:
            self.windowname = "XML Object"

        super().__init__(*args, **kwargs)

        self.resize(900, 500)
        self.setMinimumSize(QSize(300, 300))

        self.centralwidget = QWidget(self)
        self.setWidget(self.centralwidget)
        self.entity = None

        font = QFont()
        font.setFamily("Consolas")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)


        self.dummywidget = QWidget(self)
        self.dummywidget.setMaximumSize(0,0)

        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.addWidget(self.dummywidget)


        self.goto_id_action = ActionWithOwner("Go To ID", self, action_owner=self)

        self.addAction(self.goto_id_action)

        self.goto_shortcut = QKeySequence(Qt.CTRL+Qt.Key_G)


        self.goto_id_action.setShortcut(self.goto_shortcut)
        #self.goto_id_action.setShortcutContext(Qt.WidgetShortcut)
        self.goto_id_action.setAutoRepeat(False)

        self.goto_id_action.triggered_owner.connect(self.open_new_window)

        self.textbox_xml = XMLTextEdit(self.centralwidget)
        self.button_xml_savetext = QPushButton(self.centralwidget)
        self.button_xml_savetext.setText("Save XML")
        self.button_xml_savetext.setMaximumWidth(400)
        self.textbox_xml.setLineWrapMode(QTextEdit.NoWrap)
        self.textbox_xml.setContextMenuPolicy(Qt.CustomContextMenu)
        self.textbox_xml.customContextMenuRequested.connect(self.my_context_menu)

        metrics = QFontMetrics(font)
        self.textbox_xml.setTabStopWidth(4 * metrics.width(' '))
        self.textbox_xml.setFont(font)

        self.verticalLayout.addWidget(self.textbox_xml)
        self.verticalLayout.addWidget(self.button_xml_savetext)
        self.setWindowTitle(self.windowname)
Beispiel #8
0
    def headingFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

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

        return font;
Beispiel #9
0
 def lbl2(self):
     font = QFont()
     font.setFamily("Quicksand")
     font.setBold(True)
     font.setPointSize(19)
     lbl2 = QLabel('Welcome to Revolution OS, under this text you find usefull Links  to get started.',self)
     lbl2.setFont(font)
     lbl2.setStyleSheet("QLabel { color : white; }")
     lbl2.move(15, 200)
Beispiel #10
0
 def lbl3(self):
     font = QFont()
     font.setFamily("Quicksand")
     font.setBold(True)
     font.setPointSize(15)
     lbl3 = QLabel('Don\'t show this at start up' ,self)
     lbl3.setFont(font)
     lbl3.setStyleSheet("QLabel { color : white; }")
     lbl3.move(580, 650)
Beispiel #11
0
    def setupEditor(self):
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.editor = QTextEdit()
        self.editor.setFont(font)

        self.highlighter = Highlighter(self.editor.document())
Beispiel #12
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

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

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

        style = match.group('style')
        weight = match.group('weight')
        namedweight = match.group('namedweight')
        size = match.group('size')
        family = match.group('family')
        if style:
            font.setStyle(style_map[style])
        if namedweight:
            font.setWeight(weight_map[namedweight])
        if weight:
            # based on qcssparser.cpp:setFontWeightFromValue
            font.setWeight(min(int(weight) / 8, 99))
        if size:
            if size.lower().endswith('pt'):
                font.setPointSizeF(float(size[:-2]))
            elif size.lower().endswith('px'):
                font.setPixelSize(int(size[:-2]))
            else:
                # This should never happen as the regex only lets pt/px
                # through.
                raise ValueError("Unexpected size unit in {!r}!".format(
                    size))  # pragma: no cover
        # The Qt CSS parser handles " and ' before passing the string to
        # QFont.setFamily. We could do proper CSS-like parsing here, but since
        # hopefully nobody will ever have a font with quotes in the family (if
        # that's even possible), we take a much more naive approach.
        family = family.replace('"', '').replace("'", '')
        if family == 'monospace':
            family = self.monospace_fonts
        font.setFamily(family)
        return font
Beispiel #13
0
 def __init__(self):
     super(PayrecWidget, self).__init__()
     self.ui = Ui_PayrecWidget()
     self.ui.setupUi(self)
     font = QFont()
     font.setFamily("Comic Sans MS")
     font.setPointSize(10)
     font.setBold(True)
     font.setWeight(75)
     self.ui.rec_label.setFont(font)
     self.ui.gsf_label.setFont(font)
Beispiel #14
0
    def contentFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

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

        return font
Beispiel #15
0
    def DecreaseFont(self):
        FontIs = self.textEdit.currentFont()
        font = QFont(FontIs)

        FontSize = int(font.pointSize())
        FontFam = font.family()
        if FontSize > 6:
            FontSize -= 1
        font.setPointSize(FontSize)
        font.setFamily(FontFam)

        self.textEdit.setFont(font)
Beispiel #16
0
	def test_storingFonts(self):
		font = QFont()
		font.setFamily('my family')
		font.setPointSize(20)
		writeToSettings('testFont', font, None, self.settings)
		family = readFromSettings('testFont', str, self.settings)
		size = readFromSettings('testFontSize', int, self.settings)
		self.assertEqual(family, 'my family')
		self.assertEqual(size, 20)
		newFont = readFromSettings('testFont', QFont, self.settings, QFont())
		self.assertEqual(newFont.family(), family)
		self.assertEqual(newFont.pointSize(), size)
Beispiel #17
0
def get_monospace_font():
    preferred = ['Consolas', 'DejaVu Sans Mono', 'Monospace', 'Lucida Console', 'Monaco']
    for name in preferred:
        font = QFont(name)
        if QFontInfo(font).fixedPitch():
            logger.debug('Preferred monospace font: %r', font.toString())
            return font

    font = QFont()
    font.setStyleHint(QFont().Monospace)
    font.setFamily('monospace')
    logger.debug('Using fallback monospace font: %r', font.toString())
    return font
Beispiel #18
0
    def __init__(self, qsciScintillaWidget,  parent=None):
        super().__init__(parent)

        self.qsciScintillaWidget = qsciScintillaWidget

        self.qsciScintillaWidget.setReadOnly(True)

        # Set default font
        font = QFont()
        font.setFamily("Courier New")
        font.setFixedPitch(True)
        font.setPointSize(14)

        self.qsciScintillaWidget.setFont(font)

        # Set margin 0 - used for line numbers
        self.fontMetrics = QFontMetrics(font)
        self.qsciScintillaWidget.setMarginsFont(font)
        self.qsciScintillaWidget.setMarginLineNumbers(0, True)
        self.qsciScintillaWidget.setMarginsBackgroundColor(QColor("#444444"))
        self.qsciScintillaWidget.setMarginsForegroundColor(QColor("#A9B7C6"))
        self.qsciScintillaWidget.setMarginWidth(1, 0)

        self.qsciScintillaWidget.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        lexer = QsciLexerJavaScript()

        lexer.setFont(font)
        # Background color
        lexer.setPaper(QColor("#333333"))
        lexer.setDefaultPaper(QColor("#333333"))
        # Text color
        lexer.setDefaultColor(QColor("#00CCCC"))
        # Text colorization
        # Colorization for: 'some string'
        lexer.setColor(QColor("#A5C261"), QsciLexerJavaScript.SingleQuotedString)
        # Colorization for: "some string"
        lexer.setColor(QColor("#A5C261"), QsciLexerJavaScript.DoubleQuotedString)
        # Colorization for: 13 33 45
        lexer.setColor(QColor("#6897BB"), QsciLexerJavaScript.Number)
        # Colorization for: {} + = ; :
        lexer.setColor(QColor("#A9B7C6"), QsciLexerJavaScript.Operator)
        # Colorization for: true, false
        lexer.setColor(QColor("#FF00BB"), QsciLexerJavaScript.Keyword)
        # Colorization for: valueOfSomething, functionAdd()
        lexer.setColor(QColor("#FF00BB"), QsciLexerJavaScript.Identifier)

        self.qsciScintillaWidget.setLexer(lexer)

        self.qsciScintillaWidget.textChanged.connect(self.on_qsciScintillaWidget_textChanged)
Beispiel #19
0
    def tickerFont():
        font = QFont()
        font.setStyleStrategy(QFont.PreferAntialias)

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

        return font
Beispiel #20
0
    def __init__(self, parent):
        super(CustomTextEdit, self).__init__(parent)
        self.main = None

        font = QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.setFont(font)
        self.highlighter = ChordProHighlighter(self.document())

        self.setReadOnly(True)

        self.setAcceptRichText(False)
Beispiel #21
0
    def paintEvent(self,e):
        # print(e)

        linear_gradient = QLinearGradient()
        linear_gradient.setStart(0, 10) #填充的起点坐标
        linear_gradient.setFinalStop(0, 40) #填充的终点坐标
        #第一个参数终点坐标,相对于我们上面的区域而言,按照比例进行计算
        linear_gradient.setColorAt(0.1, QColor(14, 179, 255))
        linear_gradient.setColorAt(0.5, QColor(114, 232, 255))
        linear_gradient.setColorAt(0.9, QColor(14, 179, 255))

        mask_linear_gradient = QLinearGradient()
        #遮罩的线性渐变填充
        mask_linear_gradient.setStart(0, 10)
        mask_linear_gradient.setFinalStop(0, 40)
        # mask_linear_gradient.setColorAt(0.1, QColor(254, 113, 122))
        # mask_linear_gradient.setColorAt(0.3, QColor(224, 246, 242))
        mask_linear_gradient.setColorAt(0.1, QColor(14, 179, 255))
        mask_linear_gradient.setColorAt(0.5, QColor(114, 232, 255))
        # mask_linear_gradient.setColorAt(0.5, QColor(253, 147, 255))
        # mask_linear_gradient.setColorAt(0.7, QColor(1, 1, 1))
        # mask_linear_gradient.setColorAt(0.7, QColor(64, 2, 2))
        mask_linear_gradient.setColorAt(0.9, QColor(14, 179, 255))
        # mask_linear_gradient.setColorAt(1, QColor(0, 0, 0))

        # print(e)
        
        # 设置字体
        font = QFont()
        font.setFamily("文泉驿等宽微米黑")
        font.setBold(True)
        font.setPointSize(30)
        # self.q.setFont(font)
        p = QPainter(self)
        p.setFont(font);

        # p.setPen(QColor(0, 0, 0, 200));
        # p.drawText(1, 1, 700, 60, Qt.AlignHCenter, "梦音乐梦音乐梦音乐"); #//左对齐

        # // 再在上面绘制渐变文字
        # p.setPen(QPen(linear_gradient, 0));
        # p.drawText(0, 0, 800, 60, Qt.AlignHCenter, "梦音乐梦音乐梦音乐");
        # SYL - 让我们用声音聆听彼此~
        # if not self.s:
            # self.s = str("SYL - 让我们用声音聆听彼此~")
        # // 设置歌词遮罩
        p.setPen(QPen(mask_linear_gradient, 0));
        p.drawText(0, 0, 900, 60, Qt.AlignHCenter, self.text());
Beispiel #22
0
 def qbn(self, s, x, y, l, u):
     qbn = QPushButton(self)
     qbn.setIcon(QIcon(s))
     qbn.setIconSize(QSize(100, 100))
     qbn.resize(100, 100)
     qbn.move(x, y)
     font = QFont()
     font.setFamily("Quicksand")
     font.setBold(True)
     font.setPointSize(15)
     lbl = QLabel(l, self)
     lbl.setFont(font)
     lbl.setStyleSheet("QLabel { color : white; }")
     lbl.move(x, (y + 110))
     def web(self):
         webbrowser.open_new(u)
     qbn.clicked.connect(web)
Beispiel #23
0
 def __init__(self, parent=None):
     super(GcodeLexer, self).__init__(parent)
     self._styles = {
         0: 'Default',
         1: 'Comment',
         2: 'Key',
         3: 'Assignment',
         4: 'Value',
         }
     for key, value in self._styles.iteritems():
         setattr(self, value, key)
     font = QFont()
     font.setFamily('Courier')
     font.setFixedPitch(True)
     font.setPointSize(12)
     font.setBold(True)
     self.setFont(font, 2)
Beispiel #24
0
 def data(self, index, role=Qt.DisplayRole):
     """
     return value for an index
     """
     rows = index.row()
     columns = index.column()
     index_number = rows - 1
     index_number = index_number * columns
     index_number = index_number + columns
     if index.isValid():
         if role == Qt.DisplayRole:
             try:
                 value = self.dmx_list[rows][columns]
                 if value == 255:
                     value = 'FF'
                 elif value == 0:
                     value = ''
                 return QVariant(value)
             except IndexError:
                 if debug:
                     # these cells does not exists
                     print(rows,columns,'is out of dmx_list')
         elif role == Qt.BackgroundRole:
             try:
                 value =  self.dmx_list[rows][columns]
                 green = 255 - value
                 color = QColor(green,255,green)
                 return QBrush(color)
             except IndexError:
                 # these cells does not exists
                 return QVariant()
         elif role == Qt.FontRole:
             try:
                 font = QFont()
                 font.setFamily('Helvetica')
                 #font.setStretch('UltraCondensed')
                 font.setFixedPitch(True)
                 font.setPointSize(10)
                 return font
             except:
                 return QVariant()
         else:
             return QVariant()
     else:
         return QVariant()
Beispiel #25
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
 def setSampleFont(font, familyOnly, sizeOnly):
     """
     Local function to set the font of the sample text.
     
     @param font font to be set (QFont)
     @param familyOnly flag indicating to set the font family only
         (boolean)
     @param sizeOnly flag indicating to set the font size only (boolean
     """
     if familyOnly or sizeOnly:
         newFont = QFont(self.lexer.font(self.style))
         if familyOnly:
             newFont.setFamily(font.family())
         if sizeOnly:
             newFont.setPointSize(font.pointSize())
         self.sampleText.setFont(newFont)
     else:
         self.sampleText.setFont(font)
Beispiel #27
0
    def defaultsPushButtonPressed(self , button):
        download_path_temp_default = str(home_address) + '/.persepolis'
        download_path_default = str(home_address) + '/Downloads/Persepolis'
 
        self.setting_dict = {'max-tries' : 5 , 'retry-wait': 0 , 'timeout' : 60 , 'connections' : 16 , 'download_path_temp' : download_path_temp_default , 'download_path':download_path_default , 'sound' : 'yes' , 'sound-volume':100 , 'style':'Fusion' , 'color-scheme' : 'Persepolis Dark Red' , 'icons':'Archdroid-Red','font' : 'Ubuntu' , 'font-size' : 9  }

        self.tries_spinBox.setValue(int(self.setting_dict['max-tries']))
        self.wait_spinBox.setValue(int(self.setting_dict['retry-wait']))
        self.time_out_spinBox.setValue(int(self.setting_dict['timeout']))
        self.connections_spinBox.setValue(int(self.setting_dict['connections']))

        self.download_folder_lineEdit.setText(str(self.setting_dict['download_path']))
        self.temp_download_lineEdit.setText(str(self.setting_dict['download_path_temp']))


        
        self.volume_label.setText('Volume : ' + str(self.setting_dict['sound-volume']) )
        self.volume_dial.setValue(int(self.setting_dict['sound-volume']))
#set style 
        current_style_index = self.style_comboBox.findText(str(self.setting_dict['style']))
        if current_style_index != -1 :
            self.style_comboBox.setCurrentIndex(current_style_index)
#set color_scheme
        current_color_index = self.color_comboBox.findText(str(self.setting_dict['color-scheme']))
        if current_color_index != -1 :
            self.color_comboBox.setCurrentIndex(current_color_index)
#set icons
        current_icons_index = self.icon_comboBox.findText(str(self.setting_dict['icons']))
        if current_icons_index != -1 :
            self.icon_comboBox.setCurrentIndex(current_icons_index)

#set font 
        font_setting = QFont() 
        font_setting.setFamily(str(self.setting_dict['font']))
        self.fontComboBox.setCurrentFont(font_setting)
    
        self.font_size_spinBox.setValue(int(self.setting_dict['font-size']))

#sound frame 
        if str(self.setting_dict['sound']) == 'yes':
            self.enable_notifications_checkBox.setChecked(True) 
        else:
            self.enable_notifications_checkBox(False)
Beispiel #28
0
 def configure(self):
     font = QFont()
     font.setFamily('ubuntu mono')
     font.setFixedPitch(True)
     font.setPointSize(12)
     self.setFont(font)
     lexer_class = EditorHelper.language_lexer(self.file_info)
     if lexer_class:
         base_lexer = lexer_class()
         self.lang_lexer = type(self.lang, (lexer_class,), {
             'keys_ens': [base_lexer.keywords(i) for i in range(10)],
             'keywords': lambda self, ens: self.keys_ens[ens]
         })()
     #self.lang_lexer = lexer_class() if lexer_class else None
     #ModuleManager.core['theme_manager'].ThemeManager.set_editor_theme(
     #    self, self.lang_lexer)
     
     if hasattr(self, 'lang_lexer'):
         self.lang_lexer.setFont(font)
         self.setLexer(self.lang_lexer)
     
     fontmetrics = QFontMetrics(font)
     self.setMarginsFont(font)
     self.setMarginLineNumbers(1, True)
     self.setMarginWidth(1, fontmetrics.width("00000"))
     self.setCaretLineVisible(True)
     self.setIndentationGuides(True)
     self.setIndentationsUseTabs(False)
     self.setIndentationWidth(4)
     self.setTabWidth(4)
     self.setAutoIndent(True)
     self.setBackspaceUnindents(True)
     self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
     self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
     self.setEdgeColumn(79)
     self.setEdgeColor(QColor('#424242'))
     self.setEdgeMode(QsciScintilla.EdgeLine)
     
     Alter.invoke_all('editor_configure', self)
Beispiel #29
0
    def setAllFonts(self, family='monospace', size=10, fixedpitch=True):
        '''Set the font of all visible elements in the text editor.
        
        This syncronizes the font in the main text area with the margins and 
        calltips.
        '''
        self.fontfamily = family
        self.fontsize = size
        self.fontfixedpitch = True
        
        # Configure editor font size
        font = QFont()
        font.setFamily(family)
        font.setFixedPitch(fixedpitch)
        font.setPointSize(size)
        self.setFont(font)

        # Margin 0 is used for line numbers
        fontmetrics = QtGui.QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(0, fontmetrics.width('___') + 0)
        self.setMarginWidth(1, 0)
        self.setMarginLineNumbers(0, True)
        
        
        # Change lexer font
        bfamily = bytes(family, encoding='utf8')
        lexer = self.lexer()
        if lexer is not None:
            font_bold = QFont(font)
            font_bold.setBold(True)
            for style in self.LEXER_STYLES.values():
                if style in self.BOLD_STYLES:
                    lexer.setFont(font_bold, style)
                else:
                    lexer.setFont(font, style)
            self.SendScintilla(Qsci.QsciScintilla.SCI_STYLESETFONT, 1, bfamily)
def otherUIFont():
    """
    Returns an auxiliary UI font.
    """
    font = QFont()
    pointSize = 9
    if sys.platform == "win32":
        font.setFamily("Segoe UI")
    elif sys.platform == "darwin":
        try:
            platform
        except NameError:
            import platform
        if platform.mac_ver()[0].startswith("10.10"):
            font.setFamily("Lucida Grande")
        pointSize = 12
    elif sys.platform.startswith("linux"):
        font.setFamily("Luxi Sans")
    font.setPointSize(pointSize)
    return font
Beispiel #31
0
    def __init__(self):

        super().__init__()

        self.title = 'Donkey Kong'

        self.setStyleSheet("QWidget { background-color: %s}" %
                           QColor(0, 0, 0).name())
        self.resize(800, 600)
        self.center()
        self.setFixedSize(800, 600)

        self.textLabel = QLabel(self)
        self.textLabel.move(180, 250)
        fontLabel = QFont()
        fontLabel.setFamily("Arcade Normal")
        fontLabel.setPointSize(20)
        self.textLabel.setStyleSheet('color: white;')
        self.textLabel.setFont(fontLabel)
        self.textLabel.setText("Enter players names")

        fontTB = QFont()
        fontTB.setFamily("Arcade Normal")
        fontTB.setPointSize(13)

        self.player1Label = QLabel(self)
        self.player1Label.move(180, 335)
        self.player1Label.setStyleSheet('color: white;')
        self.player1Label.setFont(fontTB)
        self.player1Label.setText("Player 1: ")

        self.textEdit = QLineEdit(self)
        self.textEdit.resize(200, 50)
        self.textEdit.move(340, 320)
        self.textEdit.setStyleSheet(
            "QLineEdit { background-color: black; color: white; }")
        self.textEdit.setFont(fontTB)

        self.player2Label = QLabel(self)
        self.player2Label.move(180, 425)
        self.player2Label.setStyleSheet('color: white;')
        self.player2Label.setFont(fontTB)
        self.player2Label.setText("Player 2: ")

        self.textEdit2 = QLineEdit(self)
        self.textEdit2.resize(200, 50)
        self.textEdit2.move(340, 410)
        self.textEdit2.setStyleSheet(
            "QLineEdit { background-color: black; color: white; }")
        self.textEdit2.setFont(fontTB)

        fontBtn = QFont()
        fontBtn.setFamily("Arcade Normal")
        fontBtn.setPointSize(13)

        self.playBtn = QPushButton("Play", self)
        self.playBtn.clicked.connect(self.startGame)
        self.playBtn.resize(200, 50)
        self.playBtn.move(300, 500)
        self.playBtn.setStyleSheet(
            "QPushButton:!hover { background-color: black; color: white;  }"
            "QPushButton:hover {background-color: black; color: red; }")
        self.playBtn.setFont(fontBtn)

        self.initUI()
Beispiel #32
0
class Main(QMainWindow):
    def __init__(self, app, palette, editor, parent=None):
        super().__init__(parent)

        self.editor = editor
        self.onStart(choiceIndex)
        self.status = QStatusBar(self)
        # Initializing the main widget where text is displayed
        self.tab = Tabs(self.openFile, app, palette, self)
        self.tabsOpen = []
        self.pic_opened = False
        self.dialog = MessageBox(self)

        self.setWindowIcon(QIcon('resources/Python-logo-notext.svg_.png')
                           )  # Setting the window icon

        self.setWindowTitle('PyPad')  # Setting the window title

        self.status_font = QFont(editor["statusBarFont"],
                                 editor["statusBarFontSize"])

        self.os = platform.system()

        self.tab.tabs.currentChanged.connect(self.fileNameChange)
        self.search = DocumentSearch()
        self.openterm()
        self.openterminal()
        # self.split2Tabs()
        self.new()
        self.newProject()
        self.findDocument()
        self.openProjectF()
        self.open()
        self.save()
        self.saveAs()
        self.exit()

        self.thread = UpdateThread()
        self.thread.start()

        self.thread.textSignal.connect(self.check_updates)

        self.dir_opened = False
        self._dir = None

        self.update_progress = QProgressBar()
        self.update_progress.setMaximumWidth(225)

        self.update_progress.setStyleSheet(self.update_progress.styleSheet())

        self.setCentralWidget(self.tab)

        self.files = None  # Tracking the current file that is open

        self.cFileOpened = False

        self.update_process = QProcess()

        self.initUI()  # Main UI

    def check_updates(self, text):

        self.update_label = QLabel()
        self.update_label.setFont(
            QFont(self.editor["generalFont"], self.editor["generalFontSize"]))
        self.update_label.setFont(self.status_font)
        self.update_label.setText(text)
        self.status.addWidget(self.update_label)

        if text != "An update is available, would you like to update?":
            pass
        else:
            self.button = QPushButton("Update")
            self.button.setFont(
                QFont(self.editor["generalFont"],
                      self.editor["generalFontSize"]))
            self.status.addWidget(self.button)
            self.button.clicked.connect(self.update_pypad)

    def update_pypad(self):
        self.update_label.setText("Updating...")
        self.status.removeWidget(self.button)
        self.status.addWidget(self.update_progress)
        """
        So "updating" means I should first have an executeable or something of that sorts
        """

        for i in range(101):
            self.update_progress.setValue(i)
            QTest.qWait(random.randint(50, 75))
        # make_decision(True)

    def fileNameChange(self):

        try:
            currentFileName = self.tab.tabs.currentWidget().baseName
            self.setWindowTitle("PyPad ~ " + str(currentFileName))

        except AttributeError:
            self.setWindowTitle("PyPad ~ ")

    def onStart(self, index):

        try:
            editor = configs[index]['editor']
            if editor["windowStaysOnTop"] is True:
                self.setWindowFlags(Qt.WindowStaysOnTopHint)

            else:
                pass

        except Exception as err:
            pass  # log exception

        self.font = QFont()
        self.font.setFamily(self.editor["editorFont"])

        self.font.setPointSize(self.editor["editorFontSize"])
        self.tabSize = self.editor["TabWidth"]

    def initUI(self):

        self.setStatusBar(self.status)  # Initializing the status bar

        self.font.setFixedPitch(True)
        menuFont = QFont()
        menuFont.setFamily(self.editor["menuFont"])
        menuFont.setPointSize(self.editor['menuFontSize'])
        menu = self.menuBar()
        menu.setFont(menuFont)
        # Creating the file menu

        fileMenu = menu.addMenu('File')

        # Adding options to the file menu
        # self.setStatusBar(self.status)
        fileMenu.addAction(self.newAct)
        fileMenu.addAction(self.newProjectAct)
        fileMenu.addAction(self.openAct)
        fileMenu.addAction(self.openProjectAct)
        fileMenu.addAction(self.saveAct)
        fileMenu.addAction(self.saveAsAct)
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAct)

        toolMenu = menu.addMenu('Tools')
        toolMenu.addAction(self.openTermAct)
        toolMenu.addAction(self.openTerminalAct)
        # toolMenu.addAction(self.split2TabsAct)

        searchDoc = menu.addMenu('Find document')

        searchDoc.addAction(self.findDocumentAct)

        self.showMaximized()

    def open(self):
        self.openAct = QAction('Open...', self)
        self.openAct.setShortcut('Ctrl+O')

        self.openAct.setStatusTip('Open a file')
        self.openAct.triggered.connect(self.openFileFromMenu)

    def closeEvent(self, QCloseEvent):

        os._exit(42)  # This makes sure every thread gets killed

    def new(self):
        self.newAct = QAction('New')
        self.newAct.setShortcut('Ctrl+N')

        self.newAct.setStatusTip('Create a new file')
        self.newAct.triggered.connect(self.newFile)

    def newProject(self):
        self.newProjectAct = QAction('New project')
        self.newProjectAct.setShortcut('Ctrl+Shift+N')

        self.newProjectAct.setStatusTip('Create a new project')
        self.newProjectAct.triggered.connect(self.newProjectFolder)

    def openProjectF(self):
        self.openProjectAct = QAction('Open project')
        self.openProjectAct.setShortcut('Ctrl+Shift+O')

        self.openProjectAct.setStatusTip('Open a project')
        self.openProjectAct.triggered.connect(self.openProject)

    def split2Tabs(self):
        self.split2TabsAct = QAction('Split the first 2 tabs')
        self.split2TabsAct.setShortcut('Ctrl+Alt+S')

        self.split2TabsAct.setStatusTip("Splits the first 2 tabs into one tab")
        self.split2TabsAct.triggered.connect(self.tab.split)

    def switchTabs(self):
        if self.tab.tabs.count() - 1 == self.tab.tabs.currentIndex():
            self.tab.tabs.setCurrentIndex(0)
        else:
            self.tab.tabs.setCurrentIndex(self.tab.tabs.currentIndex() + 1)

    def save(self):
        self.saveAct = QAction('Save')
        self.saveAct.setShortcut('Ctrl+S')

        self.saveAct.setStatusTip('Save a file')
        self.saveAct.triggered.connect(self.saveFile)

    def openterm(self):
        self.openTermAct = QAction('Run', self)
        self.openTermAct.setShortcut('Shift+F10')

        self.openTermAct.setStatusTip('Run your code')
        self.openTermAct.triggered.connect(self.execute_file)

    def openterminal(self):
        self.openTerminalAct = QAction("Terminal", self)
        self.openTerminalAct.setShortcut("Ctrl+T")

        self.openTerminalAct.setStatusTip("Open a terminal")
        self.openTerminalAct.triggered.connect(self.realterminal)

    def saveAs(self):
        self.saveAsAct = QAction('Save As...')
        self.saveAsAct.setShortcut('Ctrl+Shift+S')

        self.saveAsAct.setStatusTip('Save a file as')
        self.saveAsAct.triggered.connect(self.saveFileAs)

    def findDocument(self):
        self.findDocumentAct = QAction('Find document')
        self.findDocumentAct.setShortcut('Ctrl+Shift+F')

        self.findDocumentAct.setStatusTip('Find a document')
        self.findDocumentAct.triggered.connect(self.temp)

    def temp(self):
        pass

    def findDocumentFunc(self):

        self.search.run()

    def exit(self):
        self.exitAct = QAction('Quit', self)
        self.exitAct.setShortcut('Ctrl+Q')

        self.exitAct.setStatusTip('Exit application')
        self.exitAct.triggered.connect(qApp.quit)

    def openFileFromMenu(self):
        options = QFileDialog.Options()

        filenames, _ = QFileDialog.getOpenFileNames(
            self,
            'Open a file',
            '',
            'All Files (*);;Python Files (*.py);;Text Files (*.txt)',
            options=options)

        if filenames:  # If file is selected, we can open it
            filename = filenames[0]
            if filename[-3:] in ['gif', 'png', 'jpg', 'bmp'
                                 ] or filename[-4:] in ['jpeg']:
                self.pic_opened = True
            self.openFile(filename)

    def openBrowser(self, url, word):
        widget = Browser(url)
        index = self.tab.tabs.addTab(widget, "Info about: " + str(word))
        self.tab.tabs.setCurrentIndex(index)

    def openFile(self, filename):

        try:
            for index, tabName in enumerate(self.tab.tabCounter):
                with open(filename, 'r+') as file_o:
                    if filename[-3:] in ['gif', 'png', 'jpg', 'bmp'
                                         ] or filename[-4:] in ['jpeg']:
                        self.pic_opened = True
                    else:
                        self.pic_opened = False
                    try:
                        text = file_o.read()

                    except UnicodeDecodeError as E:
                        text = str(E)

                    basename = os.path.basename(filename)
                    if not self.pic_opened:
                        tab = Content(text, filename, basename, self)
                        tab.saved = True
                        tab.modified = False
                    else:
                        tab = Image(filename, basename)
                if tabName == tab.baseName:
                    self.tab.tabs.removeTab(index)

                    self.tab.tabCounter.remove(tab.baseName)
            try:
                with open(filename, 'r+') as file_o:
                    try:
                        if self.pic_opened is not True:
                            text = file_o.read()
                        else:
                            text = None
                    except (FileNotFoundError, UnicodeDecodeError,
                            AttributeError) as E:
                        text = str(E)

            except FileNotFoundError:
                with open(filename, 'w+') as newFileCreated:
                    text = newFileCreated.read()

            basename = os.path.basename(filename)
            if self.pic_opened is True:
                tab = Image(filename, basename)

            else:
                tab = Content(text, filename, basename,
                              self)  # Creating a tab object *IMPORTANT*
                tab.saved = True
                tab.modified = False
            self.tab.tabCounter.append(tab.baseName)
            dirPath = os.path.dirname(filename)
            self.files = filename

            self.tabsOpen.append(self.files)

            index = self.tab.tabs.addTab(
                tab, tab.baseName
            )  # This is the index which we will use to set the current
            self.tab.tabs.setTabToolTip(index, str(tab.fileName))
            if not self.dir_opened:  # If a project isnt opened then we open a directory everytime we open a file
                self.tab.directory.openDirectory(dirPath)

                self.tab.showDirectory()
            else:
                pass

            self.tab.setLayout(self.tab.layout)  # Finally we set the layout
            update_previous_file(filename)
            self.tab.tabs.setCurrentIndex(
                index)  # Setting the index so we could find the current widget

            self.currentTab = self.tab.tabs.currentWidget()

            if self.pic_opened is not True:
                self.currentTab.editor.setFont(self.font)  # Setting the font
                self.currentTab.editor.setFocus(
                )  # Setting focus to the tab after we open it

            self.pic_opened = False
        except (IsADirectoryError, AttributeError, UnboundLocalError,
                PermissionError) as E:
            print(E, " on line 346 in the file main.py")

    def newFile(self):
        text = ""
        if self._dir:
            base_file_name = "Untitled_file_" + str(random.randint(
                1, 100)) + ".py"
            fileName = str(self._dir) + "/" + base_file_name
        else:
            base_file_name = "Untitled_file_" + str(random.randint(
                1, 100)) + ".py"
            current = os.getcwd()
            fileName = current + "/" + base_file_name

        self.pyFileOpened = True
        # Creates a new blank file
        file = Content(text, fileName, base_file_name, self)
        self.tab.splitterH.addWidget(
            self.tab.tabs
        )  # Adding tabs, now the directory tree will be on the left
        self.tab.tabCounter.append(file.fileName)
        self.tab.setLayout(self.tab.layout)  # Finally we set the layout
        index = self.tab.tabs.addTab(
            file, file.baseName
        )  # addTab method returns an index for the tab that was added
        self.tab.tabs.setTabToolTip(index, str(file.fileName))
        self.tab.tabs.setCurrentIndex(
            index)  # Setting focus to the new tab that we created
        widget = self.tab.tabs.currentWidget()

    def newProjectFolder(self):
        self.dialog = NewProject(self)
        self.dialog.show()

    def openProject(self):

        self._dir = QFileDialog.getExistingDirectory(None, 'Select a folder:',
                                                     '',
                                                     QFileDialog.ShowDirsOnly)

        self.tab.directory.openDirectory(self._dir)
        self.dir_opened = True
        self.tab.showDirectory()

    def openProjectWithPath(self, path):

        self.tab.directory.openDirectory(path)
        self.dir_opened = True
        self._dir = path
        self.tab.showDirectory()

    def saveFile(self):
        try:
            active_tab = self.tab.tabs.currentWidget()
            if self.tab.tabs.count():  # If a file is already opened
                with open(active_tab.fileName, 'w+') as saveFile:
                    saveFile.write(active_tab.editor.toPlainText())
                    active_tab.saved = True
                    self.tab.events.look_for_dead_code(
                        active_tab.editor.toPlainText())
                    active_tab.modified = False
                    saveFile.close()
                if active_tab.fileName.endswith(".py"):
                    active_tab.editor.updateAutoComplete(active_tab.fileName)
            else:
                options = QFileDialog.Options()
                name = QFileDialog.getSaveFileName(
                    self,
                    'Save File',
                    '',
                    'All Files (*);;Python Files (*.py);;Text Files (*.txt)',
                    options=options)
                fileName = name[0]

                with open(fileName, "w+") as saveFile:
                    active_tab.saved = True
                    active_tab.modified = False
                    self.tabsOpen.append(fileName)
                    saveFile.write(active_tab.editor.toPlainText())
                    self.tab.events.look_for_dead_code(
                        active_tab.editor.toPlainText())
                    saveFile.close()
                    if fileName.endswith(".py"):
                        active_tab.editor.updateAutoComplete(
                            active_tab.fileName)
            self.setWindowTitle("PyPad ~ " + str(active_tab.baseName) +
                                " [SAVED]")
            active_tab.tokenize_file()
        except Exception as E:
            print(E, " on line 403 in the file main.py")

    def choose_python(self):
        if self.os == "Windows":
            return "python"

        elif self.os == "Linux":
            return "python3"

        elif self.os == "Darwin":
            return "python3"

    def saveFileAs(self):
        try:
            active_tab = self.tab.tabs.currentWidget()
            if active_tab is not None:
                active_index = self.tab.tabs.currentIndex()

                options = QFileDialog.Options()
                name = QFileDialog.getSaveFileName(
                    self,
                    'Save File',
                    '',
                    'All Files (*);;Python Files (*.py);;Text Files (*.txt)',
                    options=options)
                fileName = name[0]
                with open(fileName, "w+") as saveFile:
                    active_tab.saved = True
                    active_tab.modified = False
                    self.tabsOpen.append(fileName)

                    try:
                        baseName = os.path.basename(fileName)
                    except AttributeError:
                        print("All tabs closed")
                    saveFile.write(active_tab.editor.toPlainText())
                    text = active_tab.editor.toPlainText()
                    newTab = Content(str(text), fileName, baseName, self)
                    newTab.ready = True
                    self.tab.tabs.removeTab(
                        active_index
                    )  # When user changes the tab name we make sure we delete the old one
                    index = self.tab.tabs.addTab(
                        newTab, newTab.baseName)  # And add the new one!
                    self.tab.tabs.setTabToolTip(index, str(newTab.fileName))

                    self.tab.tabs.setCurrentIndex(index)
                    newActiveTab = self.tab.tabs.currentWidget()

                    newActiveTab.editor.setFont(self.font)
                    newActiveTab.editor.setFocus()

                    saveFile.close()
                self.setWindowTitle("PyPad ~ " + str(active_tab.baseName) +
                                    " [SAVED]")

            else:
                print("No file opened")

        except FileNotFoundError:
            print("File dialog closed")

    def realterminal(self):
        """
        Checking if the file executing widget already exists in the splitter layout:

        If it does exist, then we're going to replace the widget with the terminal widget, if it doesn't exist then
        just add the terminal widget to the layout and expand the splitter.

        """

        if self.tab.splitterV.indexOf(self.tab.Console) == 1:
            self.tab.splitterV.replaceWidget(
                self.tab.splitterV.indexOf(self.tab.Console),
                self.tab.terminal)
            self.tab.splitterV.setSizes([400, 10])
        else:
            self.tab.showConsole()

    def open_documentation(self, data, word):
        """
        Opens documentation for a built in function
        """
        data = data.replace("|", "")
        index = self.tab.tabs.addTab(
            Content(data,
                    os.getcwd() + "/" + str(word) + ".doc",
                    str(word) + ".doc", self, True), str(word))
        self.tab.tabs.setCurrentIndex(index)

    def execute_file(self):
        """
        Checking if the terminal widget already exists in the splitter layout:

        If it does exist, then we're going to replace it, if it doesn't then we're just gonna add our file executer to
        the layout, expand the splitter and run the file.

        Then check if the file executer already exists, but is called again to run the file again

        """
        active_tab = self.tab.tabs.currentWidget()
        python_command = self.choose_python()
        if self.tab.splitterV.indexOf(self.tab.terminal) == 1:
            self.tab.splitterV.replaceWidget(
                self.tab.splitterV.indexOf(self.tab.terminal),
                self.tab.Console)
            self.tab.Console.run(
                "{} ".format(python_command) + active_tab.fileName,
                active_tab.fileName)
            self.tab.splitterV.setSizes([400, 10])

        elif self.tab.splitterV.indexOf(self.tab.Console) == 1:
            self.tab.Console.run(
                "{} ".format(python_command) + active_tab.fileName,
                active_tab.fileName)
            self.tab.splitterV.setSizes([400, 10])
        else:
            self.tab.showFileExecuter()
            self.tab.Console.run(
                "{} ".format(python_command) + active_tab.fileName,
                active_tab.fileName)
            self.tab.splitterV.setSizes([400, 10])
Beispiel #33
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)

        # Iteratively load inherited themes
        try:
            theme_id = data["metadata"]["inherits"]
            self.load(Resources.getPath(Resources.Themes, theme_id))
        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

        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 #34
0
class MyWidget(QMainWindow):
    def __init__(self, my_app):
        super().__init__()
        self.my_app = my_app
        self.paths = self.my_app.paths

        self.setWindowTitle("Xincapio")
        self.resize(900, 600)
        self.show()

        menubar = self.menuBar()
        file_menu = menubar.addMenu("&File")

        save_button = QAction(QIcon(), "&Save", self)
        save_button.setShortcut("Ctrl+S")
        save_button.triggered.connect(self.on_save)
        file_menu.addAction(save_button)

        refresh_button = QAction(QIcon(), "&Refresh", self)
        refresh_button.setShortcut("Ctrl+R")
        refresh_button.triggered.connect(self.init_ui)
        file_menu.addAction(refresh_button)

        exit_button = QAction(QIcon(), "&Exit", self)
        exit_button.setShortcut("Ctrl+Q")
        exit_button.triggered.connect(qApp.quit)
        file_menu.addAction(exit_button)

        help_menu = menubar.addMenu("&Help")

        about_button = QAction(QIcon(), "&About", self)
        about_button.triggered.connect(self.on_about)
        help_menu.addAction(about_button)

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QHBoxLayout(self)
        self.scroll = QScrollArea(self)
        self.scroll.setWidgetResizable(True)
        self.scroll_widget_contents = QWidget()
        self.grid = QGridLayout(self.scroll_widget_contents)
        self.scroll.setWidget(self.scroll_widget_contents)
        self.layout.addWidget(self.scroll)
        self.grid.setSpacing(0)

        self.default_font = QFont()
        self.default_font.setPointSize(Style.default_font)

        self.h1_font = QFont()
        self.h1_font.setPointSize(Style.h1_font)
        self.h1_font.setBold(True)

        self.key_font = QFont()
        self.key_font.setPointSize(Style.default_font)
        self.key_font.setBold(True)

        if self.my_app.my_system == "Windows":
            self.default_font.setFamily(Style.default_typeface_win)
            self.h1_font.setFamily(Style.default_typeface_win)
            self.key_font.setFamily(Style.default_typeface_win)

        self.centralWidget().setLayout(self.layout)

        self.init_ui()

    def init_ui(self):
        self.system_info = self.my_app.get_info()
        self.show_info()

    def show_info(self):
        if self.grid.count():
            for index in reversed(range(self.grid.count())):
                widget_to_remove = self.grid.itemAt(index).widget()
                if widget_to_remove:
                    self.grid.removeWidget(widget_to_remove)
                    widget_to_remove.setParent(None)
                else:
                    self.grid.removeItem(self.grid.itemAt(index))

        i = 0
        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        blank_space = QSpacerItem(
            Style.section_border,
            0,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)

        label = QLabel("Network")
        label.setFont(self.h1_font)
        self.grid.addWidget(label, i, 2, 3, 1)

        blank_space = QSpacerItem(
            Style.h1_border,
            0,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 3)

        for network in self.system_info["network"]:
            label = QLabel("Name")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(network["name"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

            blank_space = QSpacerItem(
                Style.section_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 7)
            i += 1

            blank_space = QSpacerItem(
                0,
                Style.default_border,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 4)
            i += 1

            label = QLabel("IP")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(network["ip"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

            blank_space = QSpacerItem(
                Style.default_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 7)
            i += 1

            blank_space = QSpacerItem(
                0,
                Style.default_border,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 4)
            i += 1

            label = QLabel("MAC")
            label.setFont(self.default_font)
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(network["mac"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

            blank_space = QSpacerItem(
                Style.section_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 7)
            i += 1

            blank_space = QSpacerItem(
                0,
                Style.section_border,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 1)
            i += 1

        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        self.grid.addWidget(hline, i, 1, 1, 7)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        blank_space = QSpacerItem(
            Style.section_border,
            0,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)

        label = QLabel("Boot Disk")
        label.setFont(self.h1_font)
        self.grid.addWidget(label, i, 2, 3, 1)

        blank_space = QSpacerItem(
            Style.h1_border,
            0,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 3)

        if self.system_info["os"] == "Linux":
            label = QLabel("Mount Point")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(self.system_info["boot_disk"]["mount_point"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

            blank_space = QSpacerItem(
                Style.section_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 7)
            i += 1

            blank_space = QSpacerItem(
                0,
                Style.default_border,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 4)
            i += 1

            label = QLabel("Serial Number")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(self.system_info["boot_disk"]["serial_number"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

        else:
            label = QLabel("Device ID")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(self.system_info["boot_disk"]["device_id"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

            blank_space = QSpacerItem(
                Style.section_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 7)
            i += 1

            blank_space = QSpacerItem(
                0,
                Style.default_border,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 4)
            i += 1

            label = QLabel("Index")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(str(self.system_info["boot_disk"]["index"]))
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

            blank_space = QSpacerItem(
                Style.section_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 7)
            i += 1

            blank_space = QSpacerItem(
                0,
                Style.default_border,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 4)
            i += 1

            label = QLabel("Serial Number")
            label.setFont(self.key_font)
            self.grid.addWidget(label, i, 4)

            blank_space = QSpacerItem(
                Style.key_border,
                0,
                QSizePolicy.Minimum,
                QSizePolicy.Minimum,
            )
            self.grid.addItem(blank_space, i, 5)

            label = QLabel(self.system_info["boot_disk"]["serial_number"])
            label.setFont(self.default_font)
            self.grid.addWidget(label, i, 6)

        blank_space = QSpacerItem(
            Style.section_border,
            0,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 7)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        local_time = _convert_timezone(self.system_info["creation_time"])
        message = "Updated at " + str(local_time)
        self.statusBar().showMessage(message)

        i += 1
        self.grid.setColumnStretch(0, 1)
        self.grid.setColumnStretch(8, 1)
        self.grid.setRowStretch(i, 1)

    def on_save(self):
        output_file = QFileDialog.getSaveFileName(
            self,
            filter="All Files (*);;JSON (*.json)",
            initialFilter="JSON (*.json)",
            directory="/",
        )
        output_path, file_type = output_file
        if output_path != "":
            self.my_app.save_info(self.system_info, output_path)

    def on_about(self):
        dialog = AboutDialog(self.paths, self.system_info["os"], self)
        dialog.exec_()
Beispiel #35
0
class CreateNote(QWidget, Ui_Form):
    def __init__(self, func=None, create=True):
        super().__init__()
        self.setupUi(self)
        self.func = func
        self.get_color = GetColor()

        self.get_color_btn.clicked.connect(self.get_color.show)
        self.get_color.color_btn.clicked.connect(self.set_design)
        self.background_color = ''

        self.font_changed = QFont()
        self.font_changed.setPixelSize(12)
        self.text_note_edit.setFont(self.font_changed)

        self.save_note_btn.clicked.connect(self.save_note)

        self.fontComboBox.currentFontChanged.connect(self.change_font)
        self.font_size_box.currentTextChanged.connect(self.change_font_size)
        self.open_file_btn.clicked.connect(self.open_file)
        if create:
            self.del_note_btn.setText('Сохранить \n в файл')
            self.del_note_btn.clicked.connect(self.save_to_file)

    def open_file(self):
        fname = QFileDialog.getOpenFileName(self, 'Выбрать текстовый файл', '',
                                            "Текстовый файл(*.txt)")[0]
        if len(fname) != 0:
            with open(fname, 'r', encoding='utf-8') as f:
                self.text_note_edit.appendPlainText(f.read())

    # изменяет размер шрифта при выборе размера
    def change_font_size(self):
        self.font_changed.setPixelSize(int(self.font_size_box.currentText()))
        self.text_note_edit.setFont(self.font_changed)

    # изменяет шрифт
    def change_font(self):
        self.font_changed.setFamily(
            QFont(self.fontComboBox.currentFont()).family())
        self.text_note_edit.setFont(self.font_changed)

    def set_design(self):
        self.background_color = self.get_color.set_color()[1]
        self.text_note_edit.setStyleSheet(f'{self.get_color.set_color()[0]}')

    def save_note(self):
        self.color = self.background_color
        if self.background_color == '':
            self.color = '#fff'
        con = sqlite3.connect('other_files/my_project.db')
        cur = con.cursor()
        cur.execute(f"""INSERT INTO notes(note, fontfamily, fontsize, color) 
        VALUES ('{self.text_note_edit.toPlainText()}', 
        '{QFont(self.fontComboBox.currentFont()).family()}', 
        {int(self.font_size_box.currentText())}, '{self.color}')""")
        con.commit()
        con.close()

        self.func()
        self.close()

    def save_to_file(self):
        fname = QFileDialog.getOpenFileName(self, 'Выбрать текстовый файл', '',
                                            "Текстовый файл(*.txt)")[0]
        if len(fname) != 0:
            with open(fname, 'w', encoding='utf-8') as f:
                f.write(self.text_note_edit.toPlainText())
Beispiel #36
0
import re

from PyQt5.QtCore import pyqtSlot, Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import QWidget, QMessageBox
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QFont

from ui.add_ui import Ui_Form
from ui.netwok import add_ip

font_command = QFont()
font_command.setFamily("Arial")
font_command.setPointSize(8)

sernum = ''
mask = ''
manyc = ''
MASK_RULE = r'255.255.255.24[08]|255.255.255.224|255.255.255.192|255.255.255.128|255.255.255.0|255.255.255.252'


class Add_Ui(QWidget, Ui_Form):
    def __init__(self):
        super(Add_Ui, self).__init__()
        self.setupUi(self)
        self.textEdit.setFont(font_command)

        self.textEdit.setDisabled(True)
        self.pushButton.clicked.connect(self.push_add)

    @pyqtSlot()
    def push_add(self):
Beispiel #37
0
class TreeUi(QTreeWidget):
    def __init__(self, main_window):
        super().__init__()
        self.mainWindow = main_window
        self._createNames()
        self._createIcons()
        self._createFonts()
        self._createColorsBrush()
        self._configTree()
        self._createItems()
        self._configItems()
        self._addItems()
        self._updateItems()

    def _createNames(self):
        self.name_top_structuralmodelSetup = "Structural Model Setup"
        self.name_child_set_material = "Set Material"
        self.name_child_set_crossSection = "Set Cross-Section"
        self.name_child_setElementType = "Set Element Type"
        self.name_child_setPrescribedDofs = "Set Prescribed DOFs"
        self.name_child_setNodalLoads = "Set Nodal Loads"
        self.name_child_addMassSpringDamper = "Add: Mass / Spring / Damper"

        self.name_top_acousticmodelSetup = "Acoustic Model Setup"
        self.name_child_set_fluid = "Set Fluid"
        self.name_child_setAcousticPressure = "Set Acoustic Pressure"
        self.name_child_setVolumeVelocity = "Set Volume Velocity"
        self.name_child_setSpecificImpedance = "Set Specific Impedance"
        self.name_child_setRadiationImpedance = "Set Radiation Impedance"

        self.name_top_analysis = "Analysis"
        self.name_child_selectAnalysisType = "Select Analysis Type"
        self.name_child_analisysSetup = "Analysis Setup"
        self.name_child_selectTheOutputResults = "Select the Outputs Results"
        self.name_child_runAnalysis = "Run Analysis"

        self.name_top_resultsViewer = "Results Viewer"
        self.name_child_plotStructuralModeShapes = "Plot Structural Mode Shapes"
        self.name_child_plotStructuralHarmonicResponse = "Plot Structural Harmonic Response"
        self.name_child_plotStructuralFrequencyResponse = "Plot Structural Frequency Response"
        self.name_child_plotStressField = "Plot Stress Field"
        self.name_child_plotAcousticModeShapes = "Plot Acoustic Mode Shapes"
        self.name_child_plotAcousticHarmonicResponse = "Plot Acoustic Harmonic Response"
        self.name_child_plotAcousticFrequencyResponse = "Plot Acoustic Frequency Response"
        self.name_child_plot_TL_NR = "Plot Transmission Loss or Attenuation"
        self.name_child_plot_reactions = "Plot Reactions"

    def _createIcons(self):
        self.icon_child_set_material = QIcon()
        self.icon_child_set_material.addPixmap(
            QPixmap("pulse/data/icons/pulse.png"), QIcon.Active, QIcon.On)

    def _createFonts(self):
        self.font_top = QFont()
        #self.font_child = QFont()

        self.font_top.setFamily("Segoe UI")
        self.font_top.setPointSize(10)
        self.font_top.setBold(True)
        self.font_top.setItalic(True)
        self.font_top.setWeight(75)

    def _createColorsBrush(self):
        #color_top = QColor(39, 180, 211)
        color_top = QColor(178, 178, 178)
        #color_child = QColor(0, 0, 0)
        self.brush_top = QBrush(color_top)
        self.brush_top.setStyle(Qt.SolidPattern)

    def _configTree(self):
        self.setColumnCount(1)
        self.setHeaderHidden(True)
        self.setTabKeyNavigation(True)
        self.setIndentation(0)
        self.itemClicked.connect(self.on_click_item)

    def _createItems(self):
        self.item_top_structuralmodelSetup = QTreeWidgetItem(
            [self.name_top_structuralmodelSetup])
        self.item_child_set_material = QTreeWidgetItem(
            [self.name_child_set_material])
        self.item_child_set_crossSection = QTreeWidgetItem(
            [self.name_child_set_crossSection])
        self.item_child_setElementType = QTreeWidgetItem(
            [self.name_child_setElementType])
        self.item_child_setPrescribedDofs = QTreeWidgetItem(
            [self.name_child_setPrescribedDofs])
        self.item_child_setNodalLoads = QTreeWidgetItem(
            [self.name_child_setNodalLoads])
        self.item_child_addMassSpringDamper = QTreeWidgetItem(
            [self.name_child_addMassSpringDamper])

        self.item_top_acousticmodelSetup = QTreeWidgetItem(
            [self.name_top_acousticmodelSetup])
        self.item_child_set_fluid = QTreeWidgetItem(
            [self.name_child_set_fluid])
        self.item_child_setAcousticPressure = QTreeWidgetItem(
            [self.name_child_setAcousticPressure])
        self.item_child_setVolumeVelocity = QTreeWidgetItem(
            [self.name_child_setVolumeVelocity])
        self.item_child_setSpecificImpedance = QTreeWidgetItem(
            [self.name_child_setSpecificImpedance])
        self.item_child_setRadiationImpedance = QTreeWidgetItem(
            [self.name_child_setRadiationImpedance])

        self.item_top_analysis = QTreeWidgetItem([self.name_top_analysis])
        self.item_child_selectAnalysisType = QTreeWidgetItem(
            [self.name_child_selectAnalysisType])
        self.item_child_analisysSetup = QTreeWidgetItem(
            [self.name_child_analisysSetup])
        self.item_child_selectTheOutputResults = QTreeWidgetItem(
            [self.name_child_selectTheOutputResults])
        self.item_child_runAnalysis = QTreeWidgetItem(
            [self.name_child_runAnalysis])

        self.item_top_resultsViewer = QTreeWidgetItem(
            [self.name_top_resultsViewer])
        self.item_child_plotStructuralModeShapes = QTreeWidgetItem(
            [self.name_child_plotStructuralModeShapes])
        self.item_child_plotStructuralHarmonicResponse = QTreeWidgetItem(
            [self.name_child_plotStructuralHarmonicResponse])
        self.item_child_plotAcousticModeShapes = QTreeWidgetItem(
            [self.name_child_plotAcousticModeShapes])
        self.item_child_plotAcousticHarmonicResponse = QTreeWidgetItem(
            [self.name_child_plotAcousticHarmonicResponse])
        self.item_child_plotStressField = QTreeWidgetItem(
            [self.name_child_plotStressField])
        self.item_child_plotStructuralFrequencyResponse = QTreeWidgetItem(
            [self.name_child_plotStructuralFrequencyResponse])
        self.item_child_plotAcousticFrequencyResponse = QTreeWidgetItem(
            [self.name_child_plotAcousticFrequencyResponse])
        self.item_child_plot_TL_NR = QTreeWidgetItem(
            [self.name_child_plot_TL_NR])
        self.item_child_plot_reactions = QTreeWidgetItem(
            [self.name_child_plot_reactions])

    def _configItems(self):
        self.item_top_structuralmodelSetup.setFlags(Qt.ItemIsDragEnabled
                                                    | Qt.ItemIsUserCheckable
                                                    | Qt.ItemIsEnabled)
        self.item_top_structuralmodelSetup.setFont(0, self.font_top)
        self.item_top_structuralmodelSetup.setTextAlignment(0, Qt.AlignHCenter)
        self.item_top_structuralmodelSetup.setBackground(0, self.brush_top)

        self.item_top_acousticmodelSetup.setFlags(Qt.ItemIsDragEnabled
                                                  | Qt.ItemIsUserCheckable
                                                  | Qt.ItemIsEnabled)
        self.item_top_acousticmodelSetup.setFont(0, self.font_top)
        self.item_top_acousticmodelSetup.setTextAlignment(0, Qt.AlignHCenter)
        self.item_top_acousticmodelSetup.setBackground(0, self.brush_top)

        self.item_top_analysis.setFlags(Qt.ItemIsDragEnabled
                                        | Qt.ItemIsUserCheckable
                                        | Qt.ItemIsEnabled)
        self.item_top_analysis.setFont(0, self.font_top)
        self.item_top_analysis.setTextAlignment(0, Qt.AlignHCenter)
        self.item_top_analysis.setBackground(0, self.brush_top)

        self.item_top_resultsViewer.setFlags(Qt.ItemIsDragEnabled
                                             | Qt.ItemIsUserCheckable
                                             | Qt.ItemIsEnabled)
        self.item_top_resultsViewer.setFont(0, self.font_top)
        self.item_top_resultsViewer.setTextAlignment(0, Qt.AlignHCenter)
        self.item_top_resultsViewer.setBackground(0, self.brush_top)

        # self.item_child_setElementType.setDisabled(True)
        self.item_child_selectTheOutputResults.setDisabled(True)
        self.item_child_plotStressField.setDisabled(True)

    def _addItems(self):
        self.addTopLevelItem(self.item_top_structuralmodelSetup)
        self.addTopLevelItem(self.item_child_setElementType)
        self.addTopLevelItem(self.item_child_set_material)
        self.addTopLevelItem(self.item_child_set_crossSection)
        self.addTopLevelItem(self.item_child_setPrescribedDofs)
        self.addTopLevelItem(self.item_child_setNodalLoads)
        self.addTopLevelItem(self.item_child_addMassSpringDamper)

        self.addTopLevelItem(self.item_top_acousticmodelSetup)
        self.addTopLevelItem(self.item_child_set_fluid)
        self.addTopLevelItem(self.item_child_setAcousticPressure)
        self.addTopLevelItem(self.item_child_setVolumeVelocity)
        self.addTopLevelItem(self.item_child_setSpecificImpedance)
        self.addTopLevelItem(self.item_child_setRadiationImpedance)

        self.addTopLevelItem(self.item_top_analysis)
        self.addTopLevelItem(self.item_child_selectAnalysisType)
        self.addTopLevelItem(self.item_child_analisysSetup)
        self.addTopLevelItem(self.item_child_selectTheOutputResults)
        self.addTopLevelItem(self.item_child_runAnalysis)

        self.addTopLevelItem(self.item_top_resultsViewer)
        self.addTopLevelItem(self.item_child_plotStructuralModeShapes)
        self.addTopLevelItem(self.item_child_plotStructuralHarmonicResponse)
        self.addTopLevelItem(self.item_child_plotStructuralFrequencyResponse)
        self.addTopLevelItem(self.item_child_plotStressField)
        self.addTopLevelItem(self.item_child_plotAcousticModeShapes)
        self.addTopLevelItem(self.item_child_plotAcousticHarmonicResponse)
        self.addTopLevelItem(self.item_child_plotAcousticFrequencyResponse)
        self.addTopLevelItem(self.item_child_plot_TL_NR)
        self.addTopLevelItem(self.item_child_plot_reactions)

    def on_click_item(self, item, column):
        if item.text(0) == self.name_child_set_material:
            self.mainWindow.getInputWidget().set_material()
        elif item.text(0) == self.name_child_set_fluid:
            self.mainWindow.getInputWidget().set_fluid()
        elif item.text(0) == self.name_child_setAcousticPressure:
            self.mainWindow.getInputWidget().setAcousticPressure()
        elif item.text(0) == self.name_child_setVolumeVelocity:
            self.mainWindow.getInputWidget().setVolumeVelocity()
        elif item.text(0) == self.name_child_setSpecificImpedance:
            self.mainWindow.getInputWidget().setSpecificImpedance()
        elif item.text(0) == self.name_child_setRadiationImpedance:
            self.mainWindow.getInputWidget().setRadiationImpedance()
        elif item.text(0) == self.name_child_set_crossSection:
            self.mainWindow.getInputWidget().set_crossSection()
        elif item.text(0) == self.name_child_setElementType:
            self.mainWindow.getInputWidget().setElementType()
        elif item.text(0) == self.name_child_setPrescribedDofs:
            self.mainWindow.getInputWidget().setDOF()
        elif item.text(0) == self.name_child_setNodalLoads:
            self.mainWindow.getInputWidget().setNodalLoads()
        elif item.text(0) == self.name_child_addMassSpringDamper:
            self.mainWindow.getInputWidget().addMassSpringDamper()
        elif item.text(0) == self.name_child_selectAnalysisType:
            self.mainWindow.getInputWidget().analysisTypeInput()
            self._updateItems()
        elif item.text(0) == self.name_child_analisysSetup:
            self.mainWindow.getInputWidget().analysisSetup()
        elif item.text(0) == self.name_child_selectTheOutputResults:
            self.mainWindow.getInputWidget().analysisOutputResults()
        elif item.text(0) == self.name_child_runAnalysis:
            self.mainWindow.getInputWidget().runAnalysis()
            self._updateItems()
        elif item.text(0) == self.name_child_plotStructuralModeShapes:
            self.mainWindow.getInputWidget().plotStructuralModeShapes()
        elif item.text(0) == self.name_child_plotStructuralHarmonicResponse:
            self.mainWindow.getInputWidget().plotStructuralHarmonicResponse()
        elif item.text(0) == self.name_child_plotAcousticModeShapes:
            self.mainWindow.getInputWidget().plotAcousticModeShapes()
        elif item.text(0) == self.name_child_plotAcousticHarmonicResponse:
            self.mainWindow.getInputWidget().plotAcousticHarmonicResponse()
        elif item.text(0) == self.name_child_plotStressField:
            self.mainWindow.getInputWidget().plotStressField()
        elif item.text(0) == self.name_child_plotStructuralFrequencyResponse:
            self.mainWindow.getInputWidget().plotStructuralFrequencyResponse()
        elif item.text(0) == self.name_child_plotAcousticFrequencyResponse:
            self.mainWindow.getInputWidget().plotAcousticFrequencyResponse()
        elif item.text(0) == self.name_child_plot_TL_NR:
            self.mainWindow.getInputWidget().plot_TL_NR()
        elif item.text(0) == self.name_child_plot_reactions:
            self.mainWindow.getInputWidget().plot_reactions()

    def _updateItems(self):
        project = self.mainWindow.getProject()

        if True:
            self.item_child_plotStructuralModeShapes.setDisabled(True)
            self.item_child_plotStructuralHarmonicResponse.setDisabled(True)
            self.item_child_plotStructuralFrequencyResponse.setDisabled(True)
            self.item_child_plotAcousticModeShapes.setDisabled(True)
            self.item_child_plotAcousticFrequencyResponse.setDisabled(True)
            self.item_child_plotAcousticHarmonicResponse.setDisabled(True)
            self.item_child_plot_TL_NR.setDisabled(True)
            self.item_child_plot_reactions.setDisabled(True)

        if project.get_structural_solution(
        ) is not None or project.get_acoustic_solution() is not None:

            if project.analysis_ID == 0 or project.analysis_ID == 1:
                self.item_child_plotStructuralFrequencyResponse.setDisabled(
                    False)
                self.item_child_plotStructuralHarmonicResponse.setDisabled(
                    False)
                self.item_child_plot_reactions.setDisabled(False)
            elif project.analysis_ID == 2:
                self.item_child_plotStructuralModeShapes.setDisabled(False)
            elif project.analysis_ID == 4:
                self.item_child_plotAcousticModeShapes.setDisabled(False)
            elif project.analysis_ID == 3:
                self.item_child_plotAcousticFrequencyResponse.setDisabled(
                    False)
                self.item_child_plotAcousticHarmonicResponse.setDisabled(False)
                self.item_child_plot_TL_NR.setDisabled(False)
            elif project.analysis_ID in [5, 6]:
                self.item_child_plotStructuralFrequencyResponse.setDisabled(
                    False)
                self.item_child_plotAcousticFrequencyResponse.setDisabled(
                    False)
                self.item_child_plotStructuralHarmonicResponse.setDisabled(
                    False)
                self.item_child_plotAcousticHarmonicResponse.setDisabled(False)
                self.item_child_plot_TL_NR.setDisabled(False)
                self.item_child_plot_reactions.setDisabled(False)
Beispiel #38
0
    def setupUi(self, MainWindow):

        resolution = QDesktopWidget().screenGeometry(self)
        print("resol : ", resolution.size())
        MainWindow.resize(resolution.size())#1200 800
        #메인 화면 색상py
        self.setStyleSheet("color: black;"
                        "background-color: white;")

        font = QFont()
        font.setFamily("NanumGothic")
        MainWindow.setFont(font)
        self.centralwidget = QWidget(MainWindow)
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 20, 101, 31))
        font = QFont()
        font.setFamily("NanumGothic")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QRect(60, 730, 131, 34))
        #버튼 스타일 변경
        self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_add.setFont(staticValues.buttonFont)

        self.button_modi = QPushButton(self.centralwidget)
        self.button_modi.setGeometry(QRect(260, 730, 131, 34))
        self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_modi.setFont(staticValues.buttonFont)

        self.button_del = QPushButton(self.centralwidget)
        self.button_del.setGeometry(QRect(460, 730, 131, 34))
        self.button_del.setStyleSheet(staticValues.redButtonStyleSheet)
        self.button_del.setFont(staticValues.buttonFont)

        self.button_upload = QPushButton(self.centralwidget)
        self.button_upload.setGeometry(QRect(790, 730, 131, 34))
        self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_upload.setFont(staticValues.buttonFont)

        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QRect(40, 70, resolution.size().width()-180), resolution.size().height() - 80)
        self.tab = QWidget()
        self.tab.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab, "회원 목록")
        self.tableWidget = QTableWidget(self.tab)
        self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().height()-100, self.tabWidget.size().width()-30))
        self.tableWidget.setObjectName("회원 목록")
        self.tableWidget.setColumnCount(13)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근"
        , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"])
        
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(MainWindow)
Beispiel #39
0
    def init_ui(self):
        ''' Rembot UI '''
        self.setObjectName("CoreUI")

        # UI Contaier
        self.ui_container = QVBoxLayout(self)
        self.ui_container.setObjectName("ui_container")

        ## Header
        ### Box
        self.header_box = QHBoxLayout()
        self.header_box.setObjectName("header_box")
        self.header_box.setContentsMargins(10, 10, 10, 10)
        ### title
        font = QFont()
        font.setFamily("OCR A Extended")
        font.setPointSize(40)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.header_title = QLabel()
        self.header_title.setFont(font)
        self.header_title.setCursor(QCursor(Qt.ArrowCursor))
        self.header_title.setLayoutDirection(Qt.LeftToRight)
        self.header_title.setStyleSheet("color: rgb(108, 204, 227);")
        self.header_title.setScaledContents(False)
        self.header_title.setAlignment(Qt.AlignLeading | Qt.AlignLeft
                                       | Qt.AlignVCenter)
        self.header_title.setContentsMargins(0, 0, 0, 0)
        self.header_title.setObjectName("header_title")
        self.header_box.addWidget(self.header_title)  # add title to header
        ### version
        font = QFont()
        font.setFamily("Tahoma")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.version_number = QLabel()
        self.version_number.setFont(font)
        self.version_number.setStyleSheet("color: rgb(85, 85, 85);")
        self.version_number.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                         | Qt.AlignVCenter)
        self.version_number.setObjectName("version_number")
        self.header_box.addWidget(
            self.version_number)  # add version number to header

        # Add to UI Container
        self.ui_container.addLayout(
            self.header_box)  # add header box to layout

        # Content
        self.content_box = QHBoxLayout()
        self.content_box.setSizeConstraint(QLayout.SetDefaultConstraint)
        self.content_box.setContentsMargins(10, 10, 10, 10)
        self.content_box.setObjectName("content_box")
        ## Left Box
        self.left_box = QVBoxLayout()
        self.left_box.setSizeConstraint(QLayout.SetFixedSize)
        self.left_box.setContentsMargins(10, 10, 10, 10)
        self.left_box.setObjectName("left_box")
        ### File box
        self.file_box = QHBoxLayout()
        self.file_box.setContentsMargins(10, 10, 10, 10)
        self.file_box.setObjectName("file_box")
        #### File label
        font = QFont()
        font.setPointSize(10)
        self.file_label = QLabel()
        self.file_label.setFont(font)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.file_label.sizePolicy().hasHeightForWidth())
        self.file_label.setSizePolicy(size_policy)
        self.file_label.setObjectName("file_label")
        ### Add label to File box
        self.file_box.addWidget(self.file_label)

        #### File Input
        font = QFont()
        font.setPointSize(20)
        self.file_input = QLineEdit()
        self.file_input.setFont(font)
        self.file_input.setMinimumSize(QSize(0, 0))
        self.file_input.setAcceptDrops(True)
        self.file_input.setLayoutDirection(Qt.LeftToRight)
        self.file_input.setText("")
        self.file_input.setFrame(True)
        self.file_input.setAlignment(Qt.AlignLeading | Qt.AlignLeft
                                     | Qt.AlignVCenter)
        self.file_input.setObjectName("file_input")
        #### Add File input to File box
        self.file_box.addWidget(self.file_input)

        ### Add File box to Left Box
        self.left_box.addLayout(self.file_box)

        #### Add Button box
        self.button_box = QGridLayout()
        self.button_box.setContentsMargins(10, 10, 10, 10)
        self.button_box.setObjectName("button_box")
        ##### Start Button
        self.start_button = QPushButton()
        self.start_button.setObjectName("start_button")
        ##### Stop Button
        self.stop_button = QPushButton()
        self.stop_button.setEnabled(False)
        self.stop_button.setObjectName("stop_button")
        ##### Test Button
        self.abort_button = QPushButton()
        self.abort_button.setEnabled(False)
        self.abort_button.setObjectName("abort_button")
        ##### Quit Button
        self.quit_button = QPushButton()
        self.quit_button.setObjectName("quit_button")
        #### Add Buttons to Button Box
        self.button_box.addWidget(self.start_button, 0, 0, 1, 1)
        self.button_box.addWidget(self.stop_button, 0, 1, 1, 1)
        self.button_box.addWidget(self.abort_button, 1, 0, 1, 1)
        self.button_box.addWidget(self.quit_button, 1, 1, 1, 1)

        ### Add Button box to Left box
        self.left_box.addLayout(self.button_box)

        #### Log Box and Layout
        self.log_box = QGroupBox()
        self.log_box.setFlat(True)
        self.log_box.setObjectName("log_box")
        self.log_layout = QVBoxLayout(self.log_box)
        self.log_layout.setContentsMargins(0, 10, 0, 0)
        self.log_layout.setObjectName("log_layout")
        ##### Log output
        self.log_output = QTextEdit(self.log_box)
        self.log_output.setMinimumSize(QSize(720, 600))
        self.log_output.setReadOnly(True)
        self.log_output.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.log_output.setObjectName("log_output")
        #### Add Log Output to Log box | Log layout
        self.log_layout.addWidget(self.log_output)
        ### Add Log box to Left box
        self.left_box.addWidget(self.log_box)
        #### Left spacer
        self.spacer_item = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                       QSizePolicy.MinimumExpanding)
        ### Add spacer to Log box
        self.left_box.addItem(self.spacer_item)
        ## Add Left box to Content box
        self.content_box.addLayout(self.left_box)

        ### Right Box
        self.right_box = QVBoxLayout()
        self.right_box.setSizeConstraint(QLayout.SetMinAndMaxSize)
        self.right_box.setContentsMargins(10, 10, 10, 10)
        self.right_box.setObjectName("right_box")
        #### Origninal image box
        self.original_img_box = QGroupBox()
        self.original_img_box.setFlat(True)
        self.original_img_box.setObjectName("original_img_box")
        self.original_img_layout = QVBoxLayout(self.original_img_box)
        self.original_img_layout.setContentsMargins(0, 0, 0, 0)
        self.original_img_layout.setObjectName("original_img_layout")
        ##### Original image
        self.original_img = QLabel(self.original_img_box)
        self.original_img.setMinimumSize(QSize(720, 400))
        self.original_img.setText("")
        self.default_img = self.assets_path + "default.jpg"
        self.original_img.setPixmap(QPixmap(self.default_img))
        # self.original_img.setScaledContents(True)
        self.original_img.setObjectName("original_img")
        #### Add Original image to Original image Layout
        self.original_img_layout.addWidget(self.original_img)

        ### Add Original image box to Right box
        self.right_box.addWidget(self.original_img_box)

        #### Output image box
        self.output_img_box = QGroupBox()
        self.output_img_box.setFlat(True)
        self.output_img_box.setObjectName("output_img_box")
        self.output_img_layout = QHBoxLayout(self.output_img_box)
        self.output_img_layout.setContentsMargins(0, 0, 0, 0)
        self.output_img_layout.setObjectName("output_img_layout")
        ##### Output image
        self.output_img = QLabel(self.output_img_box)
        # self.output_img.setMinimumSize(QSize(720, 400))
        self.output_img.setText("")
        self.output_img.setPixmap(QPixmap(self.default_img))
        self.output_img.setObjectName("output_img")
        #### Add Output img to output image layout
        self.output_img_layout.addWidget(self.output_img)

        ### Add Output image box to Right box
        self.right_box.addWidget(self.output_img_box)

        ## Add Right box to Content box
        self.content_box.addLayout(self.right_box)

        # Add Content box to UI Container
        self.ui_container.addLayout(
            self.content_box)  # add content box to layout

        # Labelling
        self._translate = QCoreApplication.translate
        self.retranslate_ui()
        QMetaObject.connectSlotsByName(self)

        # Attach signals
        self.attach_events()
Beispiel #40
0
class EditorBase(QsciScintilla):
    ARROW_MARKER_NUM = 8
    _styleMarginsForegroundColor = QColor("#000000")
    _styleMarginsBackgroundColor = QColor("#000000")
    _styleBackgroundColor = QColor("#000000")

    def __init__(self, parent=None):
        super(EditorBase, self).__init__(parent)
        # don't allow editing by default
        self.setReadOnly(True)
        # Set the default font
        self.font = QFont()
        self.font.setFamily('Courier')
        self.font.setFixedPitch(True)
        self.font.setPointSize(12)
        self.setFont(self.font)

        # Margin 0 is used for line numbers
        self.setMarginsFont(self.font)
        self.set_margin_width(7)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QColor("#cccccc"))

        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, False)
        # setting marker margin width to zero make the marker highlight line
        self.setMarginWidth(1, 0)
        #self.matginClicked.connect(self.on_margin_clicked)
        self.markerDefine(QsciScintilla.Background, self.ARROW_MARKER_NUM)
        self.setMarkerBackgroundColor(QColor("#ffe4e4"), self.ARROW_MARKER_NUM)

        # Brace matching: enable for a brace immediately before or after
        # the current position
        #
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self.setCaretLineVisible(True)
        self.SendScintilla(QsciScintilla.SCI_GETCARETLINEVISIBLEALWAYS, True)
        self.setCaretLineBackgroundColor(QColor("#ffe4e4"))
        self.ensureLineVisible(True)

        # Set custom gcode lexer
        self.set_gcode_lexer()

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented
        # here: http://www.scintilla.org/ScintillaDoc.html)
        #self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTH, 700)
        self.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTHTRACKING)

        # default gray background
        self.set_background_color('#C0C0C0')
        self._stylebackgroundColor = '#C0C0C0'

        # not too small
        self.setMinimumSize(200, 100)
        self.filepath = None

    def setMarginsForegroundColor(self, color):
        super(EditorBase, self).setMarginsForegroundColor(color)
        self._styleMarginsForegroundColor = color

    def marginsForegroundColor(self):
        return self._styleMarginsForegroundColor

    def setMarginsBackgroundColor(self, color):
        super(EditorBase, self).setMarginsBackgroundColor(color)
        self._styleMarginsBackgroundColor = color

    def marginsBackgroundColor(self):
        return self._styleMarginsBackgroundColor

    def set_margin_width(self, width):
        fontmetrics = QFontMetrics(self.font)
        self.setMarginsFont(self.font)
        self.setMarginWidth(0, fontmetrics.width("0" * width) + 6)

    def setBackgroundColor(self, color):
        self._styleBackgroundColor = color
        self.set_background_color(color)

    def backgroundColor(self):
        return self._styleBackgroundColor

    # must set lexer paper background color _and_ editor background color it seems
    def set_background_color(self, color):
        self.SendScintilla(QsciScintilla.SCI_STYLESETBACK,
                           QsciScintilla.STYLE_DEFAULT, QColor(color))
        self.lexer.setPaperBackground(QColor(color))

    def on_margin_clicked(self, nmargin, nline, modifiers):
        # Toggle marker for the line the margin was clicked on
        if self.markersAtLine(nline) != 0:
            self.markerDelete(nline, self.ARROW_MARKER_NUM)
        else:
            self.markerAdd(nline, self.ARROW_MARKER_NUM)

    def set_python_lexer(self):
        self.lexer = QsciLexerPython()
        self.lexer.setDefaultFont(self.font)
        self.setLexer(self.lexer)
        #self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')

    def set_gcode_lexer(self):
        self.lexer = GcodeLexer(self)
        self.setLexer(self.lexer)

    def new_text(self):
        self.setText('')

    def load_text(self, filepath):
        self.filepath = filepath
        try:
            fp = os.path.expanduser(filepath)
            self.setText(open(fp).read())
        except:
            LOG.error('File path is not valid: {}'.format(filepath))
            self.setText('')
            return
        self.ensureCursorVisible()
        self.SendScintilla(QsciScintilla.SCI_VERTICALCENTRECARET)
        self.setModified(False)

    def save_text(self):
        with open(self.filepath + 'text', "w") as text_file:
            text_file.write(self.text())

    def replace_text(self, text):
        self.replace(text)

    def search(self,
               text,
               re=False,
               case=False,
               word=False,
               wrap=False,
               fwd=True):
Beispiel #41
0
        self.game_window = DoublePlayer()
        self.game_window.exitSignal.connect(self.game_over) # 游戏结束
        self.game_window.backSignal.connect(self.show) # 游戏
        self.game_window.show()

    def network_player(self):
        self.close()
        self.game_window = NetworkConfig(main_window=self)
        self.game_window.show()

    def game_over(self):
        sys.exit(app.exec_())

app = None
# 游戏运行的主逻辑
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    font = QFont()
    font.setFamily("微软雅黑")
    font.setPointSize(12)
    # palette = QPalette()
    # palette.setColor(QPalette.Text,QColor())
    w.setFont(font)
    w.show()
    # w.setPalette(palette)
    sys.exit(app.exec_())



    def setupUi(self, MainWindow):
        resolution = QDesktopWidget().screenGeometry(self)
        # MainWindow.setGeometry(QRect(0,0,0,0))
        MainWindow.setFixedSize(resolution.size().width()*0.99, resolution.size().height()*0.90)#1200 800
        # self.setWindowState(Qt.WindowMaximized)
        print("resol : ", MainWindow.size())

        #메인 화면 색상py
        self.setStyleSheet("color: black;"
                        "background-color: white;")

        font = QFont()
        font.setFamily("NanumGothic")
        MainWindow.setFont(font)
        self.centralwidget = QWidget(MainWindow)
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 20, 130, 35))
        font = QFont()
        font.setFamily("NanumGothic")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QRect(MainWindow.size().width()*0.05, MainWindow.size().height() - 80, 131, 34))
        #버튼 스타일 변경
        self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_add.setFont(staticValues.buttonFont)

        self.button_modi = QPushButton(self.centralwidget)
        self.button_modi.setGeometry(QRect(MainWindow.size().width()*0.20, MainWindow.size().height() - 80, 131, 34))
        self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_modi.setFont(staticValues.buttonFont)

        self.button_del = QPushButton(self.centralwidget)
        self.button_del.setGeometry(QRect(MainWindow.size().width()*0.35, MainWindow.size().height() - 80, 131, 34))
        self.button_del.setStyleSheet(staticValues.redButtonStyleSheet)
        self.button_del.setFont(staticValues.buttonFont)

        self.button_upload = QPushButton(self.centralwidget)
        self.button_upload.setGeometry(QRect(MainWindow.size().width()*0.7, MainWindow.size().height() - 80, 131, 34))
        self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_upload.setFont(staticValues.buttonFont)

        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QRect(10, 70, MainWindow.size().width()-15, MainWindow.size().height() - 180))
        self.tab = QWidget()
        self.tab.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab, "회원 목록")
        self.tableWidget = QTableWidget(self.tab)
        self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25))
        self.tableWidget.setColumnCount(13)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근"
        , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"])

        self.tab2 = QWidget()
        self.tab2.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab2, "중복 회원")

        self.label_updateDate = QLabel(self.tab2)
        self.label_updateDate.setGeometry(QRect(0, 20, 250, 35))
        self.label_updateDate.setStyleSheet("color: #838383;")

        self.tableWidget2 = QTableWidget(self.tab2)
        self.tableWidget2.setGeometry(QRect(0, 30, self.tabWidget.size().width()-5, self.tabWidget.size().height()-55))
        self.tableWidget2.setColumnCount(3)
        self.tableWidget2.setRowCount(0)
        self.tableWidget2.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "현재 단톡방", "중복 단톡방"])
        
        
        self.edit_search = QLineEdit(self.centralwidget)
        self.edit_search.setGeometry(QRect(MainWindow.size().width()-280, 35, 200, 30))
        self.edit_search.setStyleSheet(staticValues.solidStyleSheet)
        

        self.button_search = QPushButton(self.centralwidget)
        self.button_search.setGeometry(QRect(MainWindow.size().width()-80, 35, 70, 30))
        self.button_search.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_search.setFont(staticValues.buttonFont)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(MainWindow)
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if "windowtype" in kwargs:
            self.window_name = kwargs["windowtype"]
        else:
            self.window_name = "Add Object"

        self.resize(900, 500)
        self.setMinimumSize(QSize(300, 300))

        self.centralwidget = QWidget(self)
        self.setWidget(self.centralwidget)
        self.entity = None

        font = QFont()
        font.setFamily("Consolas")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.dummywidget = QWidget(self)
        self.dummywidget.setMaximumSize(0, 0)

        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setAlignment(Qt.AlignTop)
        self.verticalLayout.addWidget(self.dummywidget)

        self.setup_dropdown_menu()

        self.hbox1 = QHBoxLayout(self.centralwidget)
        self.hbox2 = QHBoxLayout(self.centralwidget)

        self.label1 = QLabel(self.centralwidget)
        self.label2 = QLabel(self.centralwidget)
        self.label3 = QLabel(self.centralwidget)
        self.label1.setText("Group")
        self.label2.setText("Position in Group")
        self.label3.setText("(-1 means end of Group)")
        self.group_edit = QLineEdit(self.centralwidget)
        self.position_edit = QLineEdit(self.centralwidget)

        self.group_edit.setValidator(QtGui.QIntValidator(0, 2**31 - 1))
        self.position_edit.setValidator(QtGui.QIntValidator(-1, 2**31 - 1))

        self.hbox1.setAlignment(Qt.AlignRight)
        self.hbox2.setAlignment(Qt.AlignRight)

        self.verticalLayout.addLayout(self.hbox1)
        self.verticalLayout.addLayout(self.hbox2)
        self.hbox1.addWidget(self.label1)
        self.hbox1.addWidget(self.group_edit)
        self.hbox2.addWidget(self.label2)
        self.hbox2.addWidget(self.position_edit)
        self.hbox2.addWidget(self.label3)

        self.group_edit.setDisabled(True)
        self.position_edit.setDisabled(True)

        self.editor_widget = None
        self.editor_layout = QScrollArea()  #QVBoxLayout(self.centralwidget)
        self.verticalLayout.addWidget(self.editor_layout)
        #self.textbox_xml = QTextEdit(self.centralwidget)
        self.button_savetext = QPushButton(self.centralwidget)
        self.button_savetext.setText("Add Object")
        self.button_savetext.setToolTip("Hotkey: Ctrl+S")
        self.button_savetext.setMaximumWidth(400)
        self.button_savetext.setDisabled(True)

        self.verticalLayout.addWidget(self.button_savetext)
        self.setWindowTitle(self.window_name)
        self.created_object = None
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setObjectName("lastmonthwidget")

        # Background image
        self.setStyleSheet(LinearStyle.get(self.objectName(), '#273B4F'))

        # Size
        self.setMaximumSize(240, 235)

        # ---- Content ----
        self.layout = QVBoxLayout()
        # -- Header --
        self.header = QLabel(self.tr("Last Month"))
        self.header.setStyleSheet(
            "background-color: rgba(0,0,0,0); margin-top: 15; margin-left: 8 ")
        font = QFont('Roboto', pointSize=20, weight=QFont.Bold)
        self.header.setFont(font)
        self.header.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        # -- Second Row : Changes --
        self.second_row = QHBoxLayout()
        self.second_row.setSpacing(0)
        self.second_row.setContentsMargins(0, 0, 0, 0)
        # Change (Fiat)
        change_fiat_value = dbhandler.get_change_last_month()
        change_fiat_value_str = "+" + \
            str(change_fiat_value) if change_fiat_value >= 0 else str(
                change_fiat_value)
        self.change_fiat = QLabel(change_fiat_value_str)
        self.change_fiat.setStyleSheet(
            "background-color: rgba(0,0,0,0); color:#D3EABD; margin-left: 8")
        font = QFont('Roboto', pointSize=15)
        self.change_fiat.setFont(font)
        self.change_fiat.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.second_row.addWidget(self.change_fiat)
        # Fiat label
        self.fiat_label = QLabel(confighandler.get_fiat_currency().upper())
        self.fiat_label.setStyleSheet(
            "background-color: rgba(0,0,0,0);color:#D3EABD; margin-top:10px")
        self.fiat_label.setFont(QFont('Roboto', pointSize=7))
        self.fiat_label.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.second_row.addWidget(self.fiat_label)
        # Change (%)
        first_total_wealth_current_month = dbhandler.get_first_total_wealth_current_month(
        )
        change_last_month = dbhandler.get_change_last_month()
        if first_total_wealth_current_month > 0:
            change_percentage = 100 * \
                (change_last_month /
                 first_total_wealth_current_month)
            change_percentage = round(change_percentage, 1)

            change_percentage_str = "+{}%".format(
                str(change_percentage
                    )) if change_percentage >= 0 else "{}%".format(
                        str(change_percentage))
        else:
            # No change this month
            change_percentage_str = "0%"

        self.change_percentage = QLabel(change_percentage_str)
        self.change_percentage.setStyleSheet(
            "background-color: rgba(0,0,0,0);color:#D3EABD; margin-right: 8")
        font = QFont()
        font.setFamily("Roboto")
        font.setPointSize(15)
        self.change_percentage.setFont(font)
        self.change_percentage.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.second_row.addWidget(self.change_percentage)

        # -- Chart --
        self.lastmonthchart = TotalWealthHistoryChartView(self)
        data = dbhandler.get_total_wealth_by_day_current_month()
        self.lastmonthchart.setupChartWithData(data)

        self.layout.addWidget(self.header)
        self.layout.addLayout(self.second_row)
        self.layout.addWidget(self.lastmonthchart)

        self.setLayout(self.layout)
Beispiel #45
0
    def defaultsPushButtonPressed(self, button):

        self.persepolis_setting.beginGroup('settings')

        self.setting_dict = returnDefaultSettings()

        self.tries_spinBox.setValue(int(self.setting_dict['max-tries']))
        self.wait_spinBox.setValue(int(self.setting_dict['retry-wait']))
        self.time_out_spinBox.setValue(int(self.setting_dict['timeout']))
        self.connections_spinBox.setValue(int(
            self.setting_dict['connections']))

        self.rpc_port_spinbox.setValue(int(self.setting_dict['rpc-port']))
        self.aria2_path_lineEdit.setText('')
        self.aria2_path_checkBox.setChecked(False)

        # wait-queue
        wait_queue_list = self.setting_dict['wait-queue']
        q_time = QTime(wait_queue_list[0], wait_queue_list[1])
        self.wait_queue_time.setTime(q_time)

        # save_as_tab
        self.download_folder_lineEdit.setText(
            str(self.setting_dict['download_path']))
        self.temp_download_lineEdit.setText(
            str(self.setting_dict['download_path_temp']))

        self.subfolder_checkBox.setChecked(True)

        # notifications_tab
        self.volume_label.setText('Volume : ' +
                                  str(self.setting_dict['sound-volume']))
        self.volume_dial.setValue(int(self.setting_dict['sound-volume']))

        # set style
        current_style_index = self.style_comboBox.findText(
            str(self.setting_dict['style']))
        self.style_comboBox.setCurrentIndex(current_style_index)

        # set language
        current_locale = self.lang_comboBox.findData(
            str(self.setting_dict['locale']))
        self.lang_comboBox.setCurrentIndex(current_locale)

        # set color_scheme
        current_color_index = self.color_comboBox.findText(
            str(self.setting_dict['color-scheme']))
        self.color_comboBox.setCurrentIndex(current_color_index)

        # set icons
        current_icons_index = self.icon_comboBox.findText(
            str(self.setting_dict['icons']))
        self.icon_comboBox.setCurrentIndex(current_icons_index)

        # set icons size
        current_icons_size_index = self.icons_size_comboBox.findText(
            str(self.setting_dict['toolbar_icon_size']))
        self.icons_size_comboBox.setCurrentIndex(current_icons_size_index)

        # set notification
        current_notification_index = self.notification_comboBox.findText(
            str(self.setting_dict['notification']))
        self.notification_comboBox.setCurrentIndex(current_notification_index)

        # set font
        self.font_checkBox.setChecked(False)
        font_setting = QFont()
        font_setting.setFamily(str(self.setting_dict['font']))
        self.fontComboBox.setCurrentFont(font_setting)

        self.font_size_spinBox.setValue(int(self.setting_dict['font-size']))

        # sound frame
        self.enable_notifications_checkBox.setChecked(True)

        # start_persepolis_if_browser_executed_checkBox
        self.start_persepolis_if_browser_executed_checkBox.setChecked(True)

        # hide window
        self.hide_window_checkBox.setChecked(True)

        # tray icon
        self.enable_system_tray_checkBox.setChecked(True)

        # after_download_checkBox
        self.after_download_checkBox.setChecked(True)

        # hide menubar for linux
        if platform.system == 'Darwin':
            self.show_menubar_checkbox.setChecked(True)
        else:
            self.show_menubar_checkbox.setChecked(False)

        # show side panel
        self.show_sidepanel_checkbox.setChecked(True)

        # show progress window
        self.show_progress_window_checkbox.setChecked(True)

        # run persepolis at startup checkBox
        self.startup_checkbox.setChecked(False)

        # keep_awake_checkBox
        self.keep_awake_checkBox.setChecked(False)

        # columns_tab
        self.column0_checkBox.setChecked(True)
        self.column1_checkBox.setChecked(True)
        self.column2_checkBox.setChecked(True)
        self.column3_checkBox.setChecked(True)
        self.column4_checkBox.setChecked(True)
        self.column5_checkBox.setChecked(True)
        self.column6_checkBox.setChecked(True)
        self.column7_checkBox.setChecked(True)
        self.column10_checkBox.setChecked(True)
        self.column11_checkBox.setChecked(True)
        self.column12_checkBox.setChecked(True)

        # video finder
        self.max_links_spinBox.setValue(3)

        # shortcuts
        self.shortcuts_list = [
            self.setting_dict['shortcuts/quit_shortcut'],
            self.setting_dict['shortcuts/hide_window_shortcut'],
            self.setting_dict['shortcuts/remove_shortcut'],
            self.setting_dict['shortcuts/delete_shortcut'],
            self.setting_dict['shortcuts/move_up_selection_shortcut'],
            self.setting_dict['shortcuts/move_down_selection_shortcut'],
            self.setting_dict['shortcuts/add_new_download_shortcut'],
            self.setting_dict['shortcuts/video_finder_shortcut'],
            self.setting_dict['shortcuts/import_text_shortcut']
        ]

        # add shortcuts to the shortcut_table
        j = 0
        for shortcut in self.shortcuts_list:
            item = QTableWidgetItem(shortcut)

            # align center
            item.setTextAlignment(0x0004 | 0x0080)

            # insert item in shortcut_table
            self.shortcut_table.setItem(j, 1, item)

            j = j + 1

        self.persepolis_setting.endGroup()
Beispiel #46
0
class AboutDialog(QDialog):
    def __init__(self, paths, os, parent=None):
        super().__init__(parent)

        self.paths = paths
        self.os = os

        self.setWindowTitle("About")
        self.resize(750, 500)
        self.show()

        self.layout = QHBoxLayout(self)
        self.scroll = QScrollArea(self)
        self.scroll.setWidgetResizable(True)
        self.scroll_widget_contents = QWidget()
        self.grid = QGridLayout(self.scroll_widget_contents)
        self.scroll.setWidget(self.scroll_widget_contents)
        self.layout.addWidget(self.scroll)

        self.default_font = QFont()
        self.default_font.setPointSize(Style.default_font)

        self.h1_font = QFont()
        self.h1_font.setPointSize(Style.h1_font)
        self.h1_font.setBold(True)

        if self.os == "Linux":
            self.default_font.setFamily(Style.mono_typeface_linux)
        else:
            self.default_font.setFamily(Style.mono_typeface_win)
            self.h1_font.setFamily(Style.default_typeface_win)

        self.init_ui()

    def init_ui(self):
        i = 0
        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        label = QLabel("Xincapio")
        label.setFont(self.h1_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        label = QLabel("Get IP address, MAC address and Disk Serial Number")
        label.setFont(self.default_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        self.grid.addWidget(hline, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        label = QLabel("Developer")
        label.setFont(self.h1_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        label = QLabel("Hajun Park")
        label.setFont(self.default_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        label = QLabel(
            '<a href="mailto:[email protected]">[email protected]</a>')
        label.setFont(self.default_font)
        label.linkActivated.connect(self.open_link)
        self.grid.addWidget(label, i, 1)
        i += 1

        label = QLabel(
            '<a href="https://github.com/jbaltop">https://github.com/jbaltop</a>'
        )
        label.setFont(self.default_font)
        label.linkActivated.connect(self.open_link)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        self.grid.addWidget(hline, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        label = QLabel("Version")
        label.setFont(self.h1_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        with open(self.paths["version"], encoding="utf-8") as fin:
            version = fin.read()[:-1]
        label = QLabel(version)
        label.setFont(self.default_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        self.grid.addWidget(hline, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        label = QLabel("License")
        label.setFont(self.h1_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)
        i += 1

        with open(self.paths["license"], encoding="utf-8") as fin:
            license = fin.read()
        label = QLabel(license)
        label.setFont(self.default_font)
        self.grid.addWidget(label, i, 1)
        i += 1

        blank_space = QSpacerItem(
            0,
            Style.section_border,
            QSizePolicy.Minimum,
            QSizePolicy.Minimum,
        )
        self.grid.addItem(blank_space, i, 1)

        i += 1
        self.grid.setColumnStretch(0, 1)
        self.grid.setColumnStretch(2, 1)
        self.grid.setRowStretch(i, 1)

    def open_link(self, url):
        QDesktopServices.openUrl(QUrl(url))
Beispiel #47
0
        def __init__(self, parent=None):
                QWidget.__init__(self, parent)
                self.setWindowTitle("SystemConfig")
                self.setMinimumSize(1200, 800)
                self.showMaximized()
                font = QFont()
                font.setFamily("MS Shell Dlg 2")
                self.setFont(font)
                self.centralwidget = QWidget(self)
                self.centralwidget.setGeometry(0, 0, 1280, 960)
                self.centralwidget.setObjectName("centralwidget")
        #         self.centralwidget.setStyleSheet("border-radius:0px;\n"
        # "background-color:rgb(255, 0, 0);\n"
        # "font-size:32px;\n"
        # "color:#fff;")

                





                self.setCentralWidget(self.centralwidget)
                self.box = QVBoxLayout(self.centralwidget)

                scroll = QScrollArea()
                content_widget = QWidget()
                scroll.setWidget(content_widget)
                scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
                scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
                scroll.setWidgetResizable(True) 

                lay = QVBoxLayout(content_widget)
                self.groupBox = QGroupBox()
                self.groupBox.setFont(QFont("Sanserif", 13))
                gridLayout = QGridLayout(self)

                self.body = QtWidgets.QFrame(self.centralwidget)
                self.body.setLocale(QtCore.QLocale(QtCore.QLocale.Thai, QtCore.QLocale.Thailand))
                self.body.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.body.setFrameShadow(QtWidgets.QFrame.Raised)
                self.body.setProperty("Color", QtGui.QColor(0, 0, 0))
                self.body.setObjectName("body")

                subBody_gridLayout = QGridLayout(self.body)
                self.groupBox_cal = QtWidgets.QGroupBox(self.body)
                self.groupBox_cal.setStyleSheet("border-radius: 5px;\n"
        "background-color:#rgb(158,158,158);\n"
        "border: 0px solid black") #groupBox Calculation setting
                self.groupBox_cal.setObjectName("groupBox")

                sub_groupbox_cal = QGridLayout(self.groupBox_cal)

                self.Label = QtWidgets.QLabel()#Topic_Cal
                self.Label.setAutoFillBackground(False)
                self.Label.setStyleSheet("border-radius: 0px;\n"
        "border: 0px solid black;\n font-size:20pt bold;\n background-color: transparent;");
                self.Label.setAlignment(QtCore.Qt.AlignCenter)

                self.widget_4 = QtWidgets.QWidget(self.groupBox_cal) #result1W
                self.widget_4.setStyleSheet("background-color:rgb(158, 158, 158);\n"
        "border: none")
                self.widget_4.setObjectName("widget_4")
                
                sub_GridCal_1 = QGridLayout(self.widget_4)

                self.label_5 = QtWidgets.QLabel(self.widget_4)#result1L
                self.label_5.setStyleSheet("align:\"center\";\n" "font-size:14pt;\n" "color:#fff")
                self.label_5.setObjectName("label_5")
                self.label_5.setText("Result1")

                sub_GridCal_1.addWidget( self.label_5,0,0)

                self.widget_5 = QtWidgets.QWidget(self.widget_4)#caliW1
                self.widget_5.setStyleSheet("background-color: rgb(255, 255, 255);\n"
        "border-radius: 0px;")
                self.widget_5.setObjectName("widget_5")
                sub_GridCal_1.addWidget(self.widget_5,2,0,1,3)

                sub_GridCal_1_1 = QGridLayout(self.widget_5)
                self.label_1_ = QtWidgets.QLabel(self.widget_5)#browse file1
                self.label_1_.setStyleSheet("background-color: rgb(255, 255, 255);\n""align:\"center\";\n" "font-size:14pt;\n" "color:#000;")
                self.label_1_.setAlignment(QtCore.Qt.AlignCenter)
                self.label_1_.setObjectName("label_1_")
                self.label_1_.setText("555")
                sub_GridCal_1_1.addWidget(self.label_1_,0,0,1,3)

                self.label_11 = QtWidgets.QLabel(self.widget_4)
                self.label_11.setGeometry(QtCore.QRect(10, 5, 300, 20)) #caliHeadL1
                self.label_11.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_11.setAlignment(QtCore.Qt.AlignCenter)
                self.label_11.setObjectName("label_11")
                self.label_11.setText("Calibration file1")
                sub_GridCal_1.addWidget(self.label_11, 1, 0, 1, 3)
                
                self.label_15 = QtWidgets.QLabel(self.widget_4)
                self.label_15.setGeometry(QtCore.QRect(3, 5, 100, 20)) #biasHeadL1
                self.label_15.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_15.setAlignment(QtCore.Qt.AlignCenter)
                self.label_15.setObjectName("label_15")
                sub_GridCal_1.addWidget(self.label_15, 1, 3 ,1 ,1)

                self.btn1 = QtWidgets.QPushButton(self.widget_5)
                self.btn1.setObjectName("btn1")
                self.btn1.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                sub_GridCal_1_1.addWidget(self.btn1,0,3,1,1)

                self.widget_12 = QtWidgets.QWidget(self.widget_4)#biasW1
                self.widget_12.setStyleSheet("border-radius: 0px;\n"
        "background-color: rgb(255, 255, 255); " "font-size:14pt")
                self.widget_12.setObjectName("widget_12")
                sub_GridCal_1.addWidget(self.widget_12,2,3,1,1)
                sub_GridCal_1_2 = QGridLayout(self.widget_12)
##spinbox4
                self.spinBox_4 = QtWidgets.QDoubleSpinBox((self.widget_12)) #biasL1
                self.spinBox_4.setObjectName("spinBox_4")
                sub_GridCal_1_2.addWidget(self.spinBox_4, 0, 0)
                self.spinBox_4.setMaximum(1000000)
                self.spinBox_4.setMinimum(-100000)

                self.widget_7 = QtWidgets.QWidget(self.groupBox_cal)
                self.widget_7.setGeometry(QtCore.QRect(80, 250, 450, 120)) #result2W
                self.widget_7.setStyleSheet("background-color:rgb(158, 158, 158);\n"
        "border: none")
                self.widget_7.setObjectName("widget_7")

                sub_GridCal_1 = QGridLayout(self.widget_7)
                self.label_6 = QtWidgets.QLabel(self.widget_7)#result2L
                self.label_6.setStyleSheet("align:\"center\";\n" "font-size:14pt;\n" "color:#fff")
                self.label_6.setObjectName("label_6")
                self.label_6.setText("Result2")
                sub_GridCal_1.addWidget( self.label_6,0,0)
                

                self.widget_8 = QtWidgets.QWidget(self.widget_7)#caliW2
                self.widget_8.setStyleSheet("background-color: rgb(255, 255, 255);\n"
        "border-radius: 0px;")
                self.widget_8.setObjectName("widget_8")
                sub_GridCal_1.addWidget(self.widget_8,2,0,1,3)

                sub_GridCal_1_1 = QGridLayout(self.widget_8)
                self.label_2_ = QtWidgets.QLabel(self.widget_8)#browse file2
                self.label_2_.setStyleSheet("background-color: rgb(255, 255, 255);\n""align:\"center\";\n" "font-size:14pt;\n" "color:#000;")
                self.label_2_.setAlignment(QtCore.Qt.AlignCenter)
                self.label_2_.setObjectName("label_2_")
                self.label_2_.setText("555")
                sub_GridCal_1_1.addWidget(self.label_2_,0,0,1,3)

                self.label_17 = QtWidgets.QLabel(self.widget_7)
                self.label_17.setGeometry(QtCore.QRect(10, 5, 300, 20)) #caliHeadL2
                self.label_17.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_17.setAlignment(QtCore.Qt.AlignCenter)
                self.label_17.setObjectName("label_17")
                self.label_17.setText("Calibration file2")
                sub_GridCal_1.addWidget(self.label_17, 1, 0, 1, 3)
                
                self.label_18 = QtWidgets.QLabel(self.widget_7)
                self.label_18.setGeometry(QtCore.QRect(3, 5, 100, 20)) #biasHeadL2
                self.label_18.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_18.setAlignment(QtCore.Qt.AlignCenter)
                self.label_18.setObjectName("label_18")
                sub_GridCal_1.addWidget(self.label_18, 1, 3 ,1 ,1)

                self.btn2 = QtWidgets.QPushButton(self.widget_8)
                self.btn2.setObjectName("btn2")
                self.btn2.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                sub_GridCal_1_1.addWidget(self.btn2,0,3,1,1)

                self.widget_17 = QtWidgets.QWidget(self.widget_7)#biasW2
                self.widget_17.setStyleSheet("border-radius: 0px;\n"
        "background-color: rgb(255, 255, 255);" "font-size:14pt")
                self.widget_17.setObjectName("widget_17")
                sub_GridCal_1.addWidget(self.widget_17,2,3,1,1)

                sub_GridCal_1_2 = QGridLayout(self.widget_17)
                self.spinBox_5 = QtWidgets.QDoubleSpinBox(self.widget_17) #biasL2
                self.spinBox_5.setObjectName("spinBox_5")
                sub_GridCal_1_2.addWidget(self.spinBox_5, 0,0)
                self.spinBox_5.setMaximum(1000000)
                self.spinBox_5.setMinimum(-100000)

                self.widget_9 = QtWidgets.QWidget(self.groupBox_cal)
                self.widget_9.setGeometry(QtCore.QRect(80, 400, 450, 120)) #result3W
                self.widget_9.setStyleSheet("background-color:rgb(158, 158, 158);\n"
        "border:none")
                self.widget_9.setObjectName("widget_9")


                sub_GridCal_1 = QGridLayout(self.widget_9)
                self.label_7 = QtWidgets.QLabel(self.widget_9)#result3L
                self.label_7.setStyleSheet("align:\"center\";\n" "font-size:14pt;\n" "color:#fff")
                self.label_7.setObjectName("label_7")
                self.label_7.setText("Result3")
                sub_GridCal_1.addWidget( self.label_7,0,0)

                self.widget_22 = QtWidgets.QWidget(self.widget_9)#caliW3
                self.widget_22.setStyleSheet("background-color: rgb(255, 255, 255);\n"
        "border-radius: 0px;")
                self.widget_22.setObjectName("widget_22")
                sub_GridCal_1.addWidget(self.widget_22,2,0,1,3)

                sub_GridCal_1_1 = QGridLayout(self.widget_22)
                self.label_3_ = QtWidgets.QLabel(self.widget_22)#browse file3
                self.label_3_.setStyleSheet("background-color: rgb(255, 255, 255);\n""align:\"center\";\n" "font-size:14pt;\n" "color:#000;")
                self.label_3_.setAlignment(QtCore.Qt.AlignCenter)
                self.label_3_.setObjectName("label_3_")
                self.label_3_.setText("555")
                sub_GridCal_1_1.addWidget(self.label_3_,0,0,1,3)

                self.label_19 = QtWidgets.QLabel(self.widget_9)
                self.label_19.setGeometry(QtCore.QRect(10, 5, 300, 20)) #caliHeadL3
                self.label_19.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_19.setAlignment(QtCore.Qt.AlignCenter)
                self.label_19.setObjectName("label_19")
                self.label_19.setText("Calibration file2")
                sub_GridCal_1.addWidget(self.label_19, 1, 0, 1, 3)
                
                self.label_20 = QtWidgets.QLabel(self.widget_9)
                self.label_20.setGeometry(QtCore.QRect(3, 5, 100, 20)) #biasHeadL3
                self.label_20.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_20.setAlignment(QtCore.Qt.AlignCenter)
                self.label_20.setObjectName("label_20")
                sub_GridCal_1.addWidget(self.label_20, 1, 3 ,1 ,1)

                self.btn3 = QtWidgets.QPushButton(self.widget_22)
                self.btn3.setObjectName("btn3")
                self.btn3.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                sub_GridCal_1_1.addWidget(self.btn3,0,3,1,1)

                self.widget_23 = QtWidgets.QWidget(self.widget_9)#biasW3
                self.widget_23.setStyleSheet("border-radius: 0px;\n"
        "background-color: rgb(255, 255, 255);" "font-size:14pt")
                self.widget_23.setObjectName("widget_17")
                sub_GridCal_1.addWidget(self.widget_23,2,3,1,1)

                sub_GridCal_1_2 = QGridLayout(self.widget_23)
                self.spinBox_6 = QtWidgets.QDoubleSpinBox(self.widget_23) #biasL3
                self.spinBox_6.setObjectName("spinBox_6")
                sub_GridCal_1_2.addWidget(self.spinBox_6, 0,0)
                self.spinBox_6.setMaximum(1000000)
                self.spinBox_6.setMinimum(-100000)


                self.widget_28 = QtWidgets.QWidget(self.groupBox_cal)#result4W
                self.widget_28.setStyleSheet("background-color:rgb(158, 158, 158);\n"
        "border:none")
                self.widget_28.setObjectName("widget_28")

                sub_GridCal_1 = QGridLayout(self.widget_28)
                self.label_8 = QtWidgets.QLabel(self.widget_28)#result4L
                self.label_8.setStyleSheet("align:\"center\";\n" "font-size:14pt;\n" "color:#fff")
                self.label_8.setObjectName("label_8")
                self.label_8.setText("Result4")
                sub_GridCal_1.addWidget( self.label_8,0,0)

                self.widget_29 = QtWidgets.QWidget(self.widget_28)#caliW4
                self.widget_29.setStyleSheet("background-color: rgb(255, 255, 255);\n"
        "border-radius: 0px;")
                self.widget_29.setObjectName("widget_29")
                sub_GridCal_1.addWidget(self.widget_29,2,0,1,3)

                sub_GridCal_1_1 = QGridLayout(self.widget_29)
                self.label_4_ = QtWidgets.QLabel(self.widget_29)#browse file4
                self.label_4_.setStyleSheet("background-color: rgb(255, 255, 255);\n""align:\"center\";\n" "font-size:14pt;\n" "color:#000;")
                self.label_4_.setAlignment(QtCore.Qt.AlignCenter)
                self.label_4_.setObjectName("label_4_")
                self.label_4_.setText("5556")
                sub_GridCal_1_1.addWidget(self.label_4_,0,0,1,3)

                self.label_21 = QtWidgets.QLabel(self.widget_28)
                self.label_21.setGeometry(QtCore.QRect(10, 5, 300, 20)) #caliHeadL4
                self.label_21.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_21.setAlignment(QtCore.Qt.AlignCenter)
                self.label_21.setObjectName("label_21")
                self.label_21.setText("Calibration file4")
                sub_GridCal_1.addWidget(self.label_21, 1, 0, 1, 3)
                
                self.label_22 = QtWidgets.QLabel(self.widget_28)
                self.label_22.setGeometry(QtCore.QRect(3, 5, 100, 20)) #biasHeadL4
                self.label_22.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_22.setAlignment(QtCore.Qt.AlignCenter)
                self.label_22.setObjectName("label_22")
                sub_GridCal_1.addWidget(self.label_22, 1, 3 ,1 ,1)

                self.btn4 = QtWidgets.QPushButton(self.widget_29)
                self.btn4.setObjectName("btn4")
                self.btn4.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                sub_GridCal_1_1.addWidget(self.btn4,0,3,1,1)

                self.widget_30 = QtWidgets.QWidget(self.widget_28)#biasW4
                self.widget_30.setStyleSheet("border-radius: 0px;\n"
        "background-color: rgb(255, 255, 255);" "font-size:14pt")
                self.widget_30.setObjectName("widget_30")
                sub_GridCal_1.addWidget(self.widget_30,2,3,1,1)

                sub_GridCal_1_2 = QGridLayout(self.widget_30)
                self.spinBox_7 = QtWidgets.QDoubleSpinBox(self.widget_30) #biasL4
                self.spinBox_7.setObjectName("spinBox_7")
                sub_GridCal_1_2.addWidget(self.spinBox_7, 0,0)
                self.spinBox_7.setMaximum(1000000)
                self.spinBox_7.setMinimum(-100000)



                self.widget_35 = QtWidgets.QWidget(self.groupBox_cal)#result5W
                self.widget_35.setStyleSheet("background-color:rgb(158, 158, 158);\n"
        "border:none")
                self.widget_35.setObjectName("widget_35")

                sub_GridCal_1 = QGridLayout(self.widget_35)
                self.label_9 = QtWidgets.QLabel(self.widget_35)#result5L
                self.label_9.setStyleSheet("align:\"center\";\n" "font-size:14pt;\n" "color:#fff")
                self.label_9.setObjectName("label_8")
                self.label_9.setText("Result5")
                sub_GridCal_1.addWidget( self.label_9,0,0)
                self.widget_36 = QtWidgets.QWidget(self.widget_35)#caliW5
                self.widget_36.setStyleSheet("background-color: rgb(255, 255, 255);\n"
        "border-radius: 0px;")
                self.widget_36.setObjectName("widget_36")
                sub_GridCal_1.addWidget(self.widget_36,2,0,1,3)

                sub_GridCal_1_1 = QGridLayout(self.widget_36)
                self.label_5_ = QtWidgets.QLabel(self.widget_36)#browse file5
                self.label_5_.setStyleSheet("background-color: rgb(255, 255, 255);\n""align:\"center\";\n" "font-size:14pt;\n" "color:#000;")
                self.label_5_.setAlignment(QtCore.Qt.AlignCenter)
                self.label_5_.setObjectName("label_5_")
                self.label_5_.setText("555")
                sub_GridCal_1_1.addWidget(self.label_5_,0,0,1,3)

                self.label_23 = QtWidgets.QLabel(self.widget_35)
                self.label_23.setGeometry(QtCore.QRect(10, 5, 300, 20)) #caliHeadL5
                self.label_23.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_23.setAlignment(QtCore.Qt.AlignCenter)
                self.label_23.setObjectName("label_23")
                self.label_23.setText("Calibration file5")
                sub_GridCal_1.addWidget(self.label_23, 1, 0, 1, 3)
                
                self.label_24 = QtWidgets.QLabel(self.widget_35)
                self.label_24.setGeometry(QtCore.QRect(3, 5, 100, 20)) #biasHeadL5
                self.label_24.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                self.label_24.setAlignment(QtCore.Qt.AlignCenter)
                self.label_24.setObjectName("label_24")
                sub_GridCal_1.addWidget(self.label_24, 1, 3 ,1 ,1)

                self.btn5 = QtWidgets.QPushButton(self.widget_36)
                self.btn5.setObjectName("btn5")
                self.btn5.setStyleSheet("background-color: rgb(236, 236, 236);\n"
        "border-radius:15px 50px 30px 5px;\n" "align:\"center\";\n"
        "font-size:14pt;")
                sub_GridCal_1_1.addWidget(self.btn5,0,3,1,1)

                self.widget_41 = QtWidgets.QWidget(self.widget_35)#biasW5
                self.widget_41.setStyleSheet("border-radius: 0px;\n"
        "background-color: rgb(255, 255, 255);" "font-size:14pt")
                self.widget_41.setObjectName("widget_41")
                sub_GridCal_1.addWidget(self.widget_41,2,3,1,1)
                
                sub_GridCal_1_2 = QGridLayout(self.widget_41)
                self.spinBox_8 = QtWidgets.QDoubleSpinBox(self.widget_41) #biasL5
                self.spinBox_8.setObjectName("spinBox_8")
                sub_GridCal_1_2.addWidget(self.spinBox_8, 0,0)
                self.spinBox_8.setMaximum(1000000)
                self.spinBox_8.setMinimum(-100000)


                sub_groupbox_cal.addWidget(self.Label , 0 , 0 , 1 , 6)
                sub_groupbox_cal.addWidget(self.widget_4 , 1 , 1 , 1 , 4)
                sub_groupbox_cal.addWidget(self.widget_7 , 2 , 1 , 1 , 4)
                sub_groupbox_cal.addWidget(self.widget_9 , 3 , 1 , 1 , 4)
                sub_groupbox_cal.addWidget(self.widget_28 , 4 , 1 , 1 , 4)
                sub_groupbox_cal.addWidget(self.widget_35 , 5 , 1 , 1 , 4)


                self.groupBox_Spec = QtWidgets.QGroupBox(self.body)
                self.groupBox_Spec.setStyleSheet("border-radius: 0px;\n"
        "border: 0px solid" "align:\"center\";\n")
                self.groupBox_Spec.setObjectName("groupBox_Spec")

                sub_GridSpec = QGridLayout(self.groupBox_Spec)

                self.groupBox_Spec_integration = QtWidgets.QGroupBox(self.groupBox_Spec)
                self.groupBox_Spec_integration.setStyleSheet("border-radius: 25px;\n"
        "color:#000000;\n" "background-color: rgb(217, 170, 251);\n" "font-size: 14pt;\n" "align:\"center\";\n" )

                sub_groupBox_Spec_integration = QGridLayout(self.groupBox_Spec_integration)



                self.Label_Spec = QtWidgets.QLabel(self.groupBox_Spec_integration)
                self.Label_Spec.setStyleSheet("color:black;\n"
                "border: none;\n" "font-size:14pt bold;\n")


                self.widget_6 = QtWidgets.QWidget(self.groupBox_Spec_integration)
                self.widget_6.setStyleSheet("align:\"center\";\n"
        "background-color: #ffffff;\n"
        "border:none;\n " "border-radius:25px; \n"  )
                self.widget_6.setObjectName("widget_6")


                integration = QGridLayout(self.widget_6)
                self.label_12 = QtWidgets.QLabel()#integrationL
                self.label_12.setObjectName("label_12")




                self.spinBox = QtWidgets.QSpinBox(self.widget_6)#integrationspinBox
                self.spinBox.setStyleSheet("border-color:rgb(158, 158, 158);\n"
        "background-color: #ffffff;\n""border-radius: 25px;\n" "font-size:14pt")
                self.spinBox.setObjectName("spinBox")
                self.label_16 = QtWidgets.QLabel(self.widget_6)
                self.label_16.setStyleSheet("align:\"center\";\n" "font-size:14pt;\n" "color:#00000")
                self.label_16.setObjectName("label_16")
                self.label_16.setAlignment(QtCore.Qt.AlignCenter)


                integration.addWidget(self.label_12,0,1)
                integration.addWidget(self.spinBox,0,2)
                integration.addWidget(self.label_16,0,3)


                sub_groupBox_Spec_integration.addWidget(self.Label_Spec,0,0)
                sub_groupBox_Spec_integration.addWidget(self.widget_6,1,0)


                self.groupBox_Spec_Wave = QtWidgets.QGroupBox(self.groupBox_Spec)
                self.groupBox_Spec_Wave.setStyleSheet("border-radius: 25px;\n"
        "border: 0px solid black;\n" "background-color: rgb(177, 217, 242);")

                sub_groupBox_Spec_Wave  = QGridLayout(self.groupBox_Spec_Wave)
                self.Label_Wave= QtWidgets.QLabel(self.groupBox_Spec_Wave)
                self.Label_Wave.setStyleSheet("color:#000000;\n"
                "border: none;\n" "font-size:14pt bold;\n")

                self.Label_Wave.setObjectName("Label_Wave")

                self.widget_10 = QtWidgets.QWidget(self.groupBox_Spec_Wave)
                self.widget_10.setStyleSheet("\n"
        "background-color: #ffffff;\n"
        "border:none;\n" )
                self.widget_10.setObjectName("widget_10")

                Wave = QGridLayout(self.widget_10)

                self.label_13 = QtWidgets.QLabel()#M_wavelength_L
                self.label_13.setStyleSheet("align:\"center\";\n" "font-size:20pt;\n" "color:#000000")
                self.label_13.setObjectName("label_13")

                self.spinBox_3 = QtWidgets.QSpinBox(self.widget_10)#N_wavelength_W
                self.spinBox_3.setStyleSheet("border-color:rgb(158, 158, 158);\n"
        "background-color: #ffffff;\n"
        "font-size:20pt;\n" "color:#000000\n")
                self.spinBox_3.setObjectName("spinBox_3")

                self.label_14 = QtWidgets.QLabel(self.widget_10)
                self.label_14.setStyleSheet("align:\"center\";\n" "font-size:20pt;\n" "color:#000000")
                self.label_14.setObjectName("label_14")

                self.spinBox_2 = QtWidgets.QSpinBox(self.widget_10)#boxN_wavelength_W
                self.spinBox_2.setStyleSheet("border-color:rgb(158, 158, 158);\n"
        "background-color: #ffffff;\n"
        "font-size:20pt;\n" "color:#000000\n")
                self.spinBox_2.setObjectName("spinBox_2")

                Wave.addWidget(self.label_13,0,0)
                Wave.addWidget(self.spinBox_3,0,1)
                Wave.addWidget(self.label_14,1,0)
                Wave.addWidget(self.spinBox_2,1,1)

                sub_groupBox_Spec_Wave.addWidget(self.Label_Wave,0,0)
                sub_groupBox_Spec_Wave.addWidget(self.widget_10,1,0)

                self.groupBox_Spec_Upload = QtWidgets.QGroupBox(self.groupBox_Spec)
                self.groupBox_Spec_Upload .setStyleSheet("border-radius: 0px;\n"
        "border: 0px solid black;\nbackground-color: transparent;")

                sub_groupBox_Spec_Upload  = QGridLayout(self.groupBox_Spec_Upload)
                self.Label_Upload= QtWidgets.QLabel(self.groupBox_Spec_Upload)
                self.Label_Upload.setStyleSheet("color:black;\n" "border-radius: 0px;\n"
                "border: 0px solid black;\n" "font-size:14pt bold;\n")

                self.Label_Upload.setObjectName("Label_Upload")

                self.widget_Upload = QtWidgets.QWidget(self.groupBox_Spec_Upload)
                self.widget_Upload .setStyleSheet("\n"
        "background-color: rgb(153, 153, 153);\n"
        "border-radius: 24px solid; \n")
                self.widget_Upload .setObjectName("widget_Upload")

                Upload = QGridLayout(self.widget_Upload)

                self.btn_Upload = QtWidgets.QPushButton(self.widget_Upload)
                self.btn_Upload.setStyleSheet("background-color: rgb(255, 255, 255);\n"
        "border-radius: 25px solid; \n"
        "background-color: rgb(153, 153, 153);\n"
        "font-size:28pt bold;\n"
        "color:#ffffff;\n")

                self.btn_Upload.setObjectName("btn_Upload")
                # self.btn_Upload.setIcon()
                Upload.addWidget(self.btn_Upload,0,0,2,1)
                self.btn_Upload.setFixedHeight(40)




                sub_groupBox_Spec_Upload.addWidget(self.Label_Upload,0,0)
                sub_groupBox_Spec_Upload.addWidget(self.widget_Upload,1,0)

                sub_GridSpec.addWidget(self.groupBox_Spec_integration,0,0)
                sub_GridSpec.addWidget(self.groupBox_Spec_Wave,1,0)
                sub_GridSpec.addWidget(self.groupBox_Spec_Upload,2,0)


                subBody_gridLayout.addWidget(self.groupBox_cal,0,0,1,3)
                subBody_gridLayout.addWidget(self.groupBox_Spec,0,3,1,1)

                gridLayout.addWidget(self.body,0, 0, 5, 6)

                self.frame = QtWidgets.QFrame(self.centralwidget)
                self.frame.setLocale(QtCore.QLocale(QtCore.QLocale.Thai, QtCore.QLocale.Thailand))
                self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame.setProperty("Color", QtGui.QColor(0, 0, 0))
                self.frame.setObjectName("frame")

                sub_gridLayout = QGridLayout(self.frame)
                self.pushButton_4 = QtWidgets.QPushButton(self.frame)
                self.pushButton_4.setStyleSheet("border-radius:30px;\n"
        "background-color:rgb(0, 170, 0);\n"
        "font-size:24px;\n"
        "color:#fff;")
                self.pushButton_4.setObjectName("pushButton_4")
                self.pushButton_3 = QtWidgets.QPushButton(self.frame)
                self.pushButton_3.setStyleSheet("border-radius:30px;\n"
        "background-color:#aa0000;\n"
        "font-size:24px;\n"
        "color:#fff;")
                self.pushButton_3.setObjectName("pushButton_3")

                self.pushButton_4.setFixedHeight(60)
                self.pushButton_3.setFixedHeight(60)
                sub_gridLayout.addWidget(QtWidgets.QLabel(self.body),0,0)
                sub_gridLayout.addWidget(self.pushButton_4,0,1)
                sub_gridLayout.addWidget(QtWidgets.QLabel(self.body),0,2)
                sub_gridLayout.addWidget(self.pushButton_3,0,3)
                sub_gridLayout.addWidget(QtWidgets.QLabel(self.body),0,4)

                gridLayout.addWidget(self.frame,5, 0, 1, 6)

                

                self.groupBox.setLayout(gridLayout)
                lay.addWidget(self.groupBox)
                # lay.addStretch()
                self.Label_Spec.setAlignment(QtCore.Qt.AlignCenter)
                self.Label_Wave.setAlignment(QtCore.Qt.AlignCenter)
                self.Label_Upload.setAlignment(QtCore.Qt.AlignCenter)
                # scroll.setFixedHeight(960)
                # scroll.setFixedWidth(1280)
                self.box.addWidget(scroll)
                self.pushButton_3.clicked.connect(self.close)
                # self.retranslateUi(self)

        
        
        # def setIcon(self):
                # appIcon = QIcon("icon.png")
                # MainWindow.setWindowIcon(appIcon)
        # def retranslateUi(self, MainWindow):
        #         _translate = QtCore.QCoreApplication.translate
                # MainWindow.setWindowTitle(_translate("MainWindow", "System Configuration"))
                self.pushButton_4.setText("APPLY")
                self.pushButton_3.setText("CANCEL")
                self.Label.setText("Calculation Setting")
                self.label_5.setText("Result1")


                self.label_11.setText("Calibration file1")
                self.label_15.setText("Bias")
                self.label_6.setText("Result2")


                self.label_17.setText("Calibration file2")
                self.label_18.setText("Bias")
                self.label_7.setText("Result3")

                self.btn_Upload.setText("Upload file")
                self.Label_Upload.setText("Directory Folder")



                self.label_19.setText("Calibration file3")
                self.label_20.setText("Bias")
                self.label_8.setText("Result4")
                self.label_1_.setText("....")
                self.label_2_.setText("....")
                self.label_3_.setText("....")
                self.label_4_.setText("....")
                self.label_5_.setText("....")

                self.label_21.setText("Calibration file4")
                self.label_22.setText("Bias")
                self.label_9.setText("Result5")

                
                self.label_23.setText("Calibration file5")
                self.label_24.setText("Bias")
                #self.groupBox_2.setTitle(_translate("MainWindow", "Spectrometer Setting"))
                self.Label_Spec.setText("Spectrometer Setting")
                self.label_12.setText("Integration time")
                self.label_16.setText("ms")
                #self.groupBox_3.setTitle(_translate("MainWindow", "Wave Length"))
                self.Label_Wave.setText("Wave Length")
                self.label_13.setText("N")
                self.label_14.setText( "M")
                # self.btnBack.setText(_translate("MainWindow", "Back"))
                self.btn1.setText("browse")
                self.btn2.setText("browse")
                self.btn3.setText("browse")
                self.btn4.setText("browse")
                self.btn5.setText("browse")
Beispiel #48
0
class TextView(QGraphicsView):
    def __init__(self, parent):
        super().__init__(parent)

        self.initUI()

    def initUI(self):

        self.scene = QGraphicsScene()
        self.pixmap = QPixmap("geo5.jpg")
        self.font = QFont("PT Sans", 16)
        self.basicFontSize = 16  # The font size before window scaling.
        self.fontRatio = 0.85 / 500.0  # The scaling ratio for the font.
        self.font.setBold(True)
        self.shadowSize = 5
        self.shadowRatio = 0.5 * self.shadowSize / float(16)
        self.shadowOffset = 2
        self.shadowOffsetRatio = self.shadowOffset / float(16)

        self.currentSlide = 0
        if self.readSong('praise-to-the-lord'):
            self.unrollSong()
            self.text = self.scene.addText(self.slides[0], self.font)
        else:
            self.text = self.scene.addText(
                "Praise to the Lord\nThe Almighty\nThe King of Creation",
                self.font)
        self.text.setDefaultTextColor(QColor(255, 255, 255))
        self.text.setFlags(QGraphicsItem.ItemIsSelectable
                           | QGraphicsItem.ItemIsMovable)
        self.text.setTextInteractionFlags(Qt.TextEditorInteraction)

        bylineFont = QFont("PT Sans", 11)
        self.byline = self.scene.addText(
            "Author: %s\nCopyright: %s" % (self.author, self.copyright),
            bylineFont)
        self.byline.setDefaultTextColor(QColor(255, 255, 255))

        self.setScene(self.scene)

    def resizeEvent(self, e):

        self.adjustText()
        self.scene.setSceneRect(QRectF(self.viewport().rect()))
        self.centerText()
        self.positionByline()

    def keyPressEvent(self, e):

        if not self.text.hasFocus():

            if e.key() == Qt.Key_Right:
                self.currentSlide += 1
                if self.currentSlide >= len(self.slides):
                    #Loop to beginning
                    self.currentSlide = 0
                self.text.setPlainText(self.slides[self.currentSlide])
                self.adjustText()
                self.centerText()

            elif e.key() == Qt.Key_Left:
                self.currentSlide -= 1
                if self.currentSlide < 0:
                    #Loop to end
                    self.currentSlide = len(self.slides) - 1
                self.text.setPlainText(self.slides[self.currentSlide])
                self.adjustText()
                self.centerText()

        super().keyPressEvent(e)

    def blur(self):

        shadow = QGraphicsBlurEffect()
        shadow.setBlurRadius(self.shadowSize)
        self.text.setGraphicsEffect(shadow)

    def shadow(self):

        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(self.shadowSize)
        shadow.setOffset(self.shadowOffset)
        self.text.setGraphicsEffect(shadow)

    def opacity(self):

        self.text.setGraphicsEffect(QGraphicsOpacityEffect())

    def noEffect(self):

        self.text.setGraphicsEffect(None)

    def bold(self, enabled):

        self.font.setBold(enabled)
        self.adjustText()
        self.centerText()

    def italic(self, enabled):

        self.font.setItalic(enabled)
        self.adjustText()
        self.centerText()

    def fontFamily(self, font):

        self.font.setFamily(font.family())
        self.adjustText()
        self.centerText()

    def fontSize(self, size):

        self.basicFontSize = int(size)
        self.adjustText()
        self.centerText()

    def drawBackground(self, qp, rect):

        # The rectangle is in "Scene coordinates".  mapFromScene converts to viewport coordinates
        # Not sure how scene coordinates and self.sceneRect() relate.
        # The QGraphicsView source code shows the how the rectangle is computed and passed in.
        viewRect = QRectF(self.mapFromScene(rect).boundingRect())

        # Need to scale the rectangle from viewport coordinates to pixmap coordinates
        # This is matrix algebra.
        scaleMatrix = QMatrix4x4()
        scaleMatrix.scale(
            float(self.pixmap.width()) / self.viewport().width(),
            float(self.pixmap.height()) / self.viewport().height())
        pixmapRect = scaleMatrix.mapRect(viewRect)

        # Now we have the target drawing buffer (rect in scene coordinates)
        # as well as the source drawing buffer (rect in pixmap coordinates).
        # We are sampling correctly from both.
        qp.drawPixmap(rect, self.pixmap, pixmapRect)

    def adjustText(self):

        fontSize = self.basicFontSize * self.fontRatio * self.viewport().width(
        )
        self.font.setPointSizeF(fontSize)
        self.shadowSize = int(fontSize * self.shadowRatio)
        self.shadowOffset = int(fontSize * self.shadowOffsetRatio)
        self.text.setFont(self.font)

        # Must do duck typing here because the object takes ownership
        # of its graphics effect object and deletes it when it's changed.
        try:
            self.text.graphicsEffect().setBlurRadius(self.shadowSize)
            self.text.graphicsEffect().setOffset(self.shadowOffset)
            self.text.graphicsEffect().update()
        except (AttributeError, TypeError):
            pass

    def centerText(self):

        # The center of the window
        windowWidth = self.viewport().width()
        windowHeight = self.viewport().height()
        centerPos = QPointF(float(windowWidth) / 2, float(windowHeight) / 2)

        # The desired new location
        rect = self.text.boundingRect()
        topLeftPos = centerPos - QPointF(rect.width() / 2, rect.height() / 2)

        # Any position of the text relative to the scene
        rectS = self.text.mapRectToScene(rect)

        # Move the text to the center position
        self.text.moveBy(topLeftPos.x() - rectS.x(),
                         topLeftPos.y() - rectS.y())

    def positionByline(self):

        windowHeight = self.viewport().height()
        rect = self.byline.boundingRect()

        # The desired new location (must subtract original text height to correct for initial position)
        topLeftHeight = windowHeight - float(rect.height())

        # Any position of the text relative to the scene
        rectS = self.byline.mapRectToScene(rect)

        self.byline.moveBy(0, topLeftHeight - rectS.y())

    def readSong(self, filename):

        try:
            with open(filename, 'r') as f:
                song = {}
                verseOrder = []
                slide = []
                label = ''
                for line in f:
                    if '-author:' in line:
                        self.author = line.partition(':')[2]
                        self.author = self.author.rstrip('\n')
                    elif '-copyright:' in line:
                        self.copyright = line.partition(':')[2]
                        self.copyright = self.copyright.rstrip('\n')
                    elif '---[' in line:
                        start = len('---[')
                        end = line.find(']---')
                        label = line[start:end]
                        label = label.replace(':', ' ')
                        if label not in song:
                            song[label] = []
                            verseOrder.append(label)
                        if slide:
                            #Flush slide
                            slideStr = ('').join(slide)
                            #Get rid of that last newline
                            slideStr = slideStr.rstrip('\n')
                            song[label].append(slideStr)
                            slide = []
                    else:
                        slide.append(line)

                #Flush last slide
                slideStr = ('').join(slide)
                #Get rid of that last newline
                slideStr = slideStr.rstrip('\n')
                song[label].append(slideStr)

                self.song = song
                self.verseOrder = verseOrder
                return True
        except (FileNotFoundError):
            print('%s not found' % filename)
            return False

    def unrollSong(self):

        self.slides = []
        for label in self.verseOrder:
            for item in self.song[label]:
                self.slides.append(item)
Beispiel #49
0
    def __init__(self, parent, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.parent = parent
        self.grandparent = parent.persepolis_main

        self.persepolis_setting.beginGroup('settings')

        # initialization
        self.tries_spinBox.setValue(
            int(self.persepolis_setting.value('max-tries')))
        self.wait_spinBox.setValue(
            int(self.persepolis_setting.value('retry-wait')))
        self.time_out_spinBox.setValue(
            int(self.persepolis_setting.value('timeout')))
        self.connections_spinBox.setValue(
            int(self.persepolis_setting.value('connections')))
        self.rpc_port_spinbox.setValue(
            int(self.persepolis_setting.value('rpc-port')))

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # wait_queue
        wait_queue_list = self.persepolis_setting.value('wait-queue')
        q_time = QTime(int(wait_queue_list[0]), int(wait_queue_list[1]))
        self.wait_queue_time.setTime(q_time)

        # change aria2 path
        self.aria2_path_pushButton.clicked.connect(self.changeAria2Path)
        self.aria2_path_checkBox.toggled.connect(self.ariaCheckBoxToggled)
        aria2_path = self.persepolis_setting.value('settings/aria2_path')

        self.aria2_path_lineEdit.setEnabled(False)
        if aria2_path != None:
            self.aria2_path_checkBox.setChecked(True)
            self.aria2_path_lineEdit.setText(str(aria2_path))

        self.ariaCheckBoxToggled('aria2')

        if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD':
            for widget in self.aria2_path_checkBox, self.aria2_path_lineEdit, self.aria2_path_pushButton:
                widget.hide()

        # save_as_tab
        self.download_folder_lineEdit.setText(
            str(self.persepolis_setting.value('download_path')))
        self.temp_download_lineEdit.setText(
            str(self.persepolis_setting.value('download_path_temp')))

        # subfolder
        if str(self.persepolis_setting.value('subfolder')) == 'yes':
            self.subfolder_checkBox.setChecked(True)
        else:
            self.subfolder_checkBox.setChecked(False)

        # notifications_tab
        self.volume_label.setText(
            'Volume : ' + str(self.persepolis_setting.value('sound-volume')))
        self.volume_dial.setValue(
            int(self.persepolis_setting.value('sound-volume')))

        # set style
        # if style_comboBox is changed, self.styleComboBoxChanged is called.
        self.style_comboBox.currentIndexChanged.connect(
            self.styleComboBoxChanged)

        # find available styles(It's depends on operating system and desktop environments).
        available_styles = QStyleFactory.keys()
        for style in available_styles:
            # 'GTK' or 'gtk' styles may cause to crashing! Eliminate them!
            if 'gtk' not in str(style) and 'GTK' not in str(style):
                self.style_comboBox.addItem(style)

        # System >> for system default style
        # when user select System for style section, the default system style is using.
        self.style_comboBox.addItem('System')

        current_style_index = self.style_comboBox.findText(
            str(self.persepolis_setting.value('style')))
        if current_style_index != -1:
            self.style_comboBox.setCurrentIndex(current_style_index)

        # available language
        available_language = [
            'en_US', 'fa_IR', 'zh_CN', 'fr_FR', 'pl_PL', 'nl_NL'
        ]
        for lang in available_language:
            self.lang_comboBox.addItem(str(QLocale(lang).nativeLanguageName()),
                                       lang)

        current_locale = self.lang_comboBox.findData(
            str(self.persepolis_setting.value('locale')))
        self.lang_comboBox.setCurrentIndex(current_locale)
        self.lang_comboBox.currentIndexChanged.connect(
            self.styleComboBoxChanged)
        self.styleComboBoxChanged()

        current_color_index = self.color_comboBox.findText(
            str(self.persepolis_setting.value('color-scheme')))
        self.color_comboBox.setCurrentIndex(current_color_index)

        self.current_icon = self.persepolis_setting.value('icons')

        # icon size
        size = ['128', '64', '48', '32', '24', '16']
        self.icons_size_comboBox.addItems(size)
        current_icons_size_index = self.icons_size_comboBox.findText(
            str(self.persepolis_setting.value('toolbar_icon_size')))
        self.icons_size_comboBox.setCurrentIndex(current_icons_size_index)

        # call iconSizeComboBoxCanged if index is changed
        self.icons_size_comboBox.currentIndexChanged.connect(
            self.iconSizeComboBoxCanged)

        self.iconSizeComboBoxCanged(1)

        # set notification
        notifications = ['Native notification', 'QT notification']
        self.notification_comboBox.addItems(notifications)
        current_notification_index = self.notification_comboBox.findText(
            str(self.persepolis_setting.value('notification')))
        self.notification_comboBox.setCurrentIndex(current_notification_index)

        # set font
        font_setting = QFont()
        font_setting.setFamily(str(self.persepolis_setting.value('font')))
        self.fontComboBox.setCurrentFont(font_setting)

        self.font_size_spinBox.setValue(
            int(self.persepolis_setting.value('font-size')))

        # sound frame
        self.sound_frame.setEnabled(False)
        self.enable_notifications_checkBox.toggled.connect(self.soundFrame)
        if str(self.persepolis_setting.value('sound')) == 'yes':
            self.enable_notifications_checkBox.setChecked(True)
        else:
            self.enable_notifications_checkBox.setChecked(False)

        # connect folder buttons
        self.download_folder_lineEdit.setEnabled(False)
        self.download_folder_pushButton.clicked.connect(
            self.downloadFolderPushButtonClicked)
        self.temp_download_lineEdit.setEnabled(False)
        self.temp_download_pushButton.clicked.connect(
            self.tempDownloadPushButtonClicked)

        # dial
        self.volume_dial.setNotchesVisible(True)
        self.volume_dial.valueChanged.connect(self.dialChanged)

        # start_persepolis_if_browser_executed_checkBox
        if str(self.persepolis_setting.value('browser-persepolis')) == 'yes':
            self.start_persepolis_if_browser_executed_checkBox.setChecked(True)
        else:
            self.start_persepolis_if_browser_executed_checkBox.setChecked(
                False)

        # hide window
        if str(self.persepolis_setting.value('hide-window')) == 'yes':
            self.hide_window_checkBox.setChecked(True)
        else:
            self.hide_window_checkBox.setChecked(False)

        # tray icon
        if str(self.persepolis_setting.value('tray-icon')) == 'yes':
            self.enable_system_tray_checkBox.setChecked(True)
        else:
            self.enable_notifications_checkBox.setChecked(False)

        # show_menubar
        if str(self.persepolis_setting.value('show-menubar')) == 'yes':
            self.show_menubar_checkbox.setChecked(True)
        else:
            self.show_menubar_checkbox.setChecked(False)

        if platform.system() == 'Darwin':
            self.show_menubar_checkbox.setChecked(True)
            self.show_menubar_checkbox.hide()

        # show_sidepanel
        if str(self.persepolis_setting.value('show-sidepanel')) == 'yes':
            self.show_sidepanel_checkbox.setChecked(True)
        else:
            self.show_sidepanel_checkbox.setChecked(False)

        # show ProgressWindow
        if str(self.persepolis_setting.value('show-progress')) == 'yes':
            self.show_progress_window_checkbox.setChecked(True)
        else:
            self.show_progress_window_checkbox.setChecked(False)

        # after download dialog
        if str(self.persepolis_setting.value('after-dialog')) == 'yes':
            self.after_download_checkBox.setChecked(True)
        else:
            self.after_download_checkBox.setChecked(False)

        # run persepolis at startup checkBox
        if str(self.persepolis_setting.value('startup')) == 'yes':
            self.startup_checkbox.setChecked(True)
        else:
            self.startup_checkbox.setChecked(False)

        # font_checkBox
        if str(self.persepolis_setting.value('custom-font')) == 'yes':
            self.font_checkBox.setChecked(True)
        else:
            self.font_checkBox.setChecked(False)

        self.fontCheckBoxState(self.font_checkBox)

        # keep_awake_checkBox
        if str(self.persepolis_setting.value('awake')) == 'yes':
            self.keep_awake_checkBox.setChecked(True)
        else:
            self.keep_awake_checkBox.setChecked(False)

        # columns_tab
        if str(self.persepolis_setting.value('column0')) == 'yes':
            self.column0_checkBox.setChecked(True)
        else:
            self.column0_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column1')) == 'yes':
            self.column1_checkBox.setChecked(True)
        else:
            self.column1_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column2')) == 'yes':
            self.column2_checkBox.setChecked(True)
        else:
            self.column2_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column3')) == 'yes':
            self.column3_checkBox.setChecked(True)
        else:
            self.column3_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column4')) == 'yes':
            self.column4_checkBox.setChecked(True)
        else:
            self.column4_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column5')) == 'yes':
            self.column5_checkBox.setChecked(True)
        else:
            self.column5_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column6')) == 'yes':
            self.column6_checkBox.setChecked(True)
        else:
            self.column6_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column7')) == 'yes':
            self.column7_checkBox.setChecked(True)
        else:
            self.column7_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column10')) == 'yes':
            self.column10_checkBox.setChecked(True)
        else:
            self.column10_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column11')) == 'yes':
            self.column11_checkBox.setChecked(True)
        else:
            self.column11_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column12')) == 'yes':
            self.column12_checkBox.setChecked(True)
        else:
            self.column12_checkBox.setChecked(False)

        # video_finder
        try:  # Integer casting may raise exception.
            self.max_links_spinBox.setValue(
                int(persepolis_setting.value('video_finder/max_links', 3)))
        except:
            pass

        # shortcuts
        self.qshortcuts_list = [
            self.parent.exitAction_shortcut,
            self.parent.minimizeAction_shortcut,
            self.parent.removeSelectedAction_shortcut,
            self.parent.deleteSelectedAction_shortcut,
            self.parent.moveUpSelectedAction_shortcut,
            self.parent.moveDownSelectedAction_shortcut,
            self.parent.addlinkAction_shortcut,
            self.parent.videoFinderAddLinkAction_shortcut,
            self.parent.addtextfileAction_shortcut
        ]

        self.shortcuts_list = [
            self.parent.exitAction_shortcut.key().toString(),
            self.parent.minimizeAction_shortcut.key().toString(),
            self.parent.removeSelectedAction_shortcut.key().toString(),
            self.parent.deleteSelectedAction_shortcut.key().toString(),
            self.parent.moveUpSelectedAction_shortcut.key().toString(),
            self.parent.moveDownSelectedAction_shortcut.key().toString(),
            self.parent.addlinkAction_shortcut.key().toString(),
            self.parent.videoFinderAddLinkAction_shortcut.key().toString(),
            self.parent.addtextfileAction_shortcut.key().toString()
        ]

        # add shortcuts to the shortcut_table
        j = 0
        for shortcut in self.shortcuts_list:
            item = QTableWidgetItem(shortcut)

            # align center
            item.setTextAlignment(0x0004 | 0x0080)

            # insert item in shortcut_table
            self.shortcut_table.setItem(j, 1, item)

            j = j + 1

        # If user doubleclicks on a row, then run showCaptureKeyboardWindow method
        self.shortcut_table.itemDoubleClicked.connect(
            self.showCaptureKeyboardWindow)

        # ok cancel default button
        self.cancel_pushButton.clicked.connect(self.close)
        self.defaults_pushButton.clicked.connect(
            self.defaultsPushButtonPressed)
        self.ok_pushButton.clicked.connect(self.okPushButtonPressed)

        # font_checkBox connect
        self.font_checkBox.stateChanged.connect(self.fontCheckBoxState)

        # saving initial value of self.persepolis_setting in self.first_key_value_dict
        # at the end! in the okPushButtonPressed method, first_key_value_dict will compared with second_key_value_dict.
        # if any thing changed , then a message box notify user about "some changes take effect after restarting persepolis".
        self.first_key_value_dict = {}
        for member in self.persepolis_setting.allKeys():
            self.first_key_value_dict[member] = str(
                self.persepolis_setting.value(member))

        self.persepolis_setting.endGroup()

        # setting window size and position
        size = self.persepolis_setting.value('PreferencesWindow/size',
                                             QSize(578, 565))
        position = self.persepolis_setting.value('PreferencesWindow/position',
                                                 QPoint(300, 300))

        self.resize(size)
        self.move(position)
Beispiel #50
0
    def initUI(self):

        main = QWidget(self)
        self.setCentralWidget(main)

        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.statusbar.showMessage(self.status)

        action_exit = QAction('Quit', self)
        action_exit.setShortcut('Ctrl+Q')
        action_exit.triggered.connect(qApp.quit)

        action_path = QAction('Data path', self)
        action_path.triggered.connect(self.path_dialog)

        action_mca = QAction('MCA', self)
        action_mca.triggered.connect(self.mca_settings)

        action_calib = QAction('Calibration', self)
        action_calib.triggered.connect(self.calibrate)

        menubar = self.menuBar()
        menu_file = menubar.addMenu('File')
        menu_file.addAction(action_path)
        menu_file.addAction(action_exit)

        menu_set = menubar.addMenu('Settings')
        menu_set.addAction(action_mca)
        menu_set.addAction(action_calib)

        fig, axes = plt.subplots(2, 2)
        self.figure = fig
        self.axes = axes

        self.init_axes()

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.onlyInt = QIntValidator()

        self.button_start = QPushButton('Start')
        self.button_start.setFixedWidth(70)
        self.button_start.clicked.connect(self.start)

        self.button_stop = QPushButton('Stop')
        self.button_stop.setFixedWidth(70)
        self.button_stop.clicked.connect(self.stop)

        self.label_file = QLabel()
        self.label_file.setText('Prefix')
        self.label_file.setFixedWidth(70)
        self.label_file.setAlignment(Qt.AlignRight)

        self.input_file = QLineEdit()
        self.input_file.setText('test')
        self.input_file.setFixedWidth(70)

        self.label_time = QLabel()
        self.label_time.setText('T = ')
        self.label_time.setFixedWidth(70)
        self.label_time.setAlignment(Qt.AlignRight)

        self.input_time = QLineEdit()
        self.input_time.setText('10')
        self.input_time.setFixedWidth(70)
        self.input_time.setValidator(self.onlyInt)

        self.progress = QProgressBar()
        self.progress.setMaximum(100)

        self.label_a0 = QLabel()
        self.label_a0.setText('A0 = ')
        self.label_a0.setFixedWidth(70)
        self.label_a0.setAlignment(Qt.AlignRight)

        self.input_a0 = QLineEdit()
        self.input_a0.setFixedWidth(70)
        self.input_a0.setAlignment(Qt.AlignLeft)
        self.input_a0.setText('0')
        self.input_a0.setValidator(self.onlyInt)

        self.label_a1 = QLabel()
        self.label_a1.setText('A1 = ')
        self.label_a1.setFixedWidth(70)
        self.label_a1.setAlignment(Qt.AlignRight)

        self.input_a1 = QLineEdit()
        self.input_a1.setFixedWidth(70)
        self.input_a1.setAlignment(Qt.AlignLeft)
        self.input_a1.setText('100')
        self.input_a1.setValidator(self.onlyInt)

        self.label_b0 = QLabel()
        self.label_b0.setText('B0 = ')
        self.label_b0.setFixedWidth(70)
        self.label_b0.setAlignment(Qt.AlignRight)

        self.input_b0 = QLineEdit()
        self.input_b0.setFixedWidth(70)
        self.input_b0.setAlignment(Qt.AlignLeft)
        self.input_b0.setText('0')
        self.input_b0.setValidator(self.onlyInt)

        self.label_b1 = QLabel()
        self.label_b1.setText('B1 = ')
        self.label_b1.setFixedWidth(70)
        self.label_b1.setAlignment(Qt.AlignRight)

        self.input_b1 = QLineEdit()
        self.input_b1.setFixedWidth(70)
        self.input_b1.setAlignment(Qt.AlignLeft)
        self.input_b1.setText('100')
        self.input_b1.setValidator(self.onlyInt)

        self.button_count = QPushButton('Sum')
        self.button_count.setFixedWidth(70)
        self.button_count.clicked.connect(self.count)

        self.count_label = QLabel()
        self.count_label.setText('N = ')
        self.count_label.setFixedWidth(70)
        self.count_label.setAlignment(Qt.AlignRight)

        self.count_input = QLineEdit()
        self.count_input.setFixedWidth(70)
        self.count_input.setAlignment(Qt.AlignLeft)
        self.count_input.setText('0')
        self.count_input.setReadOnly(True)

        self.button_fit = QPushButton('Fit peak')
        self.button_fit.setFixedWidth(70)
        self.button_fit.clicked.connect(self.fit)

        self.combo_fit = QComboBox()
        self.combo_fit.addItems(['A', 'B', 'dt'])

        self.label_fit = QLabel()
        self.label_fit.setText('Channel')
        self.label_fit.setFixedWidth(70)
        self.label_fit.setAlignment(Qt.AlignRight)

        font_fit = QFont()
        font_fit.setPointSize(11)
        font_fit.setFamily("Mono")

        self.input_fit = QPlainTextEdit()
        self.input_fit.setPlainText('')
        self.input_fit.setFont(font_fit)
        self.input_fit.setReadOnly(True)

        hline1 = QFrame()
        hline1.setFrameShape(QFrame.HLine)
        hline1.setFrameShadow(QFrame.Sunken)

        hline2 = QFrame()
        hline2.setFrameShape(QFrame.HLine)
        hline2.setFrameShadow(QFrame.Sunken)

        layout = QGridLayout()
        layout.addWidget(self.button_start, 0, 0)
        layout.addWidget(self.button_stop, 0, 1)
        layout.addWidget(self.label_file, 0, 2)
        layout.addWidget(self.input_file, 0, 3)
        layout.addWidget(self.label_time, 0, 4)
        layout.addWidget(self.input_time, 0, 5)
        layout.addWidget(self.progress, 0, 6, 1, 2)

        layout.addWidget(hline1, 1, 0, 1, 8)

        layout.addWidget(self.canvas, 2, 0, 1, 8)
        layout.addWidget(self.toolbar, 3, 0, 1, 8)

        layout.addWidget(hline2, 4, 0, 1, 8)

        layout.addWidget(self.label_a0, 5, 0)
        layout.addWidget(self.input_a0, 5, 1)
        layout.addWidget(self.label_a1, 5, 2)
        layout.addWidget(self.input_a1, 5, 3)
        layout.addWidget(self.input_fit, 5, 4, 4, 3)

        layout.addWidget(self.label_b0, 6, 0)
        layout.addWidget(self.input_b0, 6, 1)
        layout.addWidget(self.label_b1, 6, 2)
        layout.addWidget(self.input_b1, 6, 3)

        layout.addWidget(self.button_count, 7, 1)
        layout.addWidget(self.count_label, 7, 2)
        layout.addWidget(self.count_input, 7, 3)

        layout.addWidget(self.button_fit, 8, 1)
        layout.addWidget(self.label_fit, 8, 2)
        layout.addWidget(self.combo_fit, 8, 3)

        main.setLayout(layout)

        self.resize(1280, 960)
Beispiel #51
0
class Customize(QWidget):
    def __init__(self, app=None, palette=None):
        super().__init__()
        self.app = app
        self.palette = palette
        self.setFixedSize(800, 600)
        with open("default.json", "r") as selectedIndex:
            self.index = selectedIndex.read()
            if self.index == "":
                self.index = 0

            selectedIndex.close()
        self.conf = MessageBox()
        self.opened = False
        self.vbox = QVBoxLayout(self)  # Creating the layout

        self.setWindowIcon(QIcon('resources/Python-logo-notext.svg_.png'))

        self.initUI()

    def initUI(self):

        self.LayoutImage = QLabel(self)
        self.LayoutText = QLabel(self)

        self.hbox = QHBoxLayout()

        editor = config0['editor']

        self.font = QFont()
        self.font.setFamily(editor["editorFont"])
        self.font.setPointSize(editor["editorFontSize"])

        self.combo = QComboBox(self)
        self.combo.addItem("Theme 1")
        self.combo.addItem("Theme 2")
        self.combo.addItem("Theme 3")
        self.combo.currentIndexChanged.connect(self.themes)
        self.combo.setFont(self.font)

        self.theme1 = QPixmap(
            'resources/layout1.png')  # These are the pictures of themes
        self.theme2 = QPixmap('resources/layout1.png')
        self.theme3 = QPixmap('resources/layout1.png')

        self.vbox.addWidget(
            self.combo
        )  # Adding Combobox to vertical boxlayout so it would look better

        self.LayoutText.setFont(self.font)

        self.hbox.addWidget(self.LayoutText)
        self.hbox.addWidget(self.LayoutImage)

        self.LayoutImage.setPixmap(self.theme1)  # This is the "main" theme
        self.LayoutImage.resize(415, 287)

        self.LayoutText.setText("Dark theme")

        self.vbox.addLayout(self.hbox)

        self.selector = QPushButton(self)
        self.selector.setFixedSize(100, 30)
        self.selector.setLayoutDirection(Qt.RightToLeft)
        self.selector.setText("Select")
        self.selector.setFont(self.font)

        self.vbox.addWidget(self.selector)
        self.setLayout(self.vbox)

    def run(self):
        self.show()

    def themes(self, index):

        if index == 0:
            self.LayoutImage.setPixmap(self.theme1)
            self.LayoutText.setText("Dark theme")

        elif index == 1:

            self.LayoutImage.setPixmap(self.theme3)
            self.LayoutText.setText("Fancy theme")

        elif index == 2:

            self.LayoutImage.setPixmap(self.theme2)
            self.LayoutText.setText("Light theme")

        else:
            pass

    def test(self):
        index = self.combo.currentIndex()
        self.index = str(index)
        self.conf.confirmation(index + 1)
        with open("default.json", "w+") as write:
            write.write(str(self.index))
            write.close()
        if index == 0 and self.app is not None and self.palette is not None:
            editor = config0['editor']
            self.palette.setColor(QPalette.Window,
                                  QColor(editor["windowColor"]))
            self.palette.setColor(QPalette.WindowText,
                                  QColor(editor["windowText"]))
            self.palette.setColor(QPalette.Base, QColor(editor["editorColor"]))
            self.palette.setColor(QPalette.AlternateBase,
                                  QColor(editor["alternateBase"]))
            self.palette.setColor(QPalette.ToolTipBase,
                                  QColor(editor["ToolTipBase"]))
            self.palette.setColor(QPalette.ToolTipText,
                                  QColor(editor["ToolTipText"]))
            self.palette.setColor(QPalette.Text, QColor(editor["editorText"]))
            self.palette.setColor(QPalette.Button,
                                  QColor(editor["buttonColor"]))
            self.palette.setColor(QPalette.ButtonText,
                                  QColor(editor["buttonTextColor"]))
            self.palette.setColor(QPalette.Highlight,
                                  QColor(editor["HighlightColor"]).lighter())
            self.palette.setColor(QPalette.HighlightedText,
                                  QColor(editor["HighlightedTextColor"]))

        elif index == 1 and self.app is not None and self.palette is not None:
            editor = config1['editor']
            self.palette.setColor(QPalette.Window,
                                  QColor(editor["windowColor"]))
            self.palette.setColor(QPalette.WindowText,
                                  QColor(editor["windowText"]))
            self.palette.setColor(QPalette.Base, QColor(editor["editorColor"]))
            self.palette.setColor(QPalette.AlternateBase,
                                  QColor(editor["alternateBase"]))
            self.palette.setColor(QPalette.ToolTipBase,
                                  QColor(editor["ToolTipBase"]))
            self.palette.setColor(QPalette.ToolTipText,
                                  QColor(editor["ToolTipText"]))
            self.palette.setColor(QPalette.Text, QColor(editor["editorText"]))
            self.palette.setColor(QPalette.Button,
                                  QColor(editor["buttonColor"]))
            self.palette.setColor(QPalette.ButtonText,
                                  QColor(editor["buttonTextColor"]))
            self.palette.setColor(QPalette.Highlight,
                                  QColor(editor["HighlightColor"]).lighter())
            self.palette.setColor(QPalette.HighlightedText,
                                  QColor(editor["HighlightedTextColor"]))

        elif index == 2 and self.app is not None or self.palette is not None:
            editor = config2['editor']
            self.palette.setColor(QPalette.Window,
                                  QColor(editor["windowColor"]))
            self.palette.setColor(QPalette.WindowText,
                                  QColor(editor["windowText"]))
            self.palette.setColor(QPalette.Base, QColor(editor["editorColor"]))
            self.palette.setColor(QPalette.AlternateBase,
                                  QColor(editor["alternateBase"]))
            self.palette.setColor(QPalette.ToolTipBase,
                                  QColor(editor["ToolTipBase"]))
            self.palette.setColor(QPalette.ToolTipText,
                                  QColor(editor["ToolTipText"]))
            self.palette.setColor(QPalette.Text, QColor(editor["editorText"]))
            self.palette.setColor(QPalette.Button,
                                  QColor(editor["buttonColor"]))
            self.palette.setColor(QPalette.ButtonText,
                                  QColor(editor["buttonTextColor"]))
            self.palette.setColor(QPalette.Highlight,
                                  QColor(editor["HighlightColor"]).lighter())
            self.palette.setColor(QPalette.HighlightedText,
                                  QColor(editor["HighlightedTextColor"]))

        self.app.setPalette(self.palette)
    def __init__(self):
        super().__init__()

        # Other attributes...
        self.segmentation = None
        self.createdInputs = list()
        self.URLLabel = list()
        self.selectedURLLabel = list()
        self.newURL = u''
        self.newAnnotationKey = u''
        self.newAnnotationValue = u''
        self.infoBox = InfoBox(widget=self.controlArea)
        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            infoBoxAttribute='infoBox',
            sendIfPreCallback=self.updateGUI,
        )
        self.advancedSettings = AdvancedSettings(
            widget=self.controlArea,
            master=self,
            callback=self.sendButton.settingsChanged,
        )

        # GUI...

        # Advanced settings checkbox...
        self.advancedSettings.draw()

        # BASIC GUI...

        # Basic URL box
        basicURLBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Source',
            orientation='vertical',
            addSpace=False,
        )
        basicURLBoxLine1 = gui.widgetBox(
            widget=basicURLBox,
            box=False,
            orientation='horizontal',
        )
        gui.lineEdit(
            widget=basicURLBoxLine1,
            master=self,
            value='URL',
            orientation='horizontal',
            label=u'URL:',
            labelWidth=101,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"The URL whose content will be imported."),
        )
        gui.separator(widget=basicURLBox, height=3)
        advancedEncodingsCombobox = gui.comboBox(
            widget=basicURLBox,
            master=self,
            value='encoding',
            items=getPredefinedEncodings(),
            sendSelectedValue=True,
            orientation='horizontal',
            label=u'Encoding:',
            labelWidth=101,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Select URL's encoding."),
        )
        addSeparatorAfterDefaultEncodings(advancedEncodingsCombobox)
        addAutoDetectEncoding(advancedEncodingsCombobox)
        gui.separator(widget=basicURLBox, height=3)
        self.advancedSettings.basicWidgets.append(basicURLBox)
        self.advancedSettings.basicWidgetsAppendSeparator()

        # ADVANCED GUI...

        # URL box
        URLBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Sources',
            orientation='vertical',
            addSpace=False,
        )
        URLBoxLine1 = gui.widgetBox(
            widget=URLBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        self.fileListbox = gui.listBox(
            widget=URLBoxLine1,
            master=self,
            value='selectedURLLabel',
            labels='URLLabel',
            callback=self.updateURLBoxButtons,
            tooltip=(u"The list of URLs whose content will be imported.\n"
                     u"\nIn the output segmentation, the content of each\n"
                     u"URL appears in the same position as in the list.\n"
                     u"\nColumn 1 shows the URL.\n"
                     u"Column 2 shows the associated annotation (if any).\n"
                     u"Column 3 shows the associated encoding."),
        )
        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Courier)
        font.setPixelSize(12)
        self.fileListbox.setFont(font)
        URLBoxCol2 = gui.widgetBox(
            widget=URLBoxLine1,
            orientation='vertical',
        )
        self.moveUpButton = gui.button(
            widget=URLBoxCol2,
            master=self,
            label=u'Move Up',
            callback=self.moveUp,
            tooltip=(u"Move the selected URL upward in the list."),
        )
        self.moveDownButton = gui.button(
            widget=URLBoxCol2,
            master=self,
            label=u'Move Down',
            callback=self.moveDown,
            tooltip=(u"Move the selected URL downward in the list."),
        )
        self.removeButton = gui.button(
            widget=URLBoxCol2,
            master=self,
            label=u'Remove',
            callback=self.remove,
            tooltip=(u"Remove the selected URL from the list."),
        )
        self.clearAllButton = gui.button(
            widget=URLBoxCol2,
            master=self,
            label=u'Clear All',
            callback=self.clearAll,
            tooltip=(u"Remove all URLs from the list."),
        )
        self.exportButton = gui.button(
            widget=URLBoxCol2,
            master=self,
            label=u'Export List',
            callback=self.exportList,
            tooltip=(u"Open a dialog for selecting a file where the URL\n"
                     u"list can be exported in JSON format."),
        )
        self.importButton = gui.button(
            widget=URLBoxCol2,
            master=self,
            label=u'Import List',
            callback=self.importList,
            tooltip=(u"Open a dialog for selecting an URL list to\n"
                     u"import (in JSON format). URLs from this list will\n"
                     u"be added to those already imported."),
        )
        URLBoxLine2 = gui.widgetBox(
            widget=URLBox,
            box=False,
            orientation='vertical',
        )
        # Add URL box
        addURLBox = gui.widgetBox(
            widget=URLBoxLine2,
            box=True,
            orientation='vertical',
            addSpace=False,
        )
        gui.lineEdit(
            widget=addURLBox,
            master=self,
            value='newURL',
            orientation='horizontal',
            label=u'URL(s):',
            labelWidth=101,
            callback=self.updateGUI,
            tooltip=(u"The URL(s) that will be added to the list when\n"
                     u"button 'Add' is clicked.\n\n"
                     u"Successive URLs must be separated with ' / ' \n"
                     u"(space + slash + space). Their order in the list\n"
                     u" will be the same as in this field."),
        )
        gui.separator(widget=addURLBox, height=3)
        basicEncodingsCombobox = gui.comboBox(
            widget=addURLBox,
            master=self,
            value='encoding',
            items=getPredefinedEncodings(),
            sendSelectedValue=True,
            orientation='horizontal',
            label=u'Encoding:',
            labelWidth=101,
            callback=self.updateGUI,
            tooltip=(u"Select URL's encoding."),
        )
        addSeparatorAfterDefaultEncodings(basicEncodingsCombobox)
        addAutoDetectEncoding(basicEncodingsCombobox)
        self.encoding = self.encoding
        gui.separator(widget=addURLBox, height=3)
        gui.lineEdit(
            widget=addURLBox,
            master=self,
            value='newAnnotationKey',
            orientation='horizontal',
            label=u'Annotation key:',
            labelWidth=101,
            callback=self.updateGUI,
            tooltip=(u"This field lets you specify a custom annotation\n"
                     u"key associated with each URL that is about to be\n"
                     u"added to the list."),
        )
        gui.separator(widget=addURLBox, height=3)
        gui.lineEdit(
            widget=addURLBox,
            master=self,
            value='newAnnotationValue',
            orientation='horizontal',
            label=u'Annotation value:',
            labelWidth=101,
            callback=self.updateGUI,
            tooltip=(u"This field lets you specify the annotation value\n"
                     u"associated with the above annotation key."),
        )
        gui.separator(widget=addURLBox, height=3)
        self.addButton = gui.button(
            widget=addURLBox,
            master=self,
            label=u'Add',
            callback=self.add,
            tooltip=(u"Add the URL currently displayed in the 'URL'\n"
                     u"text field to the list."),
        )
        self.advancedSettings.advancedWidgets.append(URLBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # Options box...
        optionsBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Options',
            orientation='vertical',
            addSpace=False,
        )
        optionsBoxLine1 = gui.widgetBox(
            widget=optionsBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=optionsBoxLine1,
            master=self,
            value='importURLs',
            label=u'Import URLs with key:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Import URLs as annotations."),
        )
        self.importURLsKeyLineEdit = gui.lineEdit(
            widget=optionsBoxLine1,
            master=self,
            value='importURLsKey',
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotation key for importing URLs."),
        )
        gui.separator(widget=optionsBox, height=3)
        optionsBoxLine2 = gui.widgetBox(
            widget=optionsBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumber',
            label=u'Auto-number with key:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotate URLs with increasing numeric indices."),
        )
        self.autoNumberKeyLineEdit = gui.lineEdit(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumberKey',
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotation key for URL auto-numbering."),
        )
        gui.separator(widget=optionsBox, height=3)
        self.advancedSettings.advancedWidgets.append(optionsBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        gui.rubber(self.controlArea)

        # Send button...
        self.sendButton.draw()

        # Info box...
        self.infoBox.draw()

        self.adjustSizeWithTimer()
        QTimer.singleShot(0, self.sendButton.sendIf)
Beispiel #53
0
class StartMenuPage(QWidget):
    def __init__(self, musicPlayer):
        self.__WIDTH = 460
        self.__HEIGHT = 500
        self.__font = QFont()
        self.__font.setFamily("Comic Sans MS")
        super(StartMenuPage, self).__init__()
        self.resize(self.__WIDTH, self.__HEIGHT)
        self.setWindowTitle("Start Menu")
        self.setFixedSize(self.size())
        palette = QPalette()
        palette.setBrush(QPalette.Background,
                         QBrush(QPixmap("resources/background.jpg")))
        self.setPalette(palette)
        self.createLabel()
        self.createBtn()

        self.camera = ImgModule()
        self.camera.loadModelThread.start()
        self.musicPlayer = musicPlayer

    def createLabel(self):
        self.__label = QLabel(self)
        self.__label.setGeometry(QRect(12, 0, 450, 150))
        self.__pixmap = QPixmap("resources/logo.png")
        self.__label.setPixmap(self.__pixmap)
        self.__label2 = QLabel(self)
        self.__label2.setGeometry(QRect(17, 80, 450, 150))
        self.__pixmap = QPixmap("resources/logo2.png")
        self.__label2.setPixmap(self.__pixmap)

    def createBtn(self):
        button_style = """
            QPushButton {
                border: 2px solid #ffffff;
                border-radius: 10px;
                background-color: #f0b41d;
                color: #000000;
                
                min-width: 80px;
            }
            
            QPushButton:hover {
                color: #ffffff;
                background-color: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 1,
                                                  stop: 0 #000000, stop: 1 #00aaff);
            }
            
            QPushButton:pressed {
                background-color: #FFA823;
                color: #000000;
            }
        """
        self.__font.setPointSize(18)
        btn = QPushButton("Play", self)
        btn.setGeometry(QRect(160, 260, 120, 53))
        btn.setFont(self.__font)
        btn.setStyleSheet(button_style)
        btn.clicked.connect(self.jumpPage)
        btn2 = QPushButton("Exit", self)
        btn2.setGeometry(QRect(160, 350, 120, 53))
        btn2.setFont(self.__font)
        btn2.setStyleSheet(button_style)
        btn2.clicked.connect(self.closeScr)

    def jumpPage(self):
        self.__nextPage = ConnectionSetupPage(self.camera, self.musicPlayer)
        self.hide()
        self.__nextPage.show()

    def closeScr(self):
        sys.exit()
Beispiel #54
0
    def paint(self, painter):
        if self.points:
            color = self.select_line_color if self.selected else self.line_color
            pen = QPen(color)
            # Try using integer sizes for smoother drawing(?)
            # pen.setWidth(max(1, int(round(2.0 / self.scale))))
            pen.setWidth(max(1, int(round(5.0 / self.scale))))
            painter.setPen(pen)

            line_path = QPainterPath()
            vrtx_path = QPainterPath()

            line_path.moveTo(self.points[0])
            # Uncommenting the following line will draw 2 paths
            # for the 1st vertex, and make it non-filled, which
            # may be desirable.
            #self.draw_vertex(vrtx_path, 0)

            for i, p in enumerate(self.points):
                line_path.lineTo(p)
                self.draw_vertex(vrtx_path, i)
            if self.is_closed():
                line_path.lineTo(self.points[0])

            painter.drawPath(line_path)
            painter.drawPath(vrtx_path)
            painter.fillPath(vrtx_path, self.vertex_fill_color)

            # Draw text at the top-left
            if self.paint_label:
                min_x = sys.maxsize
                min_y = sys.maxsize
                for point in self.points:
                    min_x = min(min_x, point.x())
                    min_y = min(min_y, point.y())

                if min_x != sys.maxsize and min_y != sys.maxsize:
                    pen = QPen()
                    pen.setWidth(3)
                    pen.setColor(QColor(0, 0, 0))
                    painter.setRenderHint(QPainter.Antialiasing, True)
                    painter.setPen(pen)
                    linear_grad = QLinearGradient()
                    linear_grad.setColorAt(0, QColor(255, 255, 255))

                    font = QFont()
                    font.setPointSize(25)
                    font.setBold(True)
                    font.setFamily("Microsoft YaHei")

                    min_y += MIN_Y_LABEL
                    if len(self.label) > 0:
                        text_path = QPainterPath()
                        if self._current_label_text:
                            text_path.addText(min_x, min_y, font, self._current_label_text)
                        else:
                            text_path.addText(min_x, min_y, font, self.label[0])  # 应该取最后一个比较合理
                        painter.setBrush(linear_grad)
                        painter.drawPath(text_path)
                    min_y += 25

                    painter.setBrush(Qt.NoBrush)

            if self.fill:
                color = self.select_fill_color if self.selected else self.fill_color
                painter.fillPath(line_path, color)
Beispiel #55
0
    def __init__(self, parent=None):
        super(Modifier, self).__init__(parent)

        self.plotter = parent.plotterw  # This is where the plotting takes place (need to inform this widget about changes in the data)
        self.mdbinfo = parent.mdbinfo

        self.lblselect = QLabel('Select modifier:')
        self.cmbselect = QComboBox()
        self.lblcreate = QLabel('Create modifier:')
        self.txtcreate = QLineEdit('Modifier name')
        self.btncreate = QPushButton('Create')
        self.editor = QTextEdit()
        self.console = QTextEdit()
        self.btnapply = QPushButton('Apply')
        self.btndelete = QPushButton('Delete modifier')
        self.btnmakedefault = QPushButton('Make default')
        self.btnsave = QPushButton('Save modifier')

        # disable editing console
        self.console.setReadOnly(True)

        # configure "code" font
        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(12)
        self.editor.setFont(font)

        # set up tab length to 4 spaces
        metrics = QFontMetrics(font)
        self.editor.setTabStopWidth(4 * metrics.width(' '))

        self.editor.setStyleSheet('font-family: Courier;')
        self.editor.setAcceptRichText(False)

        self.cmbselect.currentIndexChanged[int].connect(self.changemod)
        self.btnapply.clicked.connect(self.apply)
        self.btnsave.clicked.connect(self.save)
        self.btndelete.clicked.connect(self.delete)
        self.btncreate.clicked.connect(self.create)
        self.btnmakedefault.clicked.connect(self.makedefault)

        h2 = QHBoxLayout()
        h2.addWidget(self.lblcreate)
        h2.addWidget(self.txtcreate)
        h2.addWidget(self.btncreate)

        h = QHBoxLayout()
        h.addWidget(self.btndelete)
        h.addWidget(self.btnsave)
        h.addWidget(self.btnmakedefault)
        h.addWidget(self.btnapply)

        l = QVBoxLayout()
        l.addWidget(self.cmbselect)
        l.addLayout(h2)
        l.addWidget(self.editor)
        l.addWidget(self.console)
        l.addLayout(h)

        self.setLayout(l)
Beispiel #56
0
class Content(QWidget):

    readyToShow = pyqtSignal(bool)

    def __init__(self,
                 text,
                 fileName,
                 baseName,
                 parent,
                 isReadOnly=False,
                 searchCommand=None):
        super().__init__()

        self.lazy = None
        if os.path.isfile(fileName):
            self.size_of_file = os.path.getsize(fileName)
            self.lazy = True  # If file exists then we can lazy load it

        else:
            self.size_of_file = 0
            self.lazy = False

        self.editor = Editor(self, isReadOnly)
        self.numberbar = NumberBar(self.editor)
        self.foldArea = FoldArea(self.editor)

        self.stack = []
        self.text = text
        self.parent = parent
        self.wordlist = wordList
        self.fileName = fileName
        self.baseName = baseName
        self.setting_up = 0
        self.temporary = 0

        self.searchCommand = searchCommand
        self.font = QFont()
        self.font.setFamily(editor["editorFont"])
        self.font.setPointSize(editor["editorFontSize"])
        self.tabSize = editor["TabWidth"]

        self.highlighter = PyHighlighter(self.editor)
        self.currentBlockCount = None
        self.saved = True
        self.editor.setPlainText(str(text))
        self.main_layout = QVBoxLayout(self)
        self.hbox = QHBoxLayout()

        self.status_bar_layout = QHBoxLayout()
        self.statusBarFont = QFont(editor["statusBarFont"],
                                   editor["statusBarFontSize"])
        self.columnLabel = StatusLabel(text="", font=self.statusBarFont)
        self.rowLabel = StatusLabel(text="", font=self.statusBarFont)
        self.totalLineLabel = StatusLabel(text="", font=self.statusBarFont)

        self.open_file = OpenFile()
        self.save_file = SaveFile(self)

        self.open_file.add_args(self.fileName, self.lazy)
        # Create a widget for the line numbers
        self.hbox.addWidget(self.numberbar)
        self.hbox.addWidget(self.foldArea)
        self.hbox.addWidget(self.editor)

        self.hbox.setSpacing(0)

        self.status_bar_layout.addWidget(self.columnLabel)
        self.status_bar_layout.addSpacing(10)
        self.status_bar_layout.addWidget(self.rowLabel)
        self.status_bar_layout.addSpacing(10)
        self.status_bar_layout.addWidget(self.totalLineLabel)
        self.status_bar_layout.addStretch()

        self.main_layout.addLayout(self.hbox)
        self.main_layout.addLayout(self.status_bar_layout)
        self.open_file.dataSignal.connect(
            self.insertText
        )  # This causes a bug if the cursor isn't in a position
        self.open_file.readDone.connect(self.readCompleted)
        # self.save_file.updateOffset.connect(lambda amount: self.change_offset(amount))

        self.open_file.readDone.connect(self.opening)
        # self.open_file.readAmountSignal.connect(self.prepare_to_save) lazy load [not working]
        # self.open_file.EndOfFileSignal.connect(self.EOF) lazy load [not working]

        self.IO_status = QLabel("Opening...")
        self.IO_status.setFont(self.font)

        self.save_file.readDone.connect(self.saving)

        self.line = None
        self.column = None
        # self.opening = True
        self.startLine = None
        self.endLine = None

        self.end = [False, 0]
        self.start_from = 0

        self.completer = Completer(self.wordlist)
        self.setCompleter(self.completer)

        if self.baseName.endswith(".py"):
            self.highlighter = PyHighlighter(self.editor.document(),
                                             self.editor)
        elif self.baseName.endswith(".doc"):
            self.highlighter = PyHighlighter(self.editor.document(),
                                             self.editor)

        self.editor.cursorPositionChanged.connect(self.change_col)
        # self.editor.textChanged.connect()

    def assignLines(self, array: list) -> None:

        self.startLine = array[0]
        self.endLine = array[1]

    def change_read_amount(self, amount: int) -> None:

        self.open_file.change_read_amount(amount)

    def change_offset(self, amount: int) -> None:

        self.open_file.change_offset(amount)

    def opening(self, state: bool) -> None:

        if state:
            self.readyToShow.emit(True)

    def saving(self, state: bool) -> None:

        if state:  # Saving has finished

            pass  # TODO: indicate that we have finished

        else:

            pass  # TODO: Indicate that we haven't finished

    def start_saving(self):

        self.save_file.add_args(self)
        self.save_file.start()

    def readCompleted(self, state: bool) -> None:

        if state:

            self.initialize(True)

    def initialize(self, justOpened=False):
        """
        After content is loaded into the file, this function will handle jump to definition when opening a file
        """
        QTest.qWait(5)  # Without this, it won't work

        if self.searchCommand:

            self.searchFor(self.searchCommand)

    def searchFor(self, searchCommand: str):

        regex = QRegExp(searchCommand)

        index = find_all(self.editor.toPlainText(), searchCommand)
        a = list(index)

        textCursor = self.editor.textCursor()
        try:
            textCursor.setPosition(a[0])
            textCursor.movePosition(textCursor.Right, textCursor.KeepAnchor,
                                    regex.matchedLength())
            self.editor.setTextCursor(textCursor)

        except Exception as E:
            pass

    def jumpToDef(self, tagList: list):

        tagInfo = tagList[0]
        fileName = tagList[1]
        searchCommand = tagList[2]

        if fileName.split("/")[-1] == self.baseName:
            self.searchFor(searchCommand)

        self.parent.cleanOpen(fileName, False, searchCommand)

    def EOF(self, data: list) -> None:
        """

        :param data[0]: bool
        :param data[1]: int
        :return: None
        """

        if data[0]:

            self.end = [*data]  # unpack the data

        else:  # this should never happen
            self.end = False

    def insertText(self, text: str) -> None:

        cursor = QTextCursor(self.editor.document())

        cursor.movePosition(QTextCursor.End)

        self.editor.setTextCursor(cursor)

        self.editor.insertPlainText(text)

    def prepare_to_save(self, array):

        currently_read_bytes = array[0]
        maximum_bytes = array[1]
        """If the user hasn't scrolled to the bottom
        (lazy loading isn't completed) and saves the file. no data gets lost"""
        self.start_from = currently_read_bytes

    def decide(self, array):  # Right now this function is not used anywhere
        """
        Decides if we lazy load text to the user or not
        :param array:
        :return: None
        """

        if not self.lazy:
            return
        else:
            text_size = len(self.editor.toPlainText().encode("utf-8"))
            if self.size_of_file != text_size:
                min_value = array[0]
                max_value = array[1]

                if min_value == max_value:
                    self.open_file.our_start()

    def start_opening(self):

        self.open_file.start()

    def change_col(self):
        textCursor = self.editor.textCursor()

        line = textCursor.blockNumber() + 1
        column = textCursor.positionInBlock()
        """self.status_bar.setText(
            "Line: "
            + str(line)
            + " Column: "
            + str(column)
            + "           Total: "
            + str(self.editor.totalLines() - 1)
            + " lines"
            + "     Size: "
            + str(self.size_of_file / 1000)
            + " KiB"
        )"""

        self.rowLabel.setText("Ln: {}".format(line))
        self.columnLabel.setText("Col: {}".format(column))
        self.totalLineLabel.setText("Total: {}".format(
            self.editor.totalLines()))

        self.editor.highlightCurrentLine()

    def get_size(self, input):
        return round(len(input.encode("utf-8")) / 1000)

    def leaveEvent(self, event: QEvent) -> None:

        self.editor.returnCursorToNormal()
        super().leaveEvent(event)

    def code_info(self, data):
        counter = 1
        keywords = {}
        text_array = data.splitlines()

        for w in text_array:
            word = w.strip()
            if word.startswith("class ") or word.startswith("def "):
                keywords[counter] = word.strip()

            counter += 1
        return keywords

    def tokenize_file(self):

        for i in tokenize(self.fileName):
            for j in i:
                if j not in self.wordlist:
                    self.wordlist.append(j)

    def setCompleter(self, completer):

        self.completer.setWidget(self)

        completer.setCompletionMode(QCompleter.PopupCompletion)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer = completer

        self.completer.insertText.connect(self.insertCompletion)

    def insertCompletion(self, completion):
        textCursor = self.editor.textCursor()

        extra = len(completion) - len(self.completer.completionPrefix())

        textCursor.movePosition(QTextCursor.Left)

        textCursor.movePosition(QTextCursor.EndOfWord)
        textCursor.insertText(completion[-extra:])

        if completion.endswith("()"):
            cursorPos = textCursor.position()
            textCursor.setPosition(cursorPos - 1)

        self.editor.setTextCursor(textCursor)

    def textUnderCursor(self):
        textCursor = self.editor.textCursor()
        textCursor.select(QTextCursor.WordUnderCursor)

        return textCursor.selectedText()

    def focusInEvent(self, event):
        if self.completer:
            self.completer.setWidget(self)
            QPlainTextEdit.focusInEvent(self, event)

    def checkIfCanComplete(self):

        pass

    def keyPressEvent(self, event):

        if (self.completer and self.completer.popup()
                and self.completer.popup().isVisible()):
            if event.key() in (
                    Qt.Key_Enter,
                    Qt.Key_Return,
                    Qt.Key_Escape,
                    Qt.Key_Tab,
                    Qt.Key_Backtab,
            ):
                event.ignore()
                return

        isShortcut = event.modifiers() == Qt.ControlModifier and event.key(
        ) == Qt.Key_B

        if not self.completer or not isShortcut:
            QPlainTextEdit.keyPressEvent(self.editor, event)

        completionPrefix = self.textUnderCursor()

        if not isShortcut:
            if self.completer.popup():
                self.completer.popup().hide()
            return

        self.completer.setCompletionPrefix(completionPrefix)

        popup = self.completer.popup()

        popup.setFont(self.font)
        popup.setCurrentIndex(self.completer.completionModel().index(0, 0))

        cr = self.editor.cursorRect()
        cr.translate(QPoint(10, 10))
        cr.setWidth(
            self.completer.popup().sizeHintForColumn(0) +
            self.completer.popup().verticalScrollBar().sizeHint().width())
        self.completer.complete(cr)

    def getTextCursor(self):
        textCursor = self.editor.textCursor()
        textCursorPos = textCursor.position()

        return textCursor, textCursorPos

    def changeSaved(self):
        self.modified = self.editor.is_modified()

        try:
            if self.modified:
                self.parent.setWindowTitle("Hydra ~ " + str(self.baseName) +
                                           " [UNSAVED]")

            else:
                pass

        except NameError as E:
            print(E, " on line 124 in the file Content.py")
    def setupUi(self, SplashScreen):
        if SplashScreen.objectName():
            SplashScreen.setObjectName(u"SplashScreen")
        SplashScreen.resize(680, 400)
        self.centralwidget = QWidget(SplashScreen)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(10, 10, 10, 10)
        self.dropShadowFrame = QFrame(self.centralwidget)
        self.dropShadowFrame.setObjectName(u"dropShadowFrame")
        self.dropShadowFrame.setStyleSheet(
            u"QFrame {\n"
            "        background-color: rgb(0, 51, 160);\n"
            "        color: rgb(220, 220, 220);\n"
            "        border-radius: 10px;\n"
            "}")
        self.dropShadowFrame.setFrameShape(QFrame.StyledPanel)
        self.dropShadowFrame.setFrameShadow(QFrame.Raised)
        self.label_title = QLabel(self.dropShadowFrame)
        self.label_title.setObjectName(u"label_title")
        self.label_title.setGeometry(QRect(0, 90, 661, 61))
        font = QFont()
        font.setFamily(u"Segoe UI")
        font.setPointSize(40)
        self.label_title.setFont(font)
        self.label_title.setStyleSheet(u"color:rgb(255,255,255)")
        self.label_title.setAlignment(Qt.AlignCenter)
        self.progressBar = QProgressBar(self.dropShadowFrame)
        self.progressBar.setObjectName(u"progressBar")
        self.progressBar.setGeometry(QRect(50, 280, 561, 23))
        self.progressBar.setStyleSheet(
            u"QProgressBar {\n"
            "\n"
            "        background-color: rgb(98, 114, 164);\n"
            "        color: rgb(255, 255, 255);\n"
            "        border-style: none;\n"
            "        border-radius: 10px;\n"
            "        text-align: center;\n"
            "}\n"
            "QProgressBar::chunk{\n"
            "        border-radius: 10px;\n"
            "        background-color: qlineargradient(spread:pad, x1:0, y1:0.511364, x2:1, y2:0.523, stop:0 rgba(255, 142, 62, 255), stop:1 rgba(206, 50, 11, 255));\n"
            "}")
        self.progressBar.setValue(24)
        self.label_loading = QLabel(self.dropShadowFrame)
        self.label_loading.setObjectName(u"label_loading")
        self.label_loading.setGeometry(QRect(0, 320, 661, 21))
        font1 = QFont()
        font1.setFamily(u"Segoe UI")
        font1.setPointSize(12)
        self.label_loading.setFont(font1)
        self.label_loading.setStyleSheet(u"color: rgb(255, 255, 255);")
        self.label_loading.setAlignment(Qt.AlignCenter)
        self.label_credits = QLabel(self.dropShadowFrame)
        self.label_credits.setObjectName(u"label_credits")
        self.label_credits.setGeometry(QRect(20, 350, 621, 21))
        font2 = QFont()
        font2.setFamily(u"Segoe UI")
        font2.setPointSize(10)
        self.label_credits.setFont(font2)
        self.label_credits.setStyleSheet(u"color: rgb(255, 255, 255);")
        self.label_credits.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                        | Qt.AlignVCenter)
        self.picture = QLabel(self.dropShadowFrame)
        self.picture.setObjectName(u"picture")
        self.picture.setEnabled(True)
        self.picture.setGeometry(QRect(280, 170, 91, 101))
        self.picture.setScaledContents(True)

        self.verticalLayout.addWidget(self.dropShadowFrame)

        SplashScreen.setCentralWidget(self.centralwidget)

        self.retranslateUi(SplashScreen)

        QMetaObject.connectSlotsByName(SplashScreen)
Beispiel #58
0
    def initUI(self):
        font = QFont()
        font.setFamily(u"Segoe UI")

        self.setFont(font)
        self.setStyleSheet(u"color: rgb(98, 103, 111);")
Beispiel #59
0
class ReTextWindow(QMainWindow):
	def __init__(self, parent=None):
		QMainWindow.__init__(self, parent)
		self.initConfig()
		self.resize(950, 700)
		screenRect = QDesktopWidget().screenGeometry()
		if globalSettings.windowGeometry:
			self.restoreGeometry(globalSettings.windowGeometry)
		else:
			self.move((screenRect.width()-self.width())/2, (screenRect.height()-self.height())/2)
		if not screenRect.contains(self.geometry()):
			self.showMaximized()
		if globalSettings.iconTheme:
			QIcon.setThemeName(globalSettings.iconTheme)
		if QFile.exists(icon_path+'retext.png'):
			self.setWindowIcon(QIcon(icon_path+'retext.png'))
		elif QFile.exists('/usr/share/pixmaps/retext.png'):
			self.setWindowIcon(QIcon('/usr/share/pixmaps/retext.png'))
		else:
			self.setWindowIcon(QIcon.fromTheme('retext',
				QIcon.fromTheme('accessories-text-editor')))
		self.editBoxes = []
		self.previewBoxes = []
		self.highlighters = []
		self.markups = []
		self.fileNames = []
		self.actionPreviewChecked = []
		self.actionLivePreviewChecked = []
		self.tabWidget = QTabWidget(self)
		self.initTabWidget()
		self.setCentralWidget(self.tabWidget)
		self.tabWidget.currentChanged.connect(self.changeIndex)
		self.tabWidget.tabCloseRequested.connect(self.closeTab)
		toolBar = QToolBar(self.tr('File toolbar'), self)
		self.addToolBar(Qt.TopToolBarArea, toolBar)
		self.editBar = QToolBar(self.tr('Edit toolbar'), self)
		self.addToolBar(Qt.TopToolBarArea, self.editBar)
		self.searchBar = QToolBar(self.tr('Search toolbar'), self)
		self.addToolBar(Qt.BottomToolBarArea, self.searchBar)
		toolBar.setVisible(not globalSettings.hideToolBar)
		self.editBar.setVisible(not globalSettings.hideToolBar)
		self.actionNew = self.act(self.tr('New'), 'document-new',
			self.createNew, shct=QKeySequence.New)
		self.actionNew.setPriority(QAction.LowPriority)
		self.actionOpen = self.act(self.tr('Open'), 'document-open',
			self.openFile, shct=QKeySequence.Open)
		self.actionOpen.setPriority(QAction.LowPriority)
		self.actionSetEncoding = self.act(self.tr('Set encoding'),
			trig=self.showEncodingDialog)
		self.actionSetEncoding.setEnabled(False)
		self.actionReload = self.act(self.tr('Reload'), 'view-refresh', trig=self.openFileMain)
		self.actionReload.setEnabled(False)
		self.actionSave = self.act(self.tr('Save'), 'document-save',
			self.saveFile, shct=QKeySequence.Save)
		self.actionSave.setEnabled(False)
		self.actionSave.setPriority(QAction.LowPriority)
		self.actionSaveAs = self.act(self.tr('Save as'), 'document-save-as',
			self.saveFileAs, shct=QKeySequence.SaveAs)
		self.actionNextTab = self.act(self.tr('Next tab'), 'go-next',
			lambda: self.switchTab(1), shct=Qt.CTRL+Qt.Key_PageDown)
		self.actionPrevTab = self.act(self.tr('Previous tab'), 'go-previous',
			lambda: self.switchTab(-1), shct=Qt.CTRL+Qt.Key_PageUp)
		self.actionPrint = self.act(self.tr('Print'), 'document-print',
			self.printFile, shct=QKeySequence.Print)
		self.actionPrint.setPriority(QAction.LowPriority)
		self.actionPrintPreview = self.act(self.tr('Print preview'), 'document-print-preview',
			self.printPreview)
		self.actionViewHtml = self.act(self.tr('View HTML code'), 'text-html', self.viewHtml)
		self.actionChangeFont = self.act(self.tr('Change default font'), trig=self.changeFont)
		self.actionSearch = self.act(self.tr('Find text'), 'edit-find', shct=QKeySequence.Find)
		self.actionSearch.setCheckable(True)
		self.actionSearch.triggered[bool].connect(self.searchBar.setVisible)
		self.searchBar.visibilityChanged.connect(self.searchBarVisibilityChanged)
		self.actionPreview = self.act(self.tr('Preview'), shct=Qt.CTRL+Qt.Key_E,
			trigbool=self.preview)
		if QIcon.hasThemeIcon('document-preview'):
			self.actionPreview.setIcon(QIcon.fromTheme('document-preview'))
		elif QIcon.hasThemeIcon('preview-file'):
			self.actionPreview.setIcon(QIcon.fromTheme('preview-file'))
		elif QIcon.hasThemeIcon('x-office-document'):
			self.actionPreview.setIcon(QIcon.fromTheme('x-office-document'))
		else:
			self.actionPreview.setIcon(QIcon(icon_path+'document-preview.png'))
		self.actionLivePreview = self.act(self.tr('Live preview'), shct=Qt.CTRL+Qt.Key_L,
		trigbool=self.enableLivePreview)
		self.actionTableMode = self.act(self.tr('Table mode'), shct=Qt.CTRL+Qt.Key_T,
			trigbool=lambda x: self.editBoxes[self.ind].enableTableMode(x))
		if ReTextFakeVimHandler:
			self.actionFakeVimMode = self.act(self.tr('FakeVim mode'),
				shct=Qt.CTRL+Qt.ALT+Qt.Key_V, trigbool=self.enableFakeVimMode)
			if globalSettings.useFakeVim:
				self.actionFakeVimMode.setChecked(True)
				self.enableFakeVimMode(True)
		self.actionFullScreen = self.act(self.tr('Fullscreen mode'), 'view-fullscreen',
			shct=Qt.Key_F11, trigbool=self.enableFullScreen)
		self.actionFullScreen.setPriority(QAction.LowPriority)
		self.actionConfig = self.act(self.tr('Preferences'), icon='preferences-system',
			trig=self.openConfigDialog)
		self.actionConfig.setMenuRole(QAction.PreferencesRole)
		self.actionSaveHtml = self.act('HTML', 'text-html', self.saveFileHtml)
		self.actionPdf = self.act('PDF', 'application-pdf', self.savePdf)
		self.actionOdf = self.act('ODT', 'x-office-document', self.saveOdf)
		self.getExportExtensionsList()
		self.actionQuit = self.act(self.tr('Quit'), 'application-exit', shct=QKeySequence.Quit)
		self.actionQuit.setMenuRole(QAction.QuitRole)
		self.actionQuit.triggered.connect(self.close)
		self.actionUndo = self.act(self.tr('Undo'), 'edit-undo',
			lambda: self.editBoxes[self.ind].undo(), shct=QKeySequence.Undo)
		self.actionRedo = self.act(self.tr('Redo'), 'edit-redo',
			lambda: self.editBoxes[self.ind].redo(), shct=QKeySequence.Redo)
		self.actionCopy = self.act(self.tr('Copy'), 'edit-copy',
			lambda: self.editBoxes[self.ind].copy(), shct=QKeySequence.Copy)
		self.actionCut = self.act(self.tr('Cut'), 'edit-cut',
			lambda: self.editBoxes[self.ind].cut(), shct=QKeySequence.Cut)
		self.actionPaste = self.act(self.tr('Paste'), 'edit-paste',
			lambda: self.editBoxes[self.ind].paste(), shct=QKeySequence.Paste)
		self.actionUndo.setEnabled(False)
		self.actionRedo.setEnabled(False)
		self.actionCopy.setEnabled(False)
		self.actionCut.setEnabled(False)
		qApp = QApplication.instance()
		qApp.clipboard().dataChanged.connect(self.clipboardDataChanged)
		self.clipboardDataChanged()
		if enchant_available:
			self.actionEnableSC = self.act(self.tr('Enable'), trigbool=self.enableSpellCheck)
			self.actionSetLocale = self.act(self.tr('Set locale'), trig=self.changeLocale)
		self.actionWebKit = self.act(self.tr('Use WebKit renderer'), trigbool=self.enableWebKit)
		self.actionWebKit.setChecked(globalSettings.useWebKit)
		self.actionShow = self.act(self.tr('Show directory'), 'system-file-manager', self.showInDir)
		self.actionFind = self.act(self.tr('Next'), 'go-next', self.find,
			shct=QKeySequence.FindNext)
		self.actionFindPrev = self.act(self.tr('Previous'), 'go-previous',
			lambda: self.find(back=True), shct=QKeySequence.FindPrevious)
		self.actionHelp = self.act(self.tr('Get help online'), 'help-contents', self.openHelp)
		self.aboutWindowTitle = self.tr('About %s', 'Example of final string: About ReText')
		self.aboutWindowTitle = self.aboutWindowTitle % app_name
		self.actionAbout = self.act(self.aboutWindowTitle, 'help-about', self.aboutDialog)
		self.actionAbout.setMenuRole(QAction.AboutRole)
		self.actionAboutQt = self.act(self.tr('About Qt'))
		self.actionAboutQt.setMenuRole(QAction.AboutQtRole)
		self.actionAboutQt.triggered.connect(qApp.aboutQt)
		availableMarkups = markups.get_available_markups()
		if not availableMarkups:
			print('Warning: no markups are available!')
		self.defaultMarkup = availableMarkups[0] if availableMarkups else None
		if globalSettings.defaultMarkup:
			mc = markups.find_markup_class_by_name(globalSettings.defaultMarkup)
			if mc and mc.available():
				self.defaultMarkup = mc
		if len(availableMarkups) > 1:
			self.chooseGroup = QActionGroup(self)
			markupActions = []
			for markup in availableMarkups:
				markupAction = self.act(markup.name, trigbool=self.markupFunction(markup))
				if markup == self.defaultMarkup:
					markupAction.setChecked(True)
				self.chooseGroup.addAction(markupAction)
				markupActions.append(markupAction)
		self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.Bold,
			trig=lambda: self.insertChars('**'))
		self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.Italic,
			trig=lambda: self.insertChars('*'))
		self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.Underline,
			trig=lambda: self.insertTag('u'))
		self.usefulTags = ('a', 'big', 'center', 'img', 's', 'small', 'span',
			'table', 'td', 'tr', 'u')
		self.usefulChars = ('deg', 'divide', 'dollar', 'hellip', 'laquo', 'larr',
			'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo',
			'rarr', 'rsquo', 'times')
		self.tagsBox = QComboBox(self.editBar)
		self.tagsBox.addItem(self.tr('Tags'))
		self.tagsBox.addItems(self.usefulTags)
		self.tagsBox.activated.connect(self.insertTag)
		self.symbolBox = QComboBox(self.editBar)
		self.symbolBox.addItem(self.tr('Symbols'))
		self.symbolBox.addItems(self.usefulChars)
		self.symbolBox.activated.connect(self.insertSymbol)
		self.updateStyleSheet()
		menubar = QMenuBar(self)
		menubar.setGeometry(QRect(0, 0, 800, 25))
		self.setMenuBar(menubar)
		menuFile = menubar.addMenu(self.tr('File'))
		menuEdit = menubar.addMenu(self.tr('Edit'))
		menuHelp = menubar.addMenu(self.tr('Help'))
		menuFile.addAction(self.actionNew)
		menuFile.addAction(self.actionOpen)
		self.menuRecentFiles = menuFile.addMenu(self.tr('Open recent'))
		self.menuRecentFiles.aboutToShow.connect(self.updateRecentFiles)
		menuFile.addMenu(self.menuRecentFiles)
		menuFile.addAction(self.actionShow)
		menuFile.addAction(self.actionSetEncoding)
		menuFile.addAction(self.actionReload)
		menuFile.addSeparator()
		menuFile.addAction(self.actionSave)
		menuFile.addAction(self.actionSaveAs)
		menuFile.addSeparator()
		menuFile.addAction(self.actionNextTab)
		menuFile.addAction(self.actionPrevTab)
		menuFile.addSeparator()
		menuExport = menuFile.addMenu(self.tr('Export'))
		menuExport.addAction(self.actionSaveHtml)
		menuExport.addAction(self.actionOdf)
		menuExport.addAction(self.actionPdf)
		if self.extensionActions:
			menuExport.addSeparator()
			for action, mimetype in self.extensionActions:
				menuExport.addAction(action)
			menuExport.aboutToShow.connect(self.updateExtensionsVisibility)
		menuFile.addAction(self.actionPrint)
		menuFile.addAction(self.actionPrintPreview)
		menuFile.addSeparator()
		menuFile.addAction(self.actionQuit)
		menuEdit.addAction(self.actionUndo)
		menuEdit.addAction(self.actionRedo)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionCut)
		menuEdit.addAction(self.actionCopy)
		menuEdit.addAction(self.actionPaste)
		menuEdit.addSeparator()
		if enchant_available:
			menuSC = menuEdit.addMenu(self.tr('Spell check'))
			menuSC.addAction(self.actionEnableSC)
			menuSC.addAction(self.actionSetLocale)
		menuEdit.addAction(self.actionSearch)
		menuEdit.addAction(self.actionChangeFont)
		menuEdit.addSeparator()
		if len(availableMarkups) > 1:
			self.menuMode = menuEdit.addMenu(self.tr('Default markup'))
			for markupAction in markupActions:
				self.menuMode.addAction(markupAction)
		menuFormat = menuEdit.addMenu(self.tr('Formatting'))
		menuFormat.addAction(self.actionBold)
		menuFormat.addAction(self.actionItalic)
		menuFormat.addAction(self.actionUnderline)
		menuEdit.addAction(self.actionWebKit)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionViewHtml)
		menuEdit.addAction(self.actionLivePreview)
		menuEdit.addAction(self.actionPreview)
		menuEdit.addAction(self.actionTableMode)
		if ReTextFakeVimHandler:
			menuEdit.addAction(self.actionFakeVimMode)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionFullScreen)
		menuEdit.addAction(self.actionConfig)
		menuHelp.addAction(self.actionHelp)
		menuHelp.addSeparator()
		menuHelp.addAction(self.actionAbout)
		menuHelp.addAction(self.actionAboutQt)
		menubar.addMenu(menuFile)
		menubar.addMenu(menuEdit)
		menubar.addMenu(menuHelp)
		toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
		toolBar.addAction(self.actionNew)
		toolBar.addSeparator()
		toolBar.addAction(self.actionOpen)
		toolBar.addAction(self.actionSave)
		toolBar.addAction(self.actionPrint)
		toolBar.addSeparator()
		toolBar.addAction(self.actionPreview)
		toolBar.addAction(self.actionFullScreen)
		self.editBar.addAction(self.actionUndo)
		self.editBar.addAction(self.actionRedo)
		self.editBar.addSeparator()
		self.editBar.addAction(self.actionCut)
		self.editBar.addAction(self.actionCopy)
		self.editBar.addAction(self.actionPaste)
		self.editBar.addSeparator()
		self.editBar.addWidget(self.tagsBox)
		self.editBar.addWidget(self.symbolBox)
		self.searchEdit = QLineEdit(self.searchBar)
		self.searchEdit.setPlaceholderText(self.tr('Search'))
		self.searchEdit.returnPressed.connect(self.find)
		self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar)
		self.searchBar.addWidget(self.searchEdit)
		self.searchBar.addSeparator()
		self.searchBar.addWidget(self.csBox)
		self.searchBar.addAction(self.actionFindPrev)
		self.searchBar.addAction(self.actionFind)
		self.searchBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
		self.searchBar.setVisible(False)
		self.autoSaveEnabled = globalSettings.autoSave
		if self.autoSaveEnabled:
			timer = QTimer(self)
			timer.start(60000)
			timer.timeout.connect(self.saveAll)
		self.ind = None
		if enchant_available:
			self.sl = globalSettings.spellCheckLocale
			if self.sl:
				try:
					enchant.Dict(self.sl)
				except Exception as e:
					print(e, file=sys.stderr)
					self.sl = None
			if globalSettings.spellCheck:
				self.actionEnableSC.setChecked(True)
				self.enableSpellCheck(True)
		self.fileSystemWatcher = QFileSystemWatcher()
		self.fileSystemWatcher.fileChanged.connect(self.fileChanged)

	def initConfig(self):
		self.font = None
		if globalSettings.font:
			self.font = QFont(globalSettings.font)
		if self.font and globalSettings.fontSize:
			self.font.setPointSize(globalSettings.fontSize)

	def updateStyleSheet(self):
		if globalSettings.styleSheet:
			sheetfile = QFile(globalSettings.styleSheet)
			sheetfile.open(QIODevice.ReadOnly)
			self.ss = QTextStream(sheetfile).readAll()
			sheetfile.close()
		else:
			self.ss = ''

	def initTabWidget(self):
		def dragEnterEvent(e):
			e.acceptProposedAction()
		def dropEvent(e):
			fn = bytes(e.mimeData().data('text/plain')).decode().rstrip()
			if fn.startswith('file:'):
				fn = QUrl(fn).toLocalFile()
			self.openFileWrapper(fn)
		self.tabWidget.setTabsClosable(True)
		self.tabWidget.setAcceptDrops(True)
		self.tabWidget.dragEnterEvent = dragEnterEvent
		self.tabWidget.dropEvent = dropEvent

	def act(self, name, icon=None, trig=None, trigbool=None, shct=None):
		if not isinstance(shct, QKeySequence):
			shct = QKeySequence(shct)
		if icon:
			action = QAction(self.actIcon(icon), name, self)
		else:
			action = QAction(name, self)
		if trig:
			action.triggered.connect(trig)
		elif trigbool:
			action.setCheckable(True)
			action.triggered[bool].connect(trigbool)
		if shct:
			action.setShortcut(shct)
		return action

	def actIcon(self, name):
		return QIcon.fromTheme(name, QIcon(icon_path+name+'.png'))

	def printError(self):
		import traceback
		print('Exception occured while parsing document:', file=sys.stderr)
		traceback.print_exc()

	def getSplitter(self, index):
		splitter = QSplitter(Qt.Horizontal)
		# Give both boxes a minimum size so the minimumSizeHint will be
		# ignored when splitter.setSizes is called below
		for widget in self.editBoxes[index], self.previewBoxes[index]:
			widget.setMinimumWidth(125)
			splitter.addWidget(widget)
		splitter.setSizes((50, 50))
		splitter.setChildrenCollapsible(False)
		return splitter

	def getWebView(self):
		webView = QWebView()
		if not globalSettings.handleWebLinks:
			webView.page().setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
			webView.page().linkClicked.connect(QDesktopServices.openUrl)
		webView.settings().setAttribute(QWebSettings.LocalContentCanAccessFileUrls, False)
		return webView

	def createTab(self, fileName):
		self.previewBlocked = False
		self.editBoxes.append(ReTextEdit(self))
		self.highlighters.append(ReTextHighlighter(self.editBoxes[-1].document()))
		if enchant_available and self.actionEnableSC.isChecked():
			self.highlighters[-1].dictionary = \
			enchant.Dict(self.sl) if self.sl else enchant.Dict()
			self.highlighters[-1].rehighlight()
		if globalSettings.useWebKit:
			self.previewBoxes.append(self.getWebView())
		else:
			self.previewBoxes.append(QTextBrowser())
			self.previewBoxes[-1].setOpenExternalLinks(True)
		self.previewBoxes[-1].setVisible(False)
		self.fileNames.append(fileName)
		markupClass = self.getMarkupClass(fileName)
		self.markups.append(self.getMarkup(fileName))
		self.highlighters[-1].docType = (markupClass.name if markupClass else '')
		liveMode = globalSettings.restorePreviewState and globalSettings.previewState
		self.actionPreviewChecked.append(liveMode)
		self.actionLivePreviewChecked.append(liveMode)
		metrics = QFontMetrics(self.editBoxes[-1].font())
		self.editBoxes[-1].setTabStopWidth(globalSettings.tabWidth * metrics.width(' '))
		self.editBoxes[-1].textChanged.connect(self.updateLivePreviewBox)
		self.editBoxes[-1].undoAvailable.connect(self.actionUndo.setEnabled)
		self.editBoxes[-1].redoAvailable.connect(self.actionRedo.setEnabled)
		self.editBoxes[-1].copyAvailable.connect(self.enableCopy)
		self.editBoxes[-1].document().modificationChanged.connect(self.modificationChanged)
		if globalSettings.useFakeVim:
			self.installFakeVimHandler(self.editBoxes[-1])
		return self.getSplitter(-1)

	def closeTab(self, ind):
		if self.maybeSave(ind):
			if self.tabWidget.count() == 1:
				self.tabWidget.addTab(self.createTab(""), self.tr("New document"))
			if self.fileNames[ind]:
				self.fileSystemWatcher.removePath(self.fileNames[ind])
			del self.editBoxes[ind]
			del self.previewBoxes[ind]
			del self.highlighters[ind]
			del self.markups[ind]
			del self.fileNames[ind]
			del self.actionPreviewChecked[ind]
			del self.actionLivePreviewChecked[ind]
			self.tabWidget.removeTab(ind)

	def getMarkupClass(self, fileName=None):
		if fileName is None:
			fileName = self.fileNames[self.ind]
		if fileName:
			markupClass = markups.get_markup_for_file_name(
				fileName, return_class=True)
			if markupClass:
				return markupClass
		return self.defaultMarkup

	def getMarkup(self, fileName=None):
		if fileName is None:
			fileName = self.fileNames[self.ind]
		markupClass = self.getMarkupClass(fileName=fileName)
		if markupClass and markupClass.available():
			return markupClass(filename=fileName)

	def docTypeChanged(self):
		oldType = self.highlighters[self.ind].docType
		markupClass = self.getMarkupClass()
		newType = markupClass.name if markupClass else ''
		if oldType != newType:
			self.markups[self.ind] = self.getMarkup()
			self.updatePreviewBox()
			self.highlighters[self.ind].docType = newType
			self.highlighters[self.ind].rehighlight()
		dtMarkdown = (newType == DOCTYPE_MARKDOWN)
		dtMkdOrReST = (newType in (DOCTYPE_MARKDOWN, DOCTYPE_REST))
		self.tagsBox.setEnabled(dtMarkdown)
		self.symbolBox.setEnabled(dtMarkdown)
		self.actionUnderline.setEnabled(dtMarkdown)
		self.actionBold.setEnabled(dtMkdOrReST)
		self.actionItalic.setEnabled(dtMkdOrReST)
		canReload = bool(self.fileNames[self.ind]) and not self.autoSaveActive()
		self.actionSetEncoding.setEnabled(canReload)
		self.actionReload.setEnabled(canReload)

	def changeIndex(self, ind):
		if ind > -1:
			self.actionUndo.setEnabled(self.editBoxes[ind].document().isUndoAvailable())
			self.actionRedo.setEnabled(self.editBoxes[ind].document().isRedoAvailable())
			self.actionCopy.setEnabled(self.editBoxes[ind].textCursor().hasSelection())
			self.actionCut.setEnabled(self.editBoxes[ind].textCursor().hasSelection())
			self.actionPreview.setChecked(self.actionPreviewChecked[ind])
			self.actionLivePreview.setChecked(self.actionLivePreviewChecked[ind])
			self.actionTableMode.setChecked(self.editBoxes[ind].tableModeEnabled)
			self.editBar.setDisabled(self.actionPreviewChecked[ind])
		self.ind = ind
		if self.fileNames[ind]:
			self.setCurrentFile()
		else:
			self.setWindowTitle(self.tr('New document') + '[*]')
			self.docTypeChanged()
		self.modificationChanged(self.editBoxes[ind].document().isModified())
		if globalSettings.restorePreviewState:
			globalSettings.previewState = self.actionLivePreviewChecked[ind]
		if self.actionLivePreviewChecked[ind]:
			self.enableLivePreview(True)
		self.editBoxes[self.ind].setFocus(Qt.OtherFocusReason)

	def changeFont(self):
		if not self.font:
			self.font = QFont()
		fd = QFontDialog.getFont(self.font, self)
		if fd[1]:
			self.font = QFont()
			self.font.setFamily(fd[0].family())
			settings.setValue('font', fd[0].family())
			self.font.setPointSize(fd[0].pointSize())
			settings.setValue('fontSize', fd[0].pointSize())
			self.updatePreviewBox()

	def preview(self, viewmode):
		self.actionPreviewChecked[self.ind] = viewmode
		if self.actionLivePreview.isChecked():
			self.actionLivePreview.setChecked(False)
			return self.enableLivePreview(False)
		self.editBar.setDisabled(viewmode)
		self.editBoxes[self.ind].setVisible(not viewmode)
		self.previewBoxes[self.ind].setVisible(viewmode)
		if viewmode:
			self.updatePreviewBox()

	def enableLivePreview(self, livemode):
		if globalSettings.restorePreviewState:
			globalSettings.previewState = livemode
		self.actionLivePreviewChecked[self.ind] = livemode
		self.actionPreviewChecked[self.ind] = livemode
		self.actionPreview.setChecked(livemode)
		self.editBar.setEnabled(True)
		self.previewBoxes[self.ind].setVisible(livemode)
		self.editBoxes[self.ind].setVisible(True)
		if livemode:
			self.updatePreviewBox()

	def enableWebKit(self, enable):
		globalSettings.useWebKit = enable
		oldind = self.ind
		self.tabWidget.clear()
		for self.ind in range(len(self.editBoxes)):
			if enable:
				self.previewBoxes[self.ind] = self.getWebView()
			else:
				self.previewBoxes[self.ind] = QTextBrowser()
				self.previewBoxes[self.ind].setOpenExternalLinks(True)
			splitter = self.getSplitter(self.ind)
			self.tabWidget.addTab(splitter, self.getDocumentTitle(baseName=True))
			self.updatePreviewBox()
			self.previewBoxes[self.ind].setVisible(self.actionPreviewChecked[self.ind])
		self.ind = oldind
		self.tabWidget.setCurrentIndex(self.ind)

	def enableCopy(self, copymode):
		self.actionCopy.setEnabled(copymode)
		self.actionCut.setEnabled(copymode)

	def enableFullScreen(self, yes):
		if yes:
			self.showFullScreen()
		else:
			self.showNormal()

	def openConfigDialog(self):
		dlg = ConfigDialog(self)
		dlg.setWindowTitle(self.tr('Preferences'))
		dlg.show()

	def installFakeVimHandler(self, editor):
		if ReTextFakeVimHandler:
			fakeVimEditor = ReTextFakeVimHandler(editor, self)
			fakeVimEditor.setSaveAction(self.actionSave)
			fakeVimEditor.setQuitAction(self.actionQuit)
			self.actionFakeVimMode.triggered.connect(fakeVimEditor.remove)

	def enableFakeVimMode(self, yes):
		globalSettings.useFakeVim = yes
		if yes:
			FakeVimMode.init(self)
			for editor in self.editBoxes:
				self.installFakeVimHandler(editor)
		else:
			FakeVimMode.exit(self)

	def enableSpellCheck(self, yes):
		if yes:
			if self.sl:
				self.setAllDictionaries(enchant.Dict(self.sl))
			else:
				self.setAllDictionaries(enchant.Dict())
		else:
			self.setAllDictionaries(None)
		globalSettings.spellCheck = yes

	def setAllDictionaries(self, dictionary):
		for hl in self.highlighters:
			hl.dictionary = dictionary
			hl.rehighlight()

	def changeLocale(self):
		if self.sl:
			localedlg = LocaleDialog(self, defaultText=self.sl)
		else:
			localedlg = LocaleDialog(self)
		if localedlg.exec() != QDialog.Accepted:
			return
		sl = localedlg.localeEdit.text()
		setdefault = localedlg.checkBox.isChecked()
		if sl:
			try:
				sl = str(sl)
				enchant.Dict(sl)
			except Exception as e:
				QMessageBox.warning(self, '', str(e))
			else:
				self.sl = sl
				self.enableSpellCheck(self.actionEnableSC.isChecked())
		else:
			self.sl = None
			self.enableSpellCheck(self.actionEnableSC.isChecked())
		if setdefault:
			globalSettings.spellCheckLocale = sl

	def searchBarVisibilityChanged(self, visible):
		self.actionSearch.setChecked(visible)
		if visible:
			self.searchEdit.setFocus(Qt.ShortcutFocusReason)

	def find(self, back=False):
		flags = QTextDocument.FindFlags()
		if back:
			flags |= QTextDocument.FindBackward
		if self.csBox.isChecked():
			flags |= QTextDocument.FindCaseSensitively
		text = self.searchEdit.text()
		editBox = self.editBoxes[self.ind]
		cursor = editBox.textCursor()
		newCursor = editBox.document().find(text, cursor, flags)
		if not newCursor.isNull():
			editBox.setTextCursor(newCursor)
			return self.setSearchEditColor(True)
		cursor.movePosition(QTextCursor.End if back else QTextCursor.Start)
		newCursor = editBox.document().find(text, cursor, flags)
		if not newCursor.isNull():
			editBox.setTextCursor(newCursor)
			return self.setSearchEditColor(True)
		self.setSearchEditColor(False)

	def setSearchEditColor(self, found):
		palette = self.searchEdit.palette()
		palette.setColor(QPalette.Active, QPalette.Base,
		                 Qt.white if found else QColor(255, 102, 102))
		self.searchEdit.setPalette(palette)

	def getHtml(self, includeStyleSheet=True, includeTitle=True,
	            includeMeta=False, styleForWebKit=False, webenv=False):
		if self.markups[self.ind] is None:
			markupClass = self.getMarkupClass()
			errMsg = self.tr('Could not parse file contents, check if '
			'you have the <a href="%s">necessary module</a> installed!')
			try:
				errMsg %= markupClass.attributes[MODULE_HOME_PAGE]
			except (AttributeError, KeyError):
				# Remove the link if markupClass doesn't have the needed attribute
				errMsg = errMsg.replace('<a href="%s">', '')
				errMsg = errMsg.replace('</a>', '')
			return '<p style="color: red">%s</p>' % errMsg
		text = self.editBoxes[self.ind].toPlainText()
		headers = ''
		if includeStyleSheet:
			fontline = ''
			if styleForWebKit:
				fontname = self.font.family() if self.font else 'Sans'
				fontsize = (self.font if self.font else QFont()).pointSize()
				fontline = 'body { font-family: %s; font-size: %spt }\n' % \
					(fontname, fontsize)
			headers += '<style type="text/css">\n' + fontline + self.ss + '</style>\n'
		cssFileName = self.getDocumentTitle(baseName=True)+'.css'
		if QFile(cssFileName).exists():
			headers += '<link rel="stylesheet" type="text/css" href="%s">\n' \
			% cssFileName
		if includeMeta:
			headers += '<meta name="generator" content="%s %s">\n' % \
			(app_name, app_version)
		fallbackTitle = self.getDocumentTitle() if includeTitle else ''
		return self.markups[self.ind].get_whole_html(text,
			custom_headers=headers, include_stylesheet=includeStyleSheet,
			fallback_title=fallbackTitle, webenv=webenv)

	def updatePreviewBox(self):
		self.previewBlocked = False
		pb = self.previewBoxes[self.ind]
		textedit = isinstance(pb, QTextEdit)
		if textedit:
			scrollbar = pb.verticalScrollBar()
			disttobottom = scrollbar.maximum() - scrollbar.value()
		else:
			frame = pb.page().mainFrame()
			scrollpos = frame.scrollPosition()
		try:
			html = self.getHtml(styleForWebKit=(not textedit))
		except Exception:
			return self.printError()
		if textedit:
			pb.setHtml(html)
		else:
			pb.setHtml(html, QUrl.fromLocalFile(self.fileNames[self.ind]))
		if self.font and textedit:
			pb.document().setDefaultFont(self.font)
		if textedit:
			scrollbar.setValue(scrollbar.maximum() - disttobottom)
		else:
			frame.setScrollPosition(scrollpos)

	def updateLivePreviewBox(self):
		if self.actionLivePreview.isChecked() and self.previewBlocked == False:
			self.previewBlocked = True
			QTimer.singleShot(1000, self.updatePreviewBox)

	def showInDir(self):
		if self.fileNames[self.ind]:
			path = QFileInfo(self.fileNames[self.ind]).path()
			QDesktopServices.openUrl(QUrl.fromLocalFile(path))
		else:
			QMessageBox.warning(self, '', self.tr("Please, save the file somewhere."))

	def setCurrentFile(self):
		self.setWindowTitle("")
		self.tabWidget.setTabText(self.ind, self.getDocumentTitle(baseName=True))
		self.setWindowFilePath(self.fileNames[self.ind])
		files = readListFromSettings("recentFileList")
		while self.fileNames[self.ind] in files:
			files.remove(self.fileNames[self.ind])
		files.insert(0, self.fileNames[self.ind])
		if len(files) > 10:
			del files[10:]
		writeListToSettings("recentFileList", files)
		QDir.setCurrent(QFileInfo(self.fileNames[self.ind]).dir().path())
		self.docTypeChanged()

	def createNew(self, text=None):
		self.tabWidget.addTab(self.createTab(""), self.tr("New document"))
		self.ind = self.tabWidget.count()-1
		self.tabWidget.setCurrentIndex(self.ind)
		if text:
			self.editBoxes[self.ind].textCursor().insertText(text)

	def switchTab(self, shift=1):
		self.tabWidget.setCurrentIndex((self.ind + shift) % self.tabWidget.count())

	def updateRecentFiles(self):
		self.menuRecentFiles.clear()
		self.recentFilesActions = []
		filesOld = readListFromSettings("recentFileList")
		files = []
		for f in filesOld:
			if QFile.exists(f):
				files.append(f)
				self.recentFilesActions.append(self.act(f, trig=self.openFunction(f)))
		writeListToSettings("recentFileList", files)
		for action in self.recentFilesActions:
			self.menuRecentFiles.addAction(action)

	def markupFunction(self, markup):
		return lambda: self.setDefaultMarkup(markup)

	def openFunction(self, fileName):
		return lambda: self.openFileWrapper(fileName)

	def extensionFuntion(self, data):
		return lambda: \
		self.runExtensionCommand(data['Exec'], data['FileFilter'], data['DefaultExtension'])

	def getExportExtensionsList(self):
		extensions = []
		for extsprefix in datadirs:
			extsdir = QDir(extsprefix+'/export-extensions/')
			if extsdir.exists():
				for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'],
				QDir.Files | QDir.Readable):
					extensions.append(self.readExtension(fileInfo.filePath()))
		locale = QLocale.system().name()
		self.extensionActions = []
		for extension in extensions:
			try:
				if ('Name[%s]' % locale) in extension:
					name = extension['Name[%s]' % locale]
				elif ('Name[%s]' % locale.split('_')[0]) in extension:
					name = extension['Name[%s]' % locale.split('_')[0]]
				else:
					name = extension['Name']
				data = {}
				for prop in ('FileFilter', 'DefaultExtension', 'Exec'):
					if 'X-ReText-'+prop in extension:
						data[prop] = extension['X-ReText-'+prop]
					elif prop in extension:
						data[prop] = extension[prop]
					else:
						data[prop] = ''
				action = self.act(name, trig=self.extensionFuntion(data))
				if 'Icon' in extension:
					action.setIcon(self.actIcon(extension['Icon']))
				mimetype = extension['MimeType'] if 'MimeType' in extension else None
			except KeyError:
				print('Failed to parse extension: Name is required', file=sys.stderr)
			else:
				self.extensionActions.append((action, mimetype))

	def updateExtensionsVisibility(self):
		markupClass = self.getMarkupClass()
		for action in self.extensionActions:
			if markupClass is None:
				action[0].setEnabled(False)
				continue
			mimetype = action[1]
			if mimetype == None:
				enabled = True
			elif markupClass == markups.MarkdownMarkup:
				enabled = (mimetype in ("text/x-retext-markdown", "text/x-markdown"))
			elif markupClass == markups.ReStructuredTextMarkup:
				enabled = (mimetype in ("text/x-retext-rst", "text/x-rst"))
			else:
				enabled = False
			action[0].setEnabled(enabled)

	def readExtension(self, fileName):
		extFile = QFile(fileName)
		extFile.open(QIODevice.ReadOnly)
		extension = {}
		stream = QTextStream(extFile)
		while not stream.atEnd():
			line = stream.readLine()
			if '=' in line:
				index = line.index('=')
				extension[line[:index].rstrip()] = line[index+1:].lstrip()
		extFile.close()
		return extension

	def openFile(self):
		supportedExtensions = ['.txt']
		for markup in markups.get_all_markups():
			supportedExtensions += markup.file_extensions
		fileFilter = ' (' + str.join(' ', ['*'+ext for ext in supportedExtensions]) + ');;'
		fileNames = QFileDialog.getOpenFileNames(self,
			self.tr("Select one or several files to open"), "",
			self.tr("Supported files") + fileFilter + self.tr("All files (*)"))
		for fileName in fileNames[0]:
			self.openFileWrapper(fileName)

	def openFileWrapper(self, fileName):
		if not fileName:
			return
		fileName = QFileInfo(fileName).canonicalFilePath()
		exists = False
		for i in range(self.tabWidget.count()):
			if self.fileNames[i] == fileName:
				exists = True
				ex = i
		if exists:
			self.tabWidget.setCurrentIndex(ex)
		elif QFile.exists(fileName):
			noEmptyTab = (
				(self.ind is None) or
				self.fileNames[self.ind] or
				self.editBoxes[self.ind].toPlainText() or
				self.editBoxes[self.ind].document().isModified()
			)
			if noEmptyTab:
				self.tabWidget.addTab(self.createTab(fileName), "")
				self.ind = self.tabWidget.count()-1
				self.tabWidget.setCurrentIndex(self.ind)
			if fileName:
				self.fileSystemWatcher.addPath(fileName)
			self.fileNames[self.ind] = fileName
			self.openFileMain()

	def openFileMain(self, encoding=None):
		openfile = QFile(self.fileNames[self.ind])
		openfile.open(QIODevice.ReadOnly)
		stream = QTextStream(openfile)
		if encoding:
			stream.setCodec(encoding)
		elif globalSettings.defaultCodec:
			stream.setCodec(globalSettings.defaultCodec)
		text = stream.readAll()
		openfile.close()
		markupClass = markups.get_markup_for_file_name(
			self.fileNames[self.ind], return_class=True)
		self.highlighters[self.ind].docType = (markupClass.name if markupClass else '')
		self.markups[self.ind] = self.getMarkup()
		if self.defaultMarkup:
			self.highlighters[self.ind].docType = self.defaultMarkup.name
		editBox = self.editBoxes[self.ind]
		modified = bool(encoding) and (editBox.toPlainText() != text)
		editBox.setPlainText(text)
		self.setCurrentFile()
		editBox.document().setModified(modified)
		self.setWindowModified(modified)

	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in QTextCodec.availableCodecs()],
			0, False)
		if ok:
			self.openFileMain(encoding)

	def saveFile(self):
		self.saveFileMain(dlg=False)

	def saveFileAs(self):
		self.saveFileMain(dlg=True)

	def saveAll(self):
		oldind = self.ind
		for self.ind in range(self.tabWidget.count()):
			if self.fileNames[self.ind] and QFileInfo(self.fileNames[self.ind]).isWritable():
				self.saveFileCore(self.fileNames[self.ind])
				self.editBoxes[self.ind].document().setModified(False)
		self.ind = oldind

	def saveFileMain(self, dlg):
		if (not self.fileNames[self.ind]) or dlg:
			markupClass = self.getMarkupClass()
			if (markupClass is None) or not hasattr(markupClass, 'default_extension'):
				defaultExt = self.tr("Plain text (*.txt)")
				ext = ".txt"
			else:
				defaultExt = self.tr('%s files',
					'Example of final string: Markdown files') \
					% markupClass.name + ' (' + str.join(' ',
					('*'+extension for extension in markupClass.file_extensions)) + ')'
				if markupClass == markups.MarkdownMarkup:
					ext = globalSettings.markdownDefaultFileExtension
				elif markupClass == markups.ReStructuredTextMarkup:
					ext = globalSettings.restDefaultFileExtension
				else:
					ext = markupClass.default_extension
			newFileName = QFileDialog.getSaveFileName(self,
				self.tr("Save file"), "", defaultExt)[0]
			if newFileName:
				if not QFileInfo(newFileName).suffix():
					newFileName += ext
				if self.fileNames[self.ind]:
					self.fileSystemWatcher.removePath(self.fileNames[self.ind])
				self.fileNames[self.ind] = newFileName
				self.actionSetEncoding.setDisabled(self.autoSaveActive())
		if self.fileNames[self.ind]:
			result = self.saveFileCore(self.fileNames[self.ind])
			if result:
				self.setCurrentFile()
				self.editBoxes[self.ind].document().setModified(False)
				self.setWindowModified(False)
				return True
			else:
				QMessageBox.warning(self, '',
				self.tr("Cannot save to file because it is read-only!"))
		return False

	def saveFileCore(self, fn):
		self.fileSystemWatcher.removePath(fn)
		savefile = QFile(fn)
		result = savefile.open(QIODevice.WriteOnly)
		if result:
			savestream = QTextStream(savefile)
			if globalSettings.defaultCodec:
				savestream.setCodec(globalSettings.defaultCodec)
			savestream << self.editBoxes[self.ind].toPlainText()
			savefile.close()
		self.fileSystemWatcher.addPath(fn)
		return result

	def saveHtml(self, fileName):
		if not QFileInfo(fileName).suffix():
			fileName += ".html"
		try:
			htmltext = self.getHtml(includeStyleSheet=False, includeMeta=True,
			webenv=True)
		except Exception:
			return self.printError()
		htmlFile = QFile(fileName)
		htmlFile.open(QIODevice.WriteOnly)
		html = QTextStream(htmlFile)
		if globalSettings.defaultCodec:
			html.setCodec(globalSettings.defaultCodec)
		html << htmltext
		htmlFile.close()

	def textDocument(self):
		td = QTextDocument()
		td.setMetaInformation(QTextDocument.DocumentTitle, self.getDocumentTitle())
		if self.ss:
			td.setDefaultStyleSheet(self.ss)
		td.setHtml(self.getHtml())
		if self.font:
			td.setDefaultFont(self.font)
		return td

	def saveOdf(self):
		try:
			document = self.textDocument()
		except Exception:
			return self.printError()
		fileName = QFileDialog.getSaveFileName(self,
			self.tr("Export document to ODT"), "",
			self.tr("OpenDocument text files (*.odt)"))[0]
		if not QFileInfo(fileName).suffix():
			fileName += ".odt"
		writer = QTextDocumentWriter(fileName)
		writer.setFormat("odf")
		writer.write(document)

	def saveFileHtml(self):
		fileName = QFileDialog.getSaveFileName(self,
			self.tr("Save file"), "",
			self.tr("HTML files (*.html *.htm)"))[0]
		if fileName:
			self.saveHtml(fileName)

	def getDocumentForPrint(self):
		if globalSettings.useWebKit:
			return self.previewBoxes[self.ind]
		try:
			return self.textDocument()
		except Exception:
			self.printError()

	def standardPrinter(self):
		printer = QPrinter(QPrinter.HighResolution)
		printer.setDocName(self.getDocumentTitle())
		printer.setCreator(app_name+" "+app_version)
		return printer

	def savePdf(self):
		self.updatePreviewBox()
		fileName = QFileDialog.getSaveFileName(self,
			self.tr("Export document to PDF"),
			"", self.tr("PDF files (*.pdf)"))[0]
		if fileName:
			if not QFileInfo(fileName).suffix():
				fileName += ".pdf"
			printer = self.standardPrinter()
			printer.setOutputFormat(QPrinter.PdfFormat)
			printer.setOutputFileName(fileName)
			document = self.getDocumentForPrint()
			if document != None:
				document.print(printer)

	def printFile(self):
		self.updatePreviewBox()
		printer = self.standardPrinter()
		dlg = QPrintDialog(printer, self)
		dlg.setWindowTitle(self.tr("Print document"))
		if (dlg.exec() == QDialog.Accepted):
			document = self.getDocumentForPrint()
			if document != None:
				document.print(printer)

	def printPreview(self):
		document = self.getDocumentForPrint()
		if document == None:
			return
		printer = self.standardPrinter()
		preview = QPrintPreviewDialog(printer, self)
		preview.paintRequested.connect(document.print)
		preview.exec()

	def runExtensionCommand(self, command, filefilter, defaultext):
		of = ('%of' in command)
		html = ('%html' in command)
		if of:
			if defaultext and not filefilter:
				filefilter = '*'+defaultext
			fileName = QFileDialog.getSaveFileName(self,
				self.tr('Export document'), '', filefilter)[0]
			if not fileName:
				return
			if defaultext and not QFileInfo(fileName).suffix():
				fileName += defaultext
		basename = '.%s.retext-temp' % self.getDocumentTitle(baseName=True)
		if html:
			tmpname = basename+'.html'
			self.saveHtml(tmpname)
		else:
			tmpname = basename+self.getMarkupClass().default_extension
			self.saveFileCore(tmpname)
		command = command.replace('%of', '"out'+defaultext+'"')
		command = command.replace('%html' if html else '%if', '"'+tmpname+'"')
		try:
			Popen(str(command), shell=True).wait()
		except Exception as error:
			errorstr = str(error)
			QMessageBox.warning(self, '', self.tr('Failed to execute the command:')
			+ '\n' + errorstr)
		QFile(tmpname).remove()
		if of:
			QFile('out'+defaultext).rename(fileName)

	def getDocumentTitle(self, baseName=False):
		markup = self.markups[self.ind]
		realTitle = ''
		if markup and not baseName:
			text = self.editBoxes[self.ind].toPlainText()
			try:
				realTitle = markup.get_document_title(text)
			except Exception:
				self.printError()
		if realTitle:
			return realTitle
		elif self.fileNames[self.ind]:
			fileinfo = QFileInfo(self.fileNames[self.ind])
			basename = fileinfo.completeBaseName()
			return (basename if basename else fileinfo.fileName())
		return self.tr("New document")

	def autoSaveActive(self):
		return self.autoSaveEnabled and self.fileNames[self.ind] and \
		QFileInfo(self.fileNames[self.ind]).isWritable()

	def modificationChanged(self, changed):
		if self.autoSaveActive():
			changed = False
		self.actionSave.setEnabled(changed)
		self.setWindowModified(changed)

	def clipboardDataChanged(self):
		mimeData = QApplication.instance().clipboard().mimeData()
		if mimeData is not None:
			self.actionPaste.setEnabled(mimeData.hasText())

	def insertChars(self, chars):
		tc = self.editBoxes[self.ind].textCursor()
		if tc.hasSelection():
			selection = tc.selectedText()
			if selection.startswith(chars) and selection.endswith(chars):
				if len(selection) > 2*len(chars):
					selection = selection[len(chars):-len(chars)]
					tc.insertText(selection)
			else:
				tc.insertText(chars+tc.selectedText()+chars)
		else:
			tc.insertText(chars)

	def insertTag(self, ut):
		if not ut:
			return
		if isinstance(ut, int):
			ut = self.usefulTags[ut - 1]
		arg = ' style=""' if ut == 'span' else ''
		tc = self.editBoxes[self.ind].textCursor()
		if ut == 'img':
			toinsert = ('<a href="' + tc.selectedText() +
			'" target="_blank"><img src="' + tc.selectedText() + '"/></a>')
		elif ut == 'a':
			toinsert = ('<a href="' + tc.selectedText() +
			'" target="_blank">' + tc.selectedText() + '</a>')
		else:
			toinsert = '<'+ut+arg+'>'+tc.selectedText()+'</'+ut+'>'
		tc.insertText(toinsert)
		self.tagsBox.setCurrentIndex(0)

	def insertSymbol(self, num):
		if num:
			self.editBoxes[self.ind].insertPlainText('&'+self.usefulChars[num-1]+';')
		self.symbolBox.setCurrentIndex(0)

	def fileChanged(self, fileName):
		ind = self.fileNames.index(fileName)
		self.tabWidget.setCurrentIndex(ind)
		if not QFile.exists(fileName):
			self.editBoxes[ind].document().setModified(True)
			QMessageBox.warning(self, '', self.tr(
				'This file has been deleted by other application.\n'
				'Please make sure you save the file before exit.'))
		elif not self.editBoxes[ind].document().isModified():
			# File was not modified in ReText, reload silently
			self.openFileMain()
			self.updatePreviewBox()
		else:
			text = self.tr(
				'This document has been modified by other application.\n'
				'Do you want to reload the file (this will discard all '
				'your changes)?\n')
			if self.autoSaveEnabled:
				text += self.tr(
					'If you choose to not reload the file, auto save mode will '
					'be disabled for this session to prevent data loss.')
			messageBox = QMessageBox(QMessageBox.Warning, '', text)
			reloadButton = messageBox.addButton(self.tr('Reload'), QMessageBox.YesRole)
			messageBox.addButton(QMessageBox.Cancel)
			messageBox.exec()
			if messageBox.clickedButton() is reloadButton:
				self.openFileMain()
				self.updatePreviewBox()
			else:
				self.autoSaveEnabled = False
				self.editBoxes[ind].document().setModified(True)
		if fileName not in self.fileSystemWatcher.files():
			# https://sourceforge.net/p/retext/tickets/137/
			self.fileSystemWatcher.addPath(fileName)

	def maybeSave(self, ind):
		if self.autoSaveActive():
			self.saveFileCore(self.fileNames[self.ind])
			return True
		if not self.editBoxes[ind].document().isModified():
			return True
		self.tabWidget.setCurrentIndex(ind)
		ret = QMessageBox.warning(self, '',
			self.tr("The document has been modified.\nDo you want to save your changes?"),
			QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
		if ret == QMessageBox.Save:
			return self.saveFileMain(False)
		elif ret == QMessageBox.Cancel:
			return False
		return True

	def closeEvent(self, closeevent):
		for self.ind in range(self.tabWidget.count()):
			if not self.maybeSave(self.ind):
				return closeevent.ignore()
		if globalSettings.saveWindowGeometry and not self.isMaximized():
			globalSettings.windowGeometry = self.saveGeometry()
		closeevent.accept()

	def viewHtml(self):
		htmlDlg = HtmlDialog(self)
		try:
			htmltext = self.getHtml(includeStyleSheet=False, includeTitle=False)
		except Exception:
			return self.printError()
		winTitle = self.getDocumentTitle(baseName=True)
		htmlDlg.setWindowTitle(winTitle+" ("+self.tr("HTML code")+")")
		htmlDlg.textEdit.setPlainText(htmltext.rstrip())
		htmlDlg.hl.rehighlight()
		htmlDlg.show()
		htmlDlg.raise_()
		htmlDlg.activateWindow()

	def openHelp(self):
		QDesktopServices.openUrl(QUrl('http://sourceforge.net/p/retext/home/Help and Support'))

	def aboutDialog(self):
		QMessageBox.about(self, self.aboutWindowTitle,
		'<p><b>' + (self.tr('ReText %s (using PyMarkups %s)') % (app_version, markups.__version__))
		+'</b></p>' + self.tr('Simple but powerful editor'
		' for Markdown and reStructuredText')
		+'</p><p>'+self.tr('Author: Dmitry Shachnev, 2011').replace('2011', '2011\u2013' '2015')
		+'<br><a href="http://sourceforge.net/p/retext/">'+self.tr('Website')
		+'</a> | <a href="http://daringfireball.net/projects/markdown/syntax">'
		+self.tr('Markdown syntax')
		+'</a> | <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">'
		+self.tr('reStructuredText syntax')+'</a></p>')

	def setDefaultMarkup(self, markup):
		self.defaultMarkup = markup
		defaultName = markups.get_available_markups()[0].name
		writeToSettings('defaultMarkup', markup.name, defaultName)
		oldind = self.ind
		for self.ind in range(len(self.previewBoxes)):
			self.docTypeChanged()
		self.ind = oldind
Beispiel #60
0
class Tetris(QWidget):

    screenWidth = None          # 窗口宽度
    screenHeight = None         # 窗口高度
    isGameStart = None          # 游戏是否开始
    isGameOver = None           # 游戏是否结束
    isPause = None              # 游戏是否暂停
    pauseButton = None          # 暂停游戏按钮
    resumeButton = None         # 继续游戏按钮
    restartButton = None        # 重新开始游戏按钮
    gameOverImage = None        # 游戏结束时显示的图片
    blockSize = None            # 一个方块的大小(像素px)
    allRows = None              # 所有的行
    allColumns = None           # 所有的列
    allBlock = None             # 二维数组, 记录方块
    currentRow = None           # 当前行
    currentColumn = None        # 当前列
    dropTimer = None            # 方块下降的定时器
    updateTimer = None          # 屏幕更新的定时器
    removeBlockTimer = None     # 消除方块的定时器
    dropInterval = None         # 方块下降定时器的时间间隔
    updateInterval = None       # 屏幕更新定时器的时间间隔
    removeBlockInterval = None  # 消除方块定时器的时间间隔
    blocks = None               # 枚举所有的方块
    blockDict = None            # 存储方块属性的字典
    nextBlockDict = None        # 存储下一个方块属性的字典
    block = None                # 当前的方块
    shape = None                # 当前方块的类型
    index = None                # 当前方块类型的下标
    score = None                # 得分情况
    pixmap = None               # 临时存储图片路径
    paint = None                # 画笔
    font = None                 # 字体

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

        self.screenWidth = 900
        self.screenHeight = 800
        self.setFocusPolicy(Qt.StrongFocus)         # 设置焦点, 监听键盘
        self.resize(self.screenWidth, self.screenHeight)

        self.initButton()
        self.initImage()

    def initButton(self):
        """初始化重新开始游戏的按钮"""
        # 暂停游戏按钮
        self.pauseButton = QPushButton(self)
        self.pauseButton.setObjectName('pauseButton')
        self.pauseButton.setShortcut('P')
        self.pauseButton.setToolTip('暂停')  # 悬停在按钮上的提示->暂停
        self.pauseButton.move(self.screenWidth - 210, 5)  # 按钮的位置
        self.pauseButton.hide()  # 默认隐藏
        self.pauseButton.clicked.connect(lambda: {
            self.pause(),
            self.pauseButton.hide(),
            self.resumeButton.show(),
        })

        # 继续游戏按钮
        self.resumeButton = QPushButton(self)
        self.resumeButton.setObjectName('resumeButton')
        self.resumeButton.setToolTip('继续')  # 悬停在按钮上的提示->继续
        self.resumeButton.move(self.screenWidth - 210, 5)  # 按钮的位置
        self.resumeButton.hide()  # 默认隐藏
        self.resumeButton.clicked.connect(lambda: {
            self.resume(),
            self.resumeButton.hide(),
            self.pauseButton.show(),
        })

        # 重新开始游戏按钮
        self.restartButton = QPushButton(self)
        self.restartButton.setObjectName('restartButton')
        self.restartButton.move(self.screenWidth // 2 - 200, self.screenHeight // 2 - 50)
        self.restartButton.hide()       # 默认隐藏
        self.restartButton.clicked.connect(self.gameOver)

    def initImage(self):
        """初始化游戏结束的图片"""
        self.gameOverImage = QLabel(self)
        self.gameOverImage.setPixmap(QPixmap('./icons/game_over.png'))
        self.gameOverImage.move(self.screenWidth // 24, self.screenHeight // 4)
        self.gameOverImage.hide()   # 默认隐藏

    def initSetting(self):
        """初始化方块的一些初始值"""
        self.blocks = {
            'L Shape': [[[0, 0], [0, -1], [0, -2], [1, -2]], [[-1, -1], [0, -1], [1, -1], [-1, -2]],
                        [[-1, 0], [0, 0], [0, -1], [0, -2]], [[-1, -1], [0, -1], [1, -1], [1, 0]]],
            'J Shape': [[[0, 0], [0, -1], [0, -2], [-1, -2]], [[-1, 0], [-1, -1], [0, -1], [1, -1]],
                        [[0, 0], [1, 0], [0, -1], [0, -2]], [[-1, -1], [0, -1], [1, -1], [1, -2]]],
            'Z Shape': [[[-1, 0], [0, 0], [0, -1], [1, -1]], [[0, 0], [0, -1], [-1, -1], [-1, -2]],
                        [[-1, 0], [0, 0], [0, -1], [1, -1]], [[0, 0], [0, -1], [-1, -1], [-1, -2]]],
            'S Shape': [[[-1, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [1, 0], [-1, -1], [0, -1]],
                        [[-1, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [1, 0], [-1, -1], [0, -1]]],
            'O Shape': [[[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]],
                        [[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]]],
            'I Shape': [[[0, 0], [0, -1], [0, -2], [0, -3]], [[-2, -1], [-1, -1], [0, -1], [1, -1]],
                        [[0, 0], [0, -1], [0, -2], [0, -3]], [[-2, -1], [-1, -1], [0, -1], [1, -1]]],
            'T Shape': [[[-1, -1], [0, -1], [1, -1], [0, -2]], [[0, 0], [-1, -1], [0, -1], [0, -2]],
                        [[0, 0], [-1, -1], [0, -1], [1, -1]], [[0, 0], [0, -1], [1, -1], [0, -2]]]
        }
        self.score = 0
        self.blockSize = 40     # 方块的大小
        self.allRows = 20       # 总共20行
        self.allColumns = 15    # 总共15列
        self.currentRow = self.allRows + 4   # +4行是用来放置待出现的方块的
        self.currentColumn = self.allColumns // 2
        self.allBlock = [[0 for row in range(self.allColumns)] for column in range(self.allRows + 5)]
        self.allBlock[0] = [1 for column in range(self.allColumns)]    # 用来判断方块是否到底
        # print(self.allBlock)

    def initFont(self):
        """初始化字体"""
        # 使用本地字体
        fontID = QFontDatabase.addApplicationFont('./Font/Consolas Italic.ttf')
        self.font = QFont()
        self.font.setFamily(QFontDatabase.applicationFontFamilies(fontID)[0])
        self.font.setItalic(True)   # 斜体
        self.font.setBold(True)     # 粗体
        self.font.setPixelSize(40)  # 字体大小

    def initTimer(self):
        """初始化定时器"""
        # 方块下降的定时器
        self.dropTimer = QTimer(self)
        self.dropInterval = 500     # 每0.5秒下降一格
        self.dropTimer.start(self.dropInterval)
        self.dropTimer.timeout.connect(self.blockDrop)

        # paintEvent更新的定时器
        self.updateTimer = QTimer(self)
        self.updateInterval = 10
        self.updateTimer.start(self.updateInterval)
        self.updateTimer.timeout.connect(self.update)

        # 消除方块的定时器
        self.removeBlockTimer = QTimer(self)
        self.removeBlockInterval = 150
        self.removeBlockTimer.start(self.removeBlockInterval)
        self.removeBlockTimer.timeout.connect(self.removeBlock)

    def getBlock(self):
        """获取方块"""
        shape = random.choice(list(self.blocks.keys()))     # 选择随机方块的类型
        index = random.randint(0, 3)
        # if shape == 'L Shape' and index == 3:
        #     pass
        block = self.blocks[shape][index]
        blockDict = {
            'shape': shape,
            'index': index,
            'block': block,
        }
        return blockDict

    def getCurrentBlock(self):
        """获取目前的方块"""
        self.blockDict = self.nextBlockDict
        self.shape = self.blockDict['shape']
        self.index = self.blockDict['index']
        self.block = self.blockDict['block']
        self.nextBlockDict = self.getBlock()

    def blockDrop(self):
        """每运行一次, 方块下降一格, 通过QTimer每隔一定时间运行一次"""
        for position1 in self.block:
            x = position1[0] + self.currentColumn    # x->column
            y = position1[1] + self.currentRow       # y->row
            # print(x, y)
            if self.allBlock[y - 1][x] == 1:
                for position2 in self.block:
                    self.allBlock[position2[1] + self.currentRow][position2[0] + self.currentColumn] = 1
                break
        else:
            # 下落方块没有接触到其他方块或者没有到底, 继续下降
            self.currentRow -= 1
            return

        # 判断游戏结束
        if 1 in self.allBlock[self.allRows]:
            self.pause()
            self.update()
            self.removeBlockTimer.disconnect()
            self.updateTimer.disconnect()
            self.pauseButton.hide()
            self.gameOverImage.show()
            self.restartButton.show()
            return

        # 方块下落完成, 获取下一个方块
        self.getCurrentBlock()
        self.currentRow = self.allRows + 4
        self.currentColumn = self.allColumns // 2

    def removeBlock(self):
        """消除方块"""
        # 叠满一行时消除方块, 从上往下消除
        for row in range(self.allRows, 0, -1):
            if 0 not in self.allBlock[row]:
                # 消除方块时触发音效, 消除一行触发一次
                player = QMediaPlayer(self)
                player.setMedia(QMediaContent(QUrl.fromLocalFile('./AudioFrequency/dingdong.mp3')))
                player.play()

                self.allBlock.pop(row)  # 即删即增
                self.allBlock.append([0 for column in range(self.allColumns)])
                self.score += 1

                break

    def blockMove(self, movePosition):
        """左右移动方块movePosition>0 代表向右移动一格 <0 代表向左移动一格"""
        for position in self.block:
            x = position[0] + self.currentColumn + movePosition
            y = position[1] + self.currentRow
            if x < 0 or x > self.allColumns - 1 or y > self.allRows:
                # 说明方块左右移动出边界了
                return
            elif self.allBlock[y][x] == 1:
                # 说明方块左右移动碰到方块了
                return
        else:
            self.currentColumn += movePosition

    def rotate(self):
        """顺时针旋转方块"""
        for position in self.blocks[self.shape][(self.index + 1) % 4]:
            x = position[0] + self.currentColumn
            y = position[1] + self.currentRow
            # print(x, y)
            if x < 0 or x > self.allColumns - 1 or y > self.allRows:
                # 说明方块旋转时候出边界了
                return
            elif self.allBlock[y][x] == 1:
                # 说明方块旋转时候碰到方块了
                return
        else:
            self.index += 1
            # print(self.blocks[self.shape][self.index % 4])
            self.block = self.blocks[self.shape][self.index % 4]

    def start(self):
        """开始游戏"""
        self.isGameStart = True
        self.isGameOver = False
        self.isPause = False
        self.pauseButton.show()
        self.initSetting()
        self.initFont()
        self.initTimer()
        self.nextBlockDict = self.getBlock()
        self.getCurrentBlock()

    def pause(self):
        """游戏暂停"""
        self.isPause = True
        self.dropTimer.disconnect()

    def resume(self):
        """游戏继续"""
        self.isPause = False
        self.dropTimer.start(self.dropInterval)
        self.dropTimer.timeout.connect(self.blockDrop)

    def gameOver(self):
        """游戏结束"""
        self.isGameOver = True

    def paintEvent(self, event):
        """重写paintEvent, 使用QTimer, 每10ms调用一次"""
        self.paint = QPainter(self)
        self.paint.begin(self)  # 开始重绘

        if self.isGameStart is True:
            penColor = QColor(255, 255, 255)  # 白色
            # backgroundColor = QColor(255, 192, 203)  # 粉色
            self.paint.setPen(QPen(penColor, 2, Qt.SolidLine, Qt.RoundCap))     # 白色,
            self.pixmap = QPixmap('./icons/game_background.png')
            self.paint.drawPixmap(QRect(0, 0, self.screenWidth, self.screenHeight), self.pixmap)    # 背景图片
            self.paint.drawLine(self.screenWidth - 300, 0, self.screenWidth - 300, self.screenHeight)   # 分割线

            # 绘制正在下落的方块
            for position in self.block:
                x = position[0] + self.currentColumn
                y = position[1] + self.currentRow
                self.paint.drawPixmap(QRect(x * self.blockSize, (self.allRows - y) * self.blockSize,
                                            self.blockSize, self.blockSize), QPixmap('./icons/block.png'))

            # 绘制静态方块
            for row in range(1, self.allRows + 1):
                for column in range(self.allColumns):
                    if self.allBlock[row][column] == 1:
                        self.paint.drawPixmap(QRect(column * self.blockSize, (self.allRows - row) * self.blockSize,
                                                    self.blockSize, self.blockSize), QPixmap('./icons/fill_block.png'))

            # 绘制下一个出现的方块
            for position in self.nextBlockDict['block']:
                x = position[0] + 18.5  # 18.5是740px/40px(方块大小)
                y = position[1] + 12.5   # 7.5是500px/40px(方块大小) 从下往上
                self.paint.drawPixmap(QRect(int(x * self.blockSize), int((self.allRows - y) * self.blockSize),
                                            self.blockSize, self.blockSize), QPixmap('./icons/block.png'))

            # 绘制得分情况
            self.paint.setFont(self.font)
            self.paint.drawText(self.screenWidth - 250, 150, 'Score: %d' % self.score)

        self.paint.end()    # 结束重绘

    def keyPressEvent(self, event):
        """重写keyPressEvent"""
        if self.isGameOver is False and self.isPause is False:
            if event.key() == Qt.Key_A:
                self.blockMove(-1)
            elif event.key() == Qt.Key_D:
                self.blockMove(1)
            if event.key() == Qt.Key_W:
                self.rotate()
            if event.key() == Qt.Key_S:
                # 加速下降, 加速一个方格
                self.blockDrop()