def iLabel(node, *args, **kargs): #code for making specialized faces for intermediates mostly cribbed from the ete2 website example (though not interactive): # http://pythonhosted.org/ete2/tutorial/tutorial_drawing.html#creating-your-custom-interactive-item-faces my_label = node.name ellipse = QGraphicsEllipseItem(0,0,fontSize*2,fontSize*2) #I think the first two are coords of center; second pair is major/minor axis ellipse.setPen(QPen(QColor( 'black' ))) ellipse.setBrush(QBrush(QColor( 'white' ))) text = QGraphicsSimpleTextItem(my_label) text.setParentItem(ellipse) text.setBrush(QBrush(QColor("black"))) font = QFont("Arial",fontSize*.9,weight=80) font.setLetterSpacing(1, 2) #add 2 pixels between letters for legibility text.setFont(font) #Center text according to masterItem size tw = text.boundingRect().width() th = text.boundingRect().height() center = ellipse.boundingRect().center() text.setPos(center.x()+1-tw/2, center.y()-th/2) #since the last letter has an extra 2 pixels after it from the spacing command, adjust center to compensate return ellipse
def show(cursor, pos=None, num_lines=6): """Displays a tooltip showing part of the cursor's Document. If the cursor has a selection, those blocks are displayed. Otherwise, num_lines lines are displayed. If pos is not given, the global mouse position is used. """ block = cursor.document().findBlock(cursor.selectionStart()) c2 = QTextCursor(block) if cursor.hasSelection(): c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor) c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) else: c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines) data = textformats.formatData('editor') doc = QTextDocument() font = QFont(data.font) font.setPointSizeF(font.pointSizeF() * .8) doc.setDefaultFont(font) doc.setPlainText(c2.selection().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlighter.highlight(doc, state=tokeniter.state(block)) size = doc.size().toSize() + QSize(8, -4) pix = QPixmap(size) pix.fill(data.baseColors['background']) doc.drawContents(QPainter(pix)) label = QLabel() label.setPixmap(pix) label.setStyleSheet("QLabel { border: 1px solid #777; }") label.resize(size) widgets.customtooltip.show(label, pos)
def __init__(self, parent=None, command="/bin/bash", font_name="Monospace", font_size=18): super(TerminalWidget, self).__init__(parent) # self.parent().setTabOrder(self, self) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._session = None self._last_update = None self._screen = [] self._text = [] self._cursor_rect = None self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._blink = False self._press_pos = None self._selection = None self._clipboard = QApplication.clipboard() QApplication.instance().lastWindowClosed.connect(Session.close_all) if command: self.execute()
def createAboutWidget( self ): self.AboutDock = QDockWidget( "About", self ) self.AboutDock.setObjectName( "about" ) self.AboutDock.setTitleBarWidget( QWidget() ) self.AboutDock.setContentsMargins( 0, 0, 0, 0 ) self.tabifyDockWidget( self.LegendDock, self.AboutDock ) self.LegendDock.raise_() # legendDock at the top from PyQt4.QtCore import QRect from PyQt4.QtGui import QSizePolicy, QGridLayout, QFont font = QFont() font.setFamily("Sans Serif") font.setPointSize(8.7) self.AboutWidget = QWidget() self.AboutWidget.setFont( font ) self.AboutWidget.setObjectName("AboutWidget") self.AboutDock.setWidget( self.AboutWidget ) self.labelAbout = QLabel( self.AboutWidget ) self.labelAbout.setAlignment(Qt.AlignCenter) self.labelAbout.setWordWrap(True) self.gridLayout = QGridLayout(self.AboutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.gridLayout.addWidget(self.labelAbout, 0, 1, 1, 1) self.labelAbout.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.LinksAccessibleByKeyboard|Qt.TextSelectableByKeyboard|Qt.TextSelectableByMouse) self.labelAbout.setOpenExternalLinks( True ) self.labelAbout.setText("<html><head/><body><a href=\"http://geotux.tuxfamily.org/index.php/en/geo-blogs/item/293-consola-sql-para-plugin-pgadmin-postgis-viewer\">PostGIS Layer Viewer</a> v.1.6.1 (2015.02.24)<br \><br \>" \ "Copyright (c) 2010 Ivan Mincik,<br \>[email protected]<br \>" \ u"Copyright (c) 2011-2015 Germán Carrillo,<br \>[email protected]<br \><br \>" \ "<i>Licensed under the terms of GNU GPL v.2.0</i><br \><br \>" \ "Based on PyQGIS. Plugin Fast SQL Layer by Pablo T. Carreira.</body></html>" )
def __init__(self): super(MonoSpaceLabel, self).__init__() font = QFont('monospace') font.setStyleHint(QFont.TypeWriter) self.setFont(font)
def minimumSizeHint(self): font = QFont(self.font()) font.setPointSize(font.pointSize() - 1) fm = QFontMetricsF(font) return QSize(fm.width(FractionSlider.WSTRING) * self.__denominator, (fm.height() * 4) + FractionSlider.YMARGIN)
def drawMarkings(self, painter): painter.save() painter.translate(self.width() / 2, self.height() / 2) scale = min((self.width() - self._margins) / 120.0, (self.height() - self._margins) / 120.0) painter.scale(scale, scale) font = QFont(self.font()) font.setPixelSize(10) metrics = QFontMetricsF(font) painter.setFont(font) painter.setPen(self.palette().color(QPalette.Shadow)) i = 0 while i < 360: if i % 45 == 0: painter.drawLine(0, -40, 0, -50) painter.drawText(-metrics.width(self._pointText[i]) / 2.0, -52, self._pointText[i]) else: painter.drawLine(0, -45, 0, -50) painter.rotate(15) i += 15 painter.restore()
def wheelEvent( self, event ): # scroll the font up and down with the wheel event if ( event.modifiers() == Qt.ControlModifier ): font = self.font() lexer = self.lexer() if ( lexer ): font = lexer.font(0) pointSize = font.pointSize() if ( event.delta() > 0 ): pointSize += 1 else: pointSize -= 1 if ( pointSize < 5 ): pointSize = 5 font.setPointSize( pointSize ) mfont = QFont(font) mfont.setPointSize(pointSize - 2) # set the font size self.setMarginsFont(mfont) self.setFont(font) if ( lexer ): lexer.setFont(font) self.fontSizeChanged.emit(pointSize) event.accept() else: super(XScintillaEdit,self).wheelEvent(event)
def font(self, text_style): device_font = text_style.fontfacename in LIBERATION_FONT_MAP try: if device_font: face = self.font_map[text_style.fontfacename] else: face = self.face_map[text_style.fontfacename] except KeyError: # Bad fontfacename field in LRF face = self.font_map['Dutch801 Rm BT Roman'] sz = text_style.fontsize wt = text_style.fontweight style = text_style.fontstyle font = (face, wt, style, sz,) if font in self.cache: rfont = self.cache[font] else: italic = font[2] == QFont.StyleItalic rfont = QFont(font[0], font[3], font[1], italic) rfont.setPixelSize(font[3]) rfont.setBold(wt>=69) self.cache[font] = rfont qfont = rfont if text_style.emplinetype != 'none': qfont = QFont(rfont) qfont.setOverline(text_style.emplineposition == 'before') qfont.setUnderline(text_style.emplineposition == 'after') return qfont
def __init__(self, dlgObj, workingPath): self.counter = -1 self.workingPath = workingPath self.defsFileName = os.path.abspath(os.path.join(self.workingPath, 'simsFile.txt')) self.dlgObj = dlgObj self.dlgObj.testLineEdit.clear() # add event for button "btnAddSimParams" self.dlgObj.btnAddSimParams.clicked.connect(self.eventAddSimParams) self.dlgObj.btnDelSimParams.clicked.connect(self.eventDelSimParams) self.columnLabels = [u'Capa origen', u'Col origen', u'Capa destino', u'Col destino', u'Vecindad', u'Tipo de cálculo', u'Fórmula', u'Peso min', u'T corte', u'Exp tiempo', u'Elasticidad'] self.colNames = ['origName', 'origFieldName', 'destName', 'destFieldName', 'vicinity', 'calcType', 'formType', 'minWeightDest', 'maxTimeCalc', 'expTime', 'elasticity', 'sideLength', 'sizeX', 'sizeY'] fnt = QFont() fnt.setPointSize(8) #fnt.setFamily("Arial") self.dlgObj.tblSimParams.setFont(fnt) self.dlgObj.tblSimParams.setColumnCount(len(self.columnLabels)) self.dlgObj.tblSimParams.setHorizontalHeaderLabels(self.columnLabels) # try to load simulation definitions from file try: defsFileSize = os.path.getsize(self.defsFileName) except: defsFileSize = -1 if defsFileSize > 0: dataFromFile = self.getSimulationDefinitions() for row_k in dataFromFile: self.counter += 1 self.dlgObj.tblSimParams.setRowCount(self.counter + 1) colIdx = 0 for key_h in self.colNames[0:11]: self.dlgObj.tblSimParams.setItem(self.counter, colIdx, QTableWidgetItem(str(row_k[key_h]))) colIdx += 1 self.dlgObj.tblSimParams.resizeColumnsToContents()
def __init__(self, printViewModel, baseFont): self.printViewModel = printViewModel # From core.gui.transaction_print self._rowFont = QFont(baseFont) self._splitFont = QFont(baseFont) self._splitFont.setPointSize(self._splitFont.pointSize()-2) self._headerFont = QFont(self._rowFont) self._headerFont.setBold(True)
def __init__(self, qnotero): """ Constructor Arguments: qnotero -- a Qnotero instance """ QStyledItemDelegate.__init__(self, qnotero) self.qnotero = qnotero self.boldFont = QFont() self.boldFont.setBold(True) self.regularFont = QFont() self.italicFont = QFont() self.italicFont.setItalic(True) self.tagFont = QFont() self.tagFont.setBold(True) self.tagFont.setPointSize(self.boldFont.pointSize() - 2) self.dy = QFontMetrics(self.boldFont) \ .size(Qt.TextSingleLine, "Dummy").height() \ *self.qnotero.theme.lineHeight() self.margin = 0.5*self.dy self._margin = 0.1*self.dy self.height = 5*self.dy+self._margin self.noPdfPixmap = self.qnotero.theme.pixmap("nopdf") self.pdfPixmap = self.qnotero.theme.pixmap("pdf") self.aboutPixmap = self.qnotero.theme.pixmap("about") self.notePixmap = self.qnotero.theme.pixmap("note") self.pixmapSize = self.pdfPixmap.height()+0.5*self.dy self.roundness = self.qnotero.theme.roundness()
def _get_font_from_string(self, font): if not font: font = QFont(settings.FONT_FAMILY, settings.FONT_SIZE) else: listFont = font.split(',') font = QFont(listFont[0].strip(), int(listFont[1].strip())) return font
def select_profile(profiles_dict): title = _('Profile Selection') input_label = _('Select a stored profile:') ok_label = _('OK') cancel_label = _('Quit') input_dialog = ComboBoxInputDialog(autoaccept=True) input_dialog.set_window_title(title) input_dialog.set_label_text(input_label) input_dialog.set_ok_button_text(ok_label) input_dialog.set_cancel_button_text(cancel_label) input_dialog.set_items(sorted(profiles_dict.keys()) + [NEW_PROFILE_LABEL]) _last_used_profile = last_used_profile() if _last_used_profile: input_dialog.set_choice_by_text(_last_used_profile) input_dialog.set_ok_button_default() last_index = input_dialog.count()-1 custom_font = QFont() custom_font.setItalic(True) icon = art.Icon('tango/16x16/actions/document-new.png').getQIcon() input_dialog.set_data(last_index, custom_font, Qt.FontRole) input_dialog.set_data(last_index, icon, Qt.DecorationRole) dialog_code = input_dialog.exec_() if dialog_code == QDialog.Accepted: return unicode(input_dialog.get_text()) return None
def __init__(self): QDialog.__init__(self) self.setupUi(self) self.setWindowIcon( QIcon('logo.svg') ) self.setWindowFlags( Qt.WindowMinimizeButtonHint ) s = QSettings( "norBIT", "norGIS-ALKIS-Import" ) self.leSERVICE.setText( s.value( "service", "" ) ) self.leHOST.setText( s.value( "host", "" ) ) self.lePORT.setText( s.value( "port", "5432" ) ) self.leDBNAME.setText( s.value( "dbname", "" ) ) self.leUID.setText( s.value( "uid", "" ) ) self.lePWD.setText( s.value( "pwd", "" ) ) self.leGT.setText( s.value( "gt", "20000" ) ) self.leGT.setValidator( QIntValidator( -1, 99999999 ) ) self.lstFiles.addItems( s.value( "files", [] ) or [] ) self.cbxSkipFailures.setChecked( s.value( "skipfailures", False, type=bool ) ) self.cbFnbruch.setCurrentIndex( 0 if s.value( "fnbruch", True, type=bool ) else 1 ) self.cbxUseCopy.setChecked( s.value( "usecopy", False, type=bool ) ) self.cbxCreate.setChecked( False ) self.cbEPSG.addItem( "UTM32N", "25832") self.cbEPSG.addItem( "UTM33N", "25833") self.cbEPSG.addItem( "3GK2 (BW)", "131466") self.cbEPSG.addItem( "3GK3 (BW)", "131467") self.cbEPSG.addItem( "3GK4 (BY)", "131468") self.cbEPSG.setCurrentIndex( self.cbEPSG.findData( s.value( "epsg", "25832" ) ) ) self.pbAdd.clicked.connect(self.selFiles) self.pbAddDir.clicked.connect(self.selDir) self.pbRemove.clicked.connect(self.rmFiles) self.pbSelectAll.clicked.connect( self.lstFiles.selectAll ) self.pbLoad.clicked.connect(self.loadList) self.pbSave.clicked.connect(self.saveList) self.lstFiles.itemSelectionChanged.connect(self.selChanged) self.pbStart.clicked.connect(self.run) self.pbLoadLog.clicked.connect(self.loadLog) self.pbSaveLog.clicked.connect(self.saveLog) self.pbClearLog.clicked.connect(self.clearLog) self.pbAbout.clicked.connect(self.about) self.pbClose.clicked.connect(self.accept) self.pbProgress.setVisible( False ) f = QFont("Monospace") f.setStyleHint( QFont.TypeWriter ) self.lwProtocol.setFont( f ) self.lwProtocol.setUniformItemSizes(True) self.status("") self.restoreGeometry( s.value("geometry", QByteArray(), type=QByteArray) ) self.canceled = False self.running = False self.skipScroll = False self.logqry = None self.reFilter = None
def __init__(self, callback): super().__init__() self.callback = callback #Toolbar toolbar = QToolBar(self) self.button_test = toolbar.addAction("Test script") self.button_burn = toolbar.addAction("Write script to ROM") #self.button_reload = toolbar.addAction("Refresh") self.button_pokescriptdoc = toolbar.addAction("PokeScript doc") self.button_pokescriptdoc.setToolTip("Opens your webbrowser, pointing at a page where some elemnets of PokeScript are explained.") self.button_scriptdoc = toolbar.addAction("List of commands.") self.button_scriptdoc.setToolTip("Opens a list of available commands in your default browser.") toolbar.actionTriggered.connect(self.toolbarAction) #Code editor sourceeditor = LNTextEdit(self) font = QFont("Monospace") font.setStyleHint(QFont.TypeWriter) sourceeditor.setFont(font) sourceeditor.setLineWrapMode(0) sourceeditor.setHighlighterClass(PokeScriptHighlighter) #Wrap it up layout = QVBoxLayout(self) layout.addWidget(toolbar) layout.addWidget(sourceeditor) layout.setContentsMargins(0, 0, 0, 0) #Store elements that we need later self.sourceeditor = sourceeditor
def __init__(self, manager): ''' See XmlController for documentation ''' XmlController.__init__(self, manager) # Create popup menu actions p = ('add', "Create model from template", self._show_dialog_for_template_node) self.action_create_model_from_template = self.create_action(*p) p = ('estimation', "Run Estimation", self.run_estimation_for_selected) self.action_run_estimation = self.create_action(*p) p = ('', "Right click the individual groups (specification/<group>) to estimate", lambda: ()) self.action_show_how_to_estimate_groups = self.create_action(*p) p = ('estimation', "Run Estimation Group", self.run_estimation_for_selected_group) self.action_run_estimation_group = self.create_action(*p) p = ('submodel', "Edit Submodel", self._open_submodel_editor_for_selected) self.action_edit_submodel = self.create_action(*p) font = QFont() font.setBold(True) self.action_edit_submodel.setFont(font) # Create a list of available template nodes self.create_from_template_actions = [] template_nodes = self.project.findall('model_manager/templates/model_template') templates = dict((node.get('name'), node) for node in template_nodes) for template_name, template_node in templates.items(): callback = lambda x = template_node: self._show_dialog_for_template_node(x) action = self.create_action('clone', template_name, callback) self.create_from_template_actions.append(action) self.editor = None self.view.connect(self.view, SIGNAL('doubleClicked(const QModelIndex&)'), self._on_double_click)
def test(): from SMlib.utils.qthelpers import qapplication app = qapplication() from SMlib.widgets.externalshell.pythonshell import ExternalPythonShell from SMlib.widgets.externalshell.systemshell import ExternalSystemShell import SMlib from SMlib.plugins.variableexplorer import VariableExplorer settings = VariableExplorer.get_settings() shell = ExternalPythonShell(wdir=osp.dirname(SMlib.__file__), ipykernel=True, stand_alone=settings, arguments="-q4thread -pylab -colors LightBG", mpl_patch_enabled=True, light_background=False) # shell = ExternalPythonShell(wdir=osp.dirname(SMlib.__file__), # interact=True, umd_enabled=True, # stand_alone=settings, # umd_namelist=['guidata', 'guiqwt'], # umd_verbose=True, mpl_patch_enabled=False, # light_background=False) # shell = ExternalSystemShell(wdir=osp.dirname(SMlib.__file__), # light_background=False) shell.shell.toggle_wrap_mode(True) shell.start_shell(False) from PyQt4.QtGui import QFont font = QFont("Lucida console") font.setPointSize(10) shell.shell.set_font(font) shell.show() sys.exit(app.exec_())
def applySettings(self): """Apply editor and lexer settings """ if self.qscilexer is None: return # Apply fonts and colors config = core.config()["Editor"] defaultFont = QFont(config["DefaultFont"], config["DefaultFontSize"]) self.qscilexer.setDefaultFont(defaultFont) for i in range(128): if self.qscilexer.description(i): font = self.qscilexer.font(i) font.setFamily(defaultFont.family()) font.setPointSize(defaultFont.pointSize()) self.qscilexer.setFont(font, i) # lexer->setColor(lexer->defaultColor(i), i); # TODO configure lexer colors # lexer->setEolFill(lexer->defaultEolFill(i), i); # lexer->setPaper(lexer->defaultPaper(i), i); if config["DefaultDocumentColours"]: self.qscilexer.setPaper(QColor(config["DefaultDocumentPaper"]), i) self.qscilexer.setEolFill(True, i) else: self.qscilexer.setPaper(self.qscilexer.defaultPaper(i), i) self.qscilexer.setEolFill(self.qscilexer.defaultEolFill(i), i) if config["DefaultDocumentColours"]: self.qscilexer.setColor(QColor(config["DefaultDocumentPen"]), 0) else: self.qscilexer.setColor(self.qscilexer.defaultColor(0), 0)
def paint_text(self, QPainter): """ Render the node text (commit sha and label) :param QPainter: interface to the canvas """ # Set up font and text settings text_font = QFont() text_font.setPointSize(NODE_TEXT_FONT_SIZE) QPainter.setFont(text_font) QPainter.setPen(NODE_TEXT_COLOR) # Measure size of strings so they can be positioned properly font_metrics = QFontMetrics(text_font) label_text_width = font_metrics.width(NODE_LABEL_TEXT) sha_text_width = font_metrics.width(self.commit.sha.get_string_of_length(NODE_SHA_LENGTH)) # Position and render text label_margin = (NODE_WIDTH - label_text_width) / 2 label_position = QPointF(label_margin, 15) QPainter.drawText(label_position, NODE_LABEL_TEXT) sha_margin = (NODE_WIDTH - sha_text_width) / 2 sha_position = QPointF(sha_margin, 25) QPainter.drawText(sha_position, self.commit.sha.get_string_of_length(NODE_SHA_LENGTH))
def load_presentation(self, config): if 'restedit' in config: for key, value in config['restedit']: if key == 'font': qtfont = QFont() if qtfont.fromString(value): self.setFont(qtfont)
def __init__(self,parent, font_name, font_size, font_height, w,h, colorscheme): super().__init__(parent) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._screen = [] self._text = [] self._transform= QTransform() self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._kbdfunc= None self._w=w self._h=h self._alt_sequence= False self._alt_seq_length=0 self._alt_seq_value=0 self._cursortype= CURSOR_OFF self._color_scheme=self.color_schemes[self.color_scheme_names[colorscheme]] self._cursor_color=self._color_scheme[2] self._cursor_char= 0x20 self._cursor_attr=-1 self._cursor_update=True self._blink= True self._blink_counter=0 self._cursor_rect = QRect(0, 0, self._char_width, self._char_height) self._cursor_polygon=QPolygon([QPoint(0,0+(self._char_height/2)), QPoint(0+(self._char_width*0.8),0+self._char_height), QPoint(0+(self._char_width*0.8),0+(self._char_height*0.67)), QPoint(0+self._char_width,0+(self._char_height*0.67)), QPoint(0+self._char_width,0+(self._char_height*0.33)), QPoint(0+(self._char_width*0.8),0+(self._char_height*0.33)), QPoint(0+(self._char_width*0.8),0), QPoint(0,0+(self._char_height/2))])
def Paint(self): scene = QGraphicsScene() # Draw the graph tt = self.ui.graphtype.currentIndex() if tt == 0: points = self.avgSpeed elif tt == 1: points = self.avgVolume elif tt == 2: points = self.avgCapacity elif tt == 3: points = self.avgRam p0 = points[0] for p in points[1:]: scene.addLine(5 + p0[0] * 2, 205 - p0[1] * 2, 5 + p[0] * 2, 205 - p[1] * 2, QPen(self.settings["graph"])) p0 = p # Draw the axis scene.addLine(5, 5, 5, 208, QPen(self.settings["axis"])) scene.addLine(2, 205, self.time * 2 + 5, 205, QPen(self.settings["axis"])) t = 0 while t <= self.time: scene.addLine(5 + t * 2, 206, 5 + t * 2, 204, QPen(self.settings["axis"])) font = QFont() font.setPointSize(6) capt = scene.addText(str(t), font) capt.setPos(t * 2, 203) t += 10 self.ui.graph.setScene(scene)
def __init__(self, parent=None): super(MikidownCfgDialog, self).__init__(parent) #tab = QWidget() #tab2 = QWidget() self.setWindowTitle(self.tr("Settings - mikidown")) self.recentNotesCount = QSpinBox() recent_notes_n = Mikibook.settings.value('recentNotesNumber',type=int, defaultValue=20) self.recentNotesCount.setValue(recent_notes_n) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.hltCfg = MikidownHighlightCfgWidget(parent=self) self.tabWidth = QSpinBox(self) self.tabWidth.setRange(2, 8) self.tabWidth.setSingleStep(2) self.iconTheme = QLineEdit(self) self.iconTheme.setText(Mikibook.settings.value('iconTheme', QIcon.themeName())) self.editorFont = QFontButton(parent=self) fontval = QFont() fontfam = Mikibook.settings.value('editorFont', defaultValue=None) fontsize = Mikibook.settings.value('editorFontSize', type=int, defaultValue=12) if fontfam is not None: fontval.setFamily(fontfam) fontval.setPointSize(fontsize) self.headerScalesFont = QCheckBox(self) if Mikibook.settings.value('headerScaleFont', type=bool, defaultValue=True): self.headerScalesFont.setCheckState(Qt.Checked) else: self.headerScalesFont.setCheckState(Qt.Unchecked) self.editorFont.font = fontval self.tabWidth.setValue(Mikibook.settings.value('tabWidth', type=int, defaultValue=4)) self.tabToSpaces = QCheckBox(self) if Mikibook.settings.value('tabInsertsSpaces', type=bool, defaultValue=True): self.tabToSpaces.setCheckState(Qt.Checked) else: self.tabToSpaces.setCheckState(Qt.Unchecked) layout = QGridLayout(self) layout.addWidget(QLabel(self.tr("# of recently viewed notes to keep")),0,0,1,1) layout.addWidget(self.recentNotesCount,0,1,1,1) layout.addWidget(QLabel(self.tr("Editor font")), 1, 0, 1, 1) layout.addWidget(self.editorFont, 1, 1, 1, 1) layout.addWidget(QLabel(self.tr("Header rank scales editor font?")), 2, 0, 1, 1) layout.addWidget(self.headerScalesFont, 2, 1, 1, 1) qs = QScrollArea(self) qs.setWidget(self.hltCfg) layout.addWidget(QLabel(self.tr("Tabs expand to spaces?")), 3, 0, 1, 1) layout.addWidget(self.tabToSpaces, 3, 1, 1, 1) layout.addWidget(QLabel(self.tr("Tab width")), 4, 0, 1, 1) layout.addWidget(self.tabWidth, 4, 1, 1, 1) layout.addWidget(QLabel(self.tr("Icon Theme")),5,0,1,1) layout.addWidget(self.iconTheme,5,1,1,1) layout.addWidget(qs,6,0,1,2) layout.addWidget(self.buttonBox,7,0,1,2) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
def data(self, index, role=Qt.DisplayRole): """ This function is used by Qt to obtain data needed by the view. It is mandatory for the model to work. """ if not index.isValid() or not (0 <= index.row() < len(self.nodes)): return QVariant() node = self.nodes[index.row()] column = index.column() if role == Qt.DisplayRole: if column == PANID: return QVariant(node.panId) elif column == ADDRESS: return QVariant(node.address) elif column == NAME: return QVariant(node.name) elif role == Qt.FontRole: if column in (PANID, ADDRESS): font = QFont() font.setFamily("DejaVu Sans Mono") return font return QVariant()
def setNameAndBrush(self, sigma, color=Qt.black): self.sigma = sigma self.setText( decode_to_qstring("σ=%.1fpx" % self.sigma, "utf-8") ) # This file is encoded as utf-8, so this string should be decoded as such. total_window = 1 + 2 * int(self.sigma * self.window_size + 0.5) self.setToolTip("sigma = {:.1f} pixels, window diameter = {:.1f}".format(self.sigma, total_window)) font = QFont() font.setPointSize(10) font.setBold(True) self.setFont(font) self.setForeground(color) pixmap = QPixmap(self.pixmapSize) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.setPen(color) brush = QBrush(color) painter.setBrush(brush) painter.drawEllipse( QRect( self.pixmapSize.width() / 2 - self.brushSize / 2, self.pixmapSize.height() / 2 - self.brushSize / 2, self.brushSize, self.brushSize, ) ) painter.end() self.setIcon(QIcon(pixmap)) self.setTextAlignment(Qt.AlignVCenter)
def __init__(self, mime, parent=None): QTextEdit.__init__(self, parent) self.setAcceptRichText(False) font = QFont() font.setFamily('Terminal [DEC]') self.setFont(font) ts = QFontMetrics(font).maxWidth()
def __init__(self,parent, font_name, font_size, cols, rows, colorscheme): super().__init__(parent) self.callback_scrollbar= None # # determine font metrics and terminal window size in pixel # font= QFont(font_name) font.setPixelSize(font_size) metrics= QFontMetrics(font) font_width=metrics.width("A") font_height=metrics.height() width= font_width*cols height= int(font_height* rows) # # create terminal window and scrollbar # self.hbox= QHBoxLayout() self.terminalwidget= QTerminalWidget(self,font_name,font_size,font_height, width,height, colorscheme) self.hbox.addWidget(self.terminalwidget) self.hbox.setAlignment(self.terminalwidget,Qt.AlignLeft) self.scrollbar= QScrollBar() self.hbox.addWidget(self.scrollbar) self.hbox.setAlignment(self.scrollbar,Qt.AlignLeft) self.setLayout(self.hbox) # # initialize scrollbar # self.scrollbar.valueChanged.connect(self.do_scrollbar) self.scrollbar.setEnabled(False)
def generate_tree_model(self, data_dict): """Generate a tree model for specified dictionary :param data_dict: A dictionary :type data_dict: dict :return: list of QTreeWidgetItem :rtype list: """ widget_items = [] font = QFont() font.setBold(True) for key in data_dict.keys(): entry = data_dict[key] key_item = QTreeWidgetItem() key_item.setText(0, str(key)) key_item.setFont(0, font) if isinstance(entry, dict): items = self.generate_tree_model(entry) key_item.addChildren(items) else: # value_item = QTreeWidgetItem() key_item.setText(1, str(entry)) key_item.setFlags(key_item.flags() | Qt.ItemIsEditable) # key_item.addChild(key_item) widget_items.append(key_item) return widget_items
def __init__(self, parent): QDialog.__init__(self, parent) self.prm = self.parent().prm self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.vBoxSizer = QVBoxLayout() self.hBoxSizer = QVBoxLayout() self.browser = QTextBrowser() self.browser.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.anotherFortuneButton = QPushButton(self.tr("One More!"), self) self.anotherFortuneButton.clicked.connect(self.onClickAnotherFortuneButton) self.hBoxSizer.addWidget(self.anotherFortuneButton) idx = random.choice(range(len(self.prm['appData']['fortunesList']))) self.browser.append(self.prm['appData']['fortunesList'][idx]['quote']) self.browser.append('\n') self.browser.append(self.prm['appData']['fortunesList'][idx]['author']) self.browser.append("In:" + self.prm['appData']['fortunesList'][idx]['source']) font = QFont() font.setFamily("Arial") font.setPointSize(12) self.browser.setFont(font) self.vBoxSizer.addWidget(self.browser) self.vBoxSizer.addLayout(self.hBoxSizer) #self.vBoxSizer.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(self.vBoxSizer) self.setWindowTitle(self.tr("pychoacoustics - fortunes")) self.resize(450, 450) self.show()
class ScaleBarItem(QGraphicsItem): def __init__(self, canvas, parent=None): super(ScaleBarItem, self).__init__(parent) self.canvas = canvas self.realsize = 100 black = QColor(Qt.black) black.setAlpha(150) white = QColor(Qt.white) white.setAlpha(150) blackpen = QPen(black, 4) whitepen = QPen(white, 8) self.pens = [whitepen, blackpen] self.whitepen = QPen(white, 1) self.blackbrush = QBrush(black) self.ticksize = 10 self.fontsize = 15 self.font = QFont() self.font.setPointSize(self.fontsize) self.font.setStyleHint(QFont.Times, QFont.PreferAntialias) self.font.setBold(True) self.metrics = QFontMetrics(self.font) def boundingRect(self): try: width, realsize, label, fontsize = self._calc_size() halfheight = (self.ticksize + fontsize[1]) / 2 halfwidth = (width + fontsize[0]) / 2 return QRectF(-halfwidth, -halfheight, halfwidth, halfheight) except ZeroDivisionError: return QRectF() def paint(self, painter, styleoptions, widget=None): try: width, realsize, label, fontsize = self._calc_size() except ZeroDivisionError: return mapunits = self.canvas.mapUnits() # painter.drawRect(self.boundingRect()) array = QPolygon() canvasheight = self.canvas.height() canvaswidth = self.canvas.width() margin = 20 originy = 0 originx = 0 self.setPos(margin, canvasheight - margin) x1, y1 = originx, originy x2, y2 = originx, originy + self.ticksize x3, y3 = originx + width, originy + self.ticksize midx, midy = originx + width / 2, originy + self.ticksize / 2 x4, y4 = originx + width, originy for pen in self.pens: painter.setPen(pen) # Drwa the scale bar painter.drawLine(x1, y1, x2, y2) painter.drawLine(x2, y2, x3, y3) painter.drawLine(x3, y3, x4, y4) painter.drawLine(midx, midy, midx, y1) # Draw the text fontwidth = self.metrics.width("0") fontheight = self.metrics.height() fontheight /= 2 fontwidth /= 2 path = QPainterPath() point = QPointF(x1 - fontwidth, y1 - fontheight) path.addText(point, self.font, "0") painter.setPen(self.whitepen) painter.setBrush(self.blackbrush) painter.setRenderHints(QPainter.Antialiasing) painter.setFont(self.font) painter.drawPath(path) fontwidth = self.metrics.width(label) fontheight = self.metrics.height() fontheight /= 2 fontwidth /= 2 point = QPointF(x4 - fontwidth, y4 - fontheight) path.addText(point, self.font, label) painter.drawPath(path) def _calc_size(self): realSize = self.realsize canvaswidth = self.canvas.width() mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel()) mapunits = self.canvas.mapUnits() prefered_units = roam.config.settings.get("prefer_units", "meters") newunits = QGis.fromLiteral(prefered_units, QGis.Meters) mapunitsperpixel *= QGis.fromUnitToUnitFactor(mapunits, newunits) mapunits = newunits # Convert the real distance into pixels barwidth = realSize / mapunitsperpixel if barwidth < 30: barwidth = canvaswidth / 4 while barwidth > canvaswidth / 3: barwidth /= 3 realSize = barwidth * mapunitsperpixel # Round powerof10 = math.floor(math.log10(realSize)) scaler = math.pow(10.0, powerof10) realSize = round(realSize / scaler) * scaler barwidth = realSize / mapunitsperpixel label, realSize = self._label_size(mapunits, realSize) metrics = QFontMetrics(self.font) fontwidth = metrics.width(label) fontheight = metrics.height() sizelabel = QLocale.system().toString(realSize) sizelabel = "{} {}".format(sizelabel, label) barwidth = self._adjust_bar_size(barwidth, mapunits) barwidth = barwidth + fontwidth return barwidth, realSize, sizelabel, (fontwidth, fontheight) def _label_size(self, unit, currentsize): if unit == QGis.Meters: if currentsize > 1000: return "km", currentsize / 1000 elif currentsize < 0.01: return "mm", currentsize * 1000 elif currentsize < 0.1: return "cm", currentsize * 100 else: return "m", currentsize elif unit == QGis.Feet: print currentsize if currentsize > 5280.0: return "miles", currentsize / 5000 elif currentsize == 5280.0: return "mile", currentsize / 5000 elif currentsize < 1: return "inches", currentsize * 10 elif currentsize == 1.0: return "foot", currentsize else: return "feet", currentsize elif unit == QGis.Degrees: if currentsize == 1.0: return "degree", currentsize else: return "degrees", currentsize else: return str(unit), currentsize def _adjust_bar_size(self, barsize, unit): if unit == QGis.Feet: if barsize > 5280.0 or barsize == 5280.0: return (barsize * 5290) / 5000 elif barsize < 1: return (barsize * 10) / 12 return barsize
def __init__(self, conteneur=None): QTextBrowser.__init__(self) self.setParent(conteneur) self.font = QFont("Courier", 12) self.setFont(self.font) self.clearTT()
def __init__(self, parent, rnavType, category, position_0, position_1, position_List, flagStr = None): QDialog.__init__(self, parent) self.flagStrName = flagStr # self.resize(326, 310) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(6) self.verticalLayout.setMargin(3) self.verticalLayout.setObjectName(("verticalLayout")) self.groupBox = QGroupBox(self) self.groupBox.setTitle(("")) self.groupBox.setObjectName(("groupBox")) self.verticalLayout_2 = QVBoxLayout(self.groupBox) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setMargin(3) self.verticalLayout_2.setObjectName(("verticalLayout_2")) self.groupBox_5 = QGroupBox(self.groupBox) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox_5.sizePolicy().hasHeightForWidth()) self.groupBox_5.setSizePolicy(sizePolicy) font = QFont() font.setFamily(("Arial")) self.groupBox_5.setFont(font) self.groupBox_5.setObjectName(("groupBox_5")) self.horizontalLayout_19 = QHBoxLayout(self.groupBox_5) self.horizontalLayout_19.setSpacing(0) self.horizontalLayout_19.setMargin(0) self.horizontalLayout_19.setObjectName(("horizontalLayout_19")) self.frame_18 = QFrame(self.groupBox_5) self.frame_18.setFrameShape(QFrame.StyledPanel) self.frame_18.setFrameShadow(QFrame.Raised) self.frame_18.setObjectName(("frame_18")) self.verticalLayout_13 = QVBoxLayout(self.frame_18) self.verticalLayout_13.setSpacing(0) self.verticalLayout_13.setContentsMargins(-1, -1, 0, -1) self.verticalLayout_13.setObjectName(("verticalLayout_13")) self.frame_19 = QFrame(self.frame_18) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_19.sizePolicy().hasHeightForWidth()) self.frame_19.setSizePolicy(sizePolicy) self.frame_19.setFrameShape(QFrame.StyledPanel) self.frame_19.setFrameShadow(QFrame.Raised) self.frame_19.setObjectName(("frame_19")) self.horizontalLayout_20 = QHBoxLayout(self.frame_19) self.horizontalLayout_20.setSpacing(0) self.horizontalLayout_20.setMargin(0) self.horizontalLayout_20.setObjectName(("horizontalLayout_20")) self.label_9 = QLabel(self.frame_19) self.label_9.setMaximumSize(QSize(60, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.label_9.setFont(font) self.label_9.setObjectName(("label_9")) self.horizontalLayout_20.addWidget(self.label_9) self.txtTHR_X = QLineEdit(self.frame_19) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtTHR_X.sizePolicy().hasHeightForWidth()) self.txtTHR_X.setSizePolicy(sizePolicy) self.txtTHR_X.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtTHR_X.setFont(font) self.txtTHR_X.setObjectName(("txtTHR_X")) self.horizontalLayout_20.addWidget(self.txtTHR_X) self.verticalLayout_13.addWidget(self.frame_19) self.frame_20 = QFrame(self.frame_18) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_20.sizePolicy().hasHeightForWidth()) self.frame_20.setSizePolicy(sizePolicy) self.frame_20.setFrameShape(QFrame.StyledPanel) self.frame_20.setFrameShadow(QFrame.Raised) self.frame_20.setObjectName(("frame_20")) self.horizontalLayout_21 = QHBoxLayout(self.frame_20) self.horizontalLayout_21.setSpacing(0) self.horizontalLayout_21.setMargin(0) self.horizontalLayout_21.setObjectName(("horizontalLayout_21")) self.label_10 = QLabel(self.frame_20) self.label_10.setMaximumSize(QSize(60, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.label_10.setFont(font) self.label_10.setObjectName(("label_10")) self.horizontalLayout_21.addWidget(self.label_10) self.txtTHR_Y = QLineEdit(self.frame_20) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtTHR_Y.sizePolicy().hasHeightForWidth()) self.txtTHR_Y.setSizePolicy(sizePolicy) self.txtTHR_Y.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtTHR_Y.setFont(font) self.txtTHR_Y.setObjectName(("txtTHR_Y")) self.horizontalLayout_21.addWidget(self.txtTHR_Y) self.verticalLayout_13.addWidget(self.frame_20) self.horizontalLayout_19.addWidget(self.frame_18) self.frame_21 = QFrame(self.groupBox_5) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_21.sizePolicy().hasHeightForWidth()) self.frame_21.setSizePolicy(sizePolicy) self.frame_21.setMaximumSize(QSize(30, 70)) self.frame_21.setFrameShape(QFrame.StyledPanel) self.frame_21.setFrameShadow(QFrame.Raised) self.frame_21.setObjectName(("frame_21")) self.verticalLayout_14 = QVBoxLayout(self.frame_21) self.verticalLayout_14.setSpacing(0) self.verticalLayout_14.setMargin(0) self.verticalLayout_14.setObjectName(("verticalLayout_14")) self.btnCaptureRunwayTHR = QToolButton(self.frame_21) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnCaptureRunwayTHR.sizePolicy().hasHeightForWidth()) self.btnCaptureRunwayTHR.setSizePolicy(sizePolicy) self.btnCaptureRunwayTHR.setMaximumSize(QSize(16777215, 47)) icon = QIcon() icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")), QIcon.Normal, QIcon.Off) self.btnCaptureRunwayTHR.setIcon(icon) self.btnCaptureRunwayTHR.setObjectName(("btnCaptureRunwayTHR")) self.verticalLayout_14.addWidget(self.btnCaptureRunwayTHR) # self.btnToolTHR = QToolButton(self.frame_21) # sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # sizePolicy.setHeightForWidth(self.btnToolTHR.sizePolicy().hasHeightForWidth()) # self.btnToolTHR.setSizePolicy(sizePolicy) # self.btnToolTHR.setMaximumSize(QSize(16777215, 20)) # icon1 = QIcon() # icon1.addPixmap(QPixmap(("Resource/sort2.png")), QIcon.Normal, QIcon.Off) # self.btnToolTHR.setIcon(icon1) # self.btnToolTHR.setObjectName(("btnToolTHR")) # self.verticalLayout_14.addWidget(self.btnToolTHR) self.horizontalLayout_19.addWidget(self.frame_21) self.verticalLayout_2.addWidget(self.groupBox_5) self.groupBox_4 = QGroupBox(self.groupBox) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox_4.sizePolicy().hasHeightForWidth()) self.groupBox_4.setSizePolicy(sizePolicy) font = QFont() font.setFamily(("Arial")) self.groupBox_4.setFont(font) self.groupBox_4.setObjectName(("groupBox_4")) self.horizontalLayout_16 = QHBoxLayout(self.groupBox_4) self.horizontalLayout_16.setSpacing(0) self.horizontalLayout_16.setMargin(0) self.horizontalLayout_16.setObjectName(("horizontalLayout_16")) self.frame_14 = QFrame(self.groupBox_4) self.frame_14.setFrameShape(QFrame.StyledPanel) self.frame_14.setFrameShadow(QFrame.Raised) self.frame_14.setObjectName(("frame_14")) self.verticalLayout_11 = QVBoxLayout(self.frame_14) self.verticalLayout_11.setSpacing(0) self.verticalLayout_11.setContentsMargins(-1, -1, 0, -1) self.verticalLayout_11.setObjectName(("verticalLayout_11")) self.frame_15 = QFrame(self.frame_14) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_15.sizePolicy().hasHeightForWidth()) self.frame_15.setSizePolicy(sizePolicy) self.frame_15.setFrameShape(QFrame.StyledPanel) self.frame_15.setFrameShadow(QFrame.Raised) self.frame_15.setObjectName(("frame_15")) self.horizontalLayout_17 = QHBoxLayout(self.frame_15) self.horizontalLayout_17.setSpacing(0) self.horizontalLayout_17.setMargin(0) self.horizontalLayout_17.setObjectName(("horizontalLayout_17")) self.label_7 = QLabel(self.frame_15) self.label_7.setMaximumSize(QSize(60, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.label_7.setFont(font) self.label_7.setObjectName(("label_7")) self.horizontalLayout_17.addWidget(self.label_7) self.txtEND_X = QLineEdit(self.frame_15) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtEND_X.sizePolicy().hasHeightForWidth()) self.txtEND_X.setSizePolicy(sizePolicy) self.txtEND_X.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtEND_X.setFont(font) self.txtEND_X.setObjectName(("txtEND_X")) self.horizontalLayout_17.addWidget(self.txtEND_X) self.verticalLayout_11.addWidget(self.frame_15) self.frame_16 = QFrame(self.frame_14) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_16.sizePolicy().hasHeightForWidth()) self.frame_16.setSizePolicy(sizePolicy) self.frame_16.setFrameShape(QFrame.StyledPanel) self.frame_16.setFrameShadow(QFrame.Raised) self.frame_16.setObjectName(("frame_16")) self.horizontalLayout_18 = QHBoxLayout(self.frame_16) self.horizontalLayout_18.setSpacing(0) self.horizontalLayout_18.setMargin(0) self.horizontalLayout_18.setObjectName(("horizontalLayout_18")) self.label_8 = QLabel(self.frame_16) self.label_8.setMaximumSize(QSize(60, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.label_8.setFont(font) self.label_8.setObjectName(("label_8")) self.horizontalLayout_18.addWidget(self.label_8) self.txtEND_Y = QLineEdit(self.frame_16) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtEND_Y.sizePolicy().hasHeightForWidth()) self.txtEND_Y.setSizePolicy(sizePolicy) self.txtEND_Y.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtEND_Y.setFont(font) self.txtEND_Y.setObjectName(("txtEND_Y")) self.horizontalLayout_18.addWidget(self.txtEND_Y) self.verticalLayout_11.addWidget(self.frame_16) self.horizontalLayout_16.addWidget(self.frame_14) self.frame_17 = QFrame(self.groupBox_4) self.frame_17.setMaximumSize(QSize(30, 16777215)) self.frame_17.setFrameShape(QFrame.StyledPanel) self.frame_17.setFrameShadow(QFrame.Raised) self.frame_17.setObjectName(("frame_17")) self.verticalLayout_12 = QVBoxLayout(self.frame_17) self.verticalLayout_12.setSpacing(0) self.verticalLayout_12.setMargin(0) self.verticalLayout_12.setObjectName(("verticalLayout_12")) self.btnCaptureRunwayEND = QToolButton(self.frame_17) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnCaptureRunwayEND.sizePolicy().hasHeightForWidth()) self.btnCaptureRunwayEND.setSizePolicy(sizePolicy) self.btnCaptureRunwayEND.setMaximumSize(QSize(16777215, 47)) self.btnCaptureRunwayEND.setIcon(icon) self.btnCaptureRunwayEND.setObjectName(("btnCaptureRunwayEND")) self.verticalLayout_12.addWidget(self.btnCaptureRunwayEND) # self.btnToolEND = QToolButton(self.frame_17) # sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # sizePolicy.setHeightForWidth(self.btnToolEND.sizePolicy().hasHeightForWidth()) # self.btnToolEND.setSizePolicy(sizePolicy) # self.btnToolEND.setMaximumSize(QSize(16777215, 20)) # self.btnToolEND.setIcon(icon1) # self.btnToolEND.setObjectName(("btnToolEND")) # self.verticalLayout_12.addWidget(self.btnToolEND) self.horizontalLayout_16.addWidget(self.frame_17) self.verticalLayout_2.addWidget(self.groupBox_4) self.lbl1 = QLabel(self.groupBox) font = QFont() font.setFamily(("Arial")) self.lbl1.setFont(font) self.lbl1.setText(("")) self.lbl1.setAlignment(Qt.AlignCenter) self.lbl1.setWordWrap(False) self.lbl1.setMargin(0) self.lbl1.setObjectName(("lbl1")) self.verticalLayout_2.addWidget(self.lbl1) self.lbl2 = QLabel(self.groupBox) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.lbl2.setFont(font) self.lbl2.setText(("")) self.lbl2.setAlignment(Qt.AlignCenter) self.lbl2.setObjectName(("lbl2")) self.verticalLayout_2.addWidget(self.lbl2) self.frame_22 = QFrame(self.groupBox) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_22.sizePolicy().hasHeightForWidth()) self.frame_22.setSizePolicy(sizePolicy) self.frame_22.setFrameShape(QFrame.StyledPanel) self.frame_22.setFrameShadow(QFrame.Raised) self.frame_22.setObjectName(("frame_22")) self.horizontalLayout_22 = QHBoxLayout(self.frame_22) self.horizontalLayout_22.setSpacing(0) self.horizontalLayout_22.setMargin(0) self.horizontalLayout_22.setObjectName(("horizontalLayout_22")) self.label_11 = QLabel(self.frame_22) self.label_11.setMinimumSize(QSize(170, 0)) self.label_11.setMaximumSize(QSize(180, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.label_11.setFont(font) self.label_11.setObjectName(("label_11")) self.horizontalLayout_22.addWidget(self.label_11) self.txtForm = QLineEdit(self.frame_22) self.txtForm.setEnabled(False) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtForm.sizePolicy().hasHeightForWidth()) self.txtForm.setSizePolicy(sizePolicy) self.txtForm.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtForm.setFont(font) self.txtForm.setObjectName(("txtForm")) self.horizontalLayout_22.addWidget(self.txtForm) self.verticalLayout_2.addWidget(self.frame_22) self.frame_23 = QFrame(self.groupBox) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_23.sizePolicy().hasHeightForWidth()) self.frame_23.setSizePolicy(sizePolicy) self.frame_23.setFrameShape(QFrame.StyledPanel) self.frame_23.setFrameShadow(QFrame.Raised) self.frame_23.setObjectName(("frame_23")) self.horizontalLayout_23 = QHBoxLayout(self.frame_23) self.horizontalLayout_23.setSpacing(0) self.horizontalLayout_23.setMargin(0) self.horizontalLayout_23.setObjectName(("horizontalLayout_23")) self.label_12 = QLabel(self.frame_23) self.label_12.setMinimumSize(QSize(170, 0)) self.label_12.setMaximumSize(QSize(180, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.label_12.setFont(font) self.label_12.setObjectName(("label_12")) self.horizontalLayout_23.addWidget(self.label_12) self.txtBearing = QLineEdit(self.frame_23) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtBearing.sizePolicy().hasHeightForWidth()) self.txtBearing.setSizePolicy(sizePolicy) self.txtBearing.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtBearing.setFont(font) self.txtBearing.setObjectName(("txtBearing")) self.horizontalLayout_23.addWidget(self.txtBearing) self.btnCaptureBearing = QToolButton(self.frame_23) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnCaptureBearing.sizePolicy().hasHeightForWidth()) self.btnCaptureBearing.setSizePolicy(sizePolicy) self.btnCaptureBearing.setMaximumSize(QSize(16777215, 25)) self.btnCaptureBearing.setStyleSheet(("")) self.btnCaptureBearing.setIcon(icon) self.btnCaptureBearing.setObjectName(("btnCaptureBearing")) self.horizontalLayout_23.addWidget(self.btnCaptureBearing) self.verticalLayout_2.addWidget(self.frame_23) self.frame_24 = QFrame(self.groupBox) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_24.sizePolicy().hasHeightForWidth()) self.frame_24.setSizePolicy(sizePolicy) self.frame_24.setFrameShape(QFrame.StyledPanel) self.frame_24.setFrameShadow(QFrame.Raised) self.frame_24.setObjectName(("frame_24")) self.horizontalLayout_24 = QHBoxLayout(self.frame_24) self.horizontalLayout_24.setSpacing(0) self.horizontalLayout_24.setMargin(0) self.horizontalLayout_24.setObjectName(("horizontalLayout_24")) self.lblDistance = QLabel(self.frame_24) self.lblDistance.setMinimumSize(QSize(170, 0)) self.lblDistance.setMaximumSize(QSize(180, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.lblDistance.setFont(font) self.lblDistance.setObjectName(("lblDistance")) self.horizontalLayout_24.addWidget(self.lblDistance) self.txtDistance = QLineEdit(self.frame_24) self.txtDistance.setEnabled(False) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txtDistance.sizePolicy().hasHeightForWidth()) self.txtDistance.setSizePolicy(sizePolicy) self.txtDistance.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) self.txtDistance.setFont(font) self.txtDistance.setObjectName(("txtDistance")) self.horizontalLayout_24.addWidget(self.txtDistance) self.btnCaptureDistance = QToolButton(self.frame_24) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnCaptureDistance.sizePolicy().hasHeightForWidth()) self.btnCaptureDistance.setSizePolicy(sizePolicy) self.btnCaptureDistance.setMaximumSize(QSize(16777215, 23)) self.btnCaptureDistance.setStyleSheet(("")) self.btnCaptureDistance.setIcon(icon) self.btnCaptureDistance.setObjectName(("btnCaptureDistance")) self.horizontalLayout_24.addWidget(self.btnCaptureDistance) self.verticalLayout_2.addWidget(self.frame_24) self.verticalLayout.addWidget(self.groupBox) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.buttonBox.setObjectName(("buttonBox")) self.verticalLayout.addWidget(self.buttonBox) self.btnCaptureDistance.clicked.connect(self.method_9) self.btnCaptureBearing.clicked.connect(self.method_8) self.txtEND_X.textChanged.connect(self.method_4) self.txtEND_Y.textChanged.connect(self.method_4) self.txtTHR_X.textChanged.connect(self.method_4) self.txtTHR_Y.textChanged.connect(self.method_4) self.type = rnavType self.category = category self.resultPosionList = position_List self.MinBearing2 = 0 self.MaxBearing2= 0 self.waypoint = None self.distanceMeasureTool = MeasureTool(define._canvas, self.txtDistance, DistanceUnits.NM) self.bearingTool = CaptureBearingTool(define._canvas, self.txtBearing) self.CaptureTHRCoordTool = CaptureCoordinateTool(define._canvas, self.txtTHR_X, self.txtTHR_Y) self.CaptureTHRCoordTool.rubberBandClick.setColor(Qt.green) self.CaptureENDCoordTool = CaptureCoordinateTool(define._canvas, self.txtEND_X, self.txtEND_Y) self.CaptureENDCoordTool.rubberBandClick.setColor(Qt.blue) if rnavType == RnavCommonWaypoint.FAWP or rnavType == RnavCommonWaypoint.MAWP: self.from1 = position_0 self.resize(326, 310) if position_List[0] != None: self.setThrPosition(position_List[0].x(),position_List[0].y()) self.CaptureTHRCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[0].x(),position_List[0].y())) # self.CaptureTHRCoordTool.rubberBandClick.show() if position_List[1] != None: self.setEndPosition(position_List[1].x(),position_List[1].y()) self.CaptureENDCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[1].x(),position_List[1].y())) # self.setWaypoint(position_List[2]) else: self.from1 = position_1 num = RnavWaypoints.smethod_0(position_0, position_1) self.MinBearing = RnavWaypoints.smethod_7(rnavType, category, num) self.MaxBearing= RnavWaypoints.smethod_8(rnavType, category, num) self.MinDistance = RnavWaypoints.smethod_4(rnavType, category) if flagStr == "Y-Bar": if (rnavType == RnavCommonWaypoint.IAWP1): self.setBearing(self.MaxBearing) elif (rnavType != RnavCommonWaypoint.IAWP3): self.setBearing(num) else: self.setBearing(self.MinBearing) else: if (rnavType == RnavCommonWaypoint.IAWP1): self.setBearing(self.MinBearing) elif (rnavType != RnavCommonWaypoint.IAWP3): self.setBearing(num) else: self.setBearing(self.MaxBearing) # if self.txtDistance.isEnabled(): # self.setDistance(RnavWaypoints.smethod_6(rnavType, category).NauticalMiles) # self.setWaypoint(position_List.pop(0)) self.method_4() self.retranslateUi() QObject.connect(self.buttonBox, SIGNAL(("accepted()")), self.btnCalculate_Click) QObject.connect(self.buttonBox, SIGNAL(("rejected()")), self.reject) # QMetaObject.connectSlotsByName(Dialog) # self.btnToolEND.clicked.connect(self.removeEnd) # self.btnToolTHR.clicked.connect(self.removeThr) self.btnCaptureRunwayTHR.clicked.connect(self.captureTHR) self.btnCaptureRunwayEND.clicked.connect(self.captureEND)
def __init__(self): super().__init__() self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH) tabs_setting = gui.tabWidget(self.controlArea) tab_bas = oasysgui.createTabPage(tabs_setting, "Basic Setting") tab_adv = oasysgui.createTabPage(tabs_setting, "Advanced Setting") lens_box = oasysgui.widgetBox(tab_bas, "Input Parameters", addSpace=False, orientation="vertical", height=600, width=450) oasysgui.lineEdit(lens_box, self, "source_plane_distance", "Source Plane Distance [cm]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "image_plane_distance", "Image Plane Distance [cm]", labelWidth=350, valueType=float, orientation="horizontal") gui.separator(lens_box) oasysgui.lineEdit(lens_box, self, "input_diameter", "Input Diameter [cm]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "angular_acceptance", "Angular Acceptance [deg]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "inner_diameter", "Central Diameter [cm]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "output_diameter", "Output Diameter [cm]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "focal_length", "Focal Length [cm]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "focus_dimension", "Approximate focus dimension [um]", labelWidth=350, valueType=float, orientation="horizontal") oasysgui.lineEdit(lens_box, self, "lens_length", "Lens Total Length [cm]", labelWidth=350, valueType=float, orientation="horizontal") gui.separator(lens_box) oasysgui.lineEdit(lens_box, self, "transmittance", "Lens Transmittance [%]", labelWidth=350, valueType=float, orientation="horizontal") gui.separator(self.controlArea, height=80) button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Run Shadow/trace", callback=self.traceOpticalElement) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(100)
def title_font(self): font = QFont('Seqoe UI', 8, QFont.Bold) return font
def __init__(self, parent, editable=False, spacerItemMove=False): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("ComboBoxPanel" + str(len(parent.findChildren(ComboBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) self.comboBox = QComboBox(self.frameBoxPanel) self.comboBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.comboBox.setFont(font) self.comboBox.setObjectName(self.objectName() + "_comboBox") self.comboBox.setMinimumWidth(70) # self.comboBox.setMaximumWidth(70) # self.hLayoutframeBoxPanel.addWidget(self.lineEdit) self.hLayoutframeBoxPanel.addWidget(self.comboBox) self.imageButton = QToolButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) if not spacerItemMove: spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutBoxPanel.addItem(spacerItem) self.comboBox.currentIndexChanged.connect(self.comboBoxChanged) # self.comboBox.editTextChanged.connect(self.comboBoxEditTextChanged) self.imageButton.clicked.connect(self.imageButtonClicked) self.captionUnits = "" self.hasObject = False self.objectList = [] if editable == True: self.lineEdit = QLineEdit(self.frameBoxPanel) self.lineEdit.setObjectName("lineEdit") self.hLayoutframeBoxPanel.insertWidget(1, self.lineEdit) self.comboBox.setLineEdit(self.lineEdit) self.lineEdit.returnPressed.connect(self.comboBoxEditTextChanged)
def populate_classified_values( unassigned_values, assigned_values, default_classes, list_unique_values, tree_mapping_widget): """Populate lstUniqueValues and treeClasses.from the parameters. :param unassigned_values: List of values that haven't been assigned to a class. It will be put in list_unique_values. :type unassigned_values: list :param assigned_values: Dictionary with class as the key and list of value as the value of the dictionary. It will be put in tree_mapping_widget. :type assigned_values: dict :param default_classes: Default classes from unit. :type default_classes: list :param list_unique_values: List Widget for unique values :type list_unique_values: QListWidget :param tree_mapping_widget: Tree Widget for classifying. :type tree_mapping_widget: QTreeWidget """ # Populate the unique values list list_unique_values.clear() list_unique_values.setSelectionMode( QAbstractItemView.ExtendedSelection) for value in unassigned_values: value_as_string = value is not None and unicode(value) or 'NULL' list_item = QListWidgetItem(list_unique_values) list_item.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) list_item.setData(Qt.UserRole, value) list_item.setText(value_as_string) list_unique_values.addItem(list_item) # Populate assigned values tree tree_mapping_widget.clear() bold_font = QFont() bold_font.setItalic(True) bold_font.setBold(True) bold_font.setWeight(75) tree_mapping_widget.invisibleRootItem().setFlags( Qt.ItemIsEnabled) for default_class in default_classes: # Create branch for class tree_branch = QTreeWidgetItem(tree_mapping_widget) tree_branch.setFlags( Qt.ItemIsDropEnabled | Qt.ItemIsEnabled) tree_branch.setExpanded(True) tree_branch.setFont(0, bold_font) if 'name' in default_class: default_class_name = default_class['name'] else: default_class_name = default_class['key'] tree_branch.setText(0, default_class_name) tree_branch.setData(0, Qt.UserRole, default_class['key']) if 'description' in default_class: tree_branch.setToolTip(0, default_class['description']) # Assign known values for value in assigned_values[default_class['key']]: string_value = value is not None and unicode(value) or 'NULL' tree_leaf = QTreeWidgetItem(tree_branch) tree_leaf.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) tree_leaf.setData(0, Qt.UserRole, value) tree_leaf.setText(0, string_value)
def setComposerTemplates(self, comptecommunal): ''' Set parameters for given comptecommunal ''' # List of templates comptecommunalAbrev = comptecommunal[9:] self.composerTemplates = { 'header1': { 'names': ['annee', 'ccodep', 'ccodir', 'ccocom', 'libcom'], 'position': [3.5, 2.5, 145, 7.5], 'align': [128, 4], 'keepContent': True, 'type': 'sql', 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND comptecommunal = '%s'" % comptecommunal }, 'sticky': True }, 'header2': { 'names': ['type'], 'position': [153.5, 2.5, 60, 7.5], 'align': [128, 4], 'keepContent': True, 'type': 'properties', 'source': [self.typeLabel], 'sticky': True }, 'header3': { 'names': ['comptecommunal'], 'position': [218.5, 2.5, 75, 7.5], 'align': [128, 2], 'keepContent': True, 'type': 'properties', 'source': [comptecommunalAbrev], 'sticky': True }, 'proprietaires': { 'names': ['lines'], 'position': [3.5, 10, 290, 40], 'align': [32, 1], 'keepContent': False, 'type': 'parent', 'source': 'proprietaires_line' }, 'proprietes_baties': { 'names': ['lines'], 'position': [3.5, 50, 290, 65], 'align': [32, 1], 'keepContent': False, 'type': 'parent', 'source': 'proprietes_baties_line' }, 'proprietes_baties_sum': { 'names': [ 'revenucadastral', 'co_vlbaia', 'co_bipevla', 'gp_vlbaia', 'gp_bipevla', 'de_vlbaia', 'de_bipevla', 're_vlbaia', 're_bipevla' ], 'position': [3.5, 115, 290, 15], 'align': [32, 1], 'type': 'sql', 'keepContent': True, 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND l10.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle } }, 'proprietes_non_baties': { 'names': ['lines'], 'position': [3.5, 130, 290, 65], 'align': [32, 1], 'keepContent': False, 'type': 'parent', 'source': 'proprietes_non_baties_line' }, 'proprietes_non_baties_sum': { 'names': [ 'sum_ha_contenance', 'sum_a_contenance', 'sum_ca_contenance', 'sum_drcsuba' ], 'position': [3.5, 195, 290, 13], 'align': [32, 1], 'type': 'sql', 'keepContent': True, 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND p.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle }, 'bgcolor': Qt.transparent }, 'footer': { 'names': ['foot'], 'position': [3.5, 208, 288, 4], 'align': [128, 4], 'keepContent': True, 'type': 'properties', 'source': [ u"Ce document est donné à titre indicatif - Il n'a pas de valeur légale" ], 'bgcolor': Qt.white, 'htmlState': 0, 'font': QFont('sans-serif', 4, 1, True), 'sticky': True } } self.mainTables = { 'proprietaires_line': { 'names': ['mainprop', 'epousede', 'adrprop', 'nele'], 'type': 'sql', 'keepContent': True, 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND comptecommunal = '%s'" % comptecommunal } }, 'proprietes_baties_line': { 'names': [ 'section', 'ndeplan', 'ndevoirie', 'adresse', 'coderivoli', 'bat', 'ent', 'niv', 'ndeporte', 'numeroinvar', 'star', 'meval', 'af', 'natloc', 'cat', 'revenucadastral', 'coll', 'natexo', 'anret', 'andeb', 'fractionrcexo', 'pourcentageexo', 'txom', 'coefreduc' ], 'type': 'sql', 'filter': 'comptecommunal', 'and': { 'proprietaire': u" AND l10.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle } }, 'proprietes_non_baties_line': { 'names': [ 'section', 'ndeplan', 'ndevoirie', 'adresse', 'coderivoli', 'nparcprim', 'fpdp', 'star', 'suf', 'grssgr', 'cl', 'natcult', 'ha_contenance', 'a_contenance', 'ca_contenance', 'revenucadastral', 'coll', 'natexo', 'anret', 'fractionrcexo', 'pourcentageexo', 'tc', 'lff' ], 'type': 'sql', 'and': { 'proprietaire': u" AND p.comptecommunal = '%s'" % comptecommunal, 'parcelle': u" AND p.parcelle = '%s'" % self.geo_parcelle } } } # items for which to count number of lines self.lineCount = { 'proprietes_baties_line': { 'count': 0, 'data': None }, 'proprietes_non_baties_line': { 'count': 0, 'data': None } } # items for which not the run a query for each page # but only once and keep content for next pages self.contentKeeped = {} for key, item in self.composerTemplates.items(): if item.has_key('keepContent') and item['keepContent']: self.contentKeeped[key] = '' for key, item in self.mainTables.items(): if item.has_key('keepContent') and item['keepContent']: self.contentKeeped[key] = ''
def __init__(self, parent=None): super(ShellOutputScintilla,self).__init__(parent) self.parent = parent self.shell = self.parent.shell self.settings = QSettings() # Creates layout for message bar self.layout = QGridLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # messageBar instance self.infoBar = QgsMessageBar() sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # Enable non-ascii chars for editor self.setUtf8(True) sys.stdout = writeOut(self, sys.stdout) sys.stderr = writeOut(self, sys.stderr, "_traceback") self.insertInitText() self.refreshSettingsOutput() self.setReadOnly(True) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers self.setMarginWidth(0, 0) self.setMarginWidth(1, 0) self.setMarginWidth(2, 0) #fm = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(1, "00000") self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor("#3E3EE3")) self.setMarginsBackgroundColor(QColor("#f9f9f9")) self.setCaretLineVisible(True) self.setCaretWidth(0) self.setMinimumHeight(120) self.setWrapMode(QsciScintilla.WrapCharacter) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self) self.runScut.setContext(Qt.WidgetShortcut) self.runScut.activated.connect(self.enteredSelected) # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view self.copyShortcut = QShortcut(QKeySequence.Copy, self) self.copyShortcut.activated.connect(self.copy) self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self) self.selectAllShortcut.activated.connect(self.selectAll)
def update_font(basefont, weight=None, italic=None, underline=None, pixelSize=None, pointSize=None): """ Return a copy of `basefont` :class:`QFont` with updated properties. """ font = QFont(basefont) if weight is not None: font.setWeight(weight) if italic is not None: font.setItalic(italic) if underline is not None: font.setUnderline(underline) if pixelSize is not None: font.setPixelSize(pixelSize) if pointSize is not None: font.setPointSize(pointSize) return font
class hexView(QGraphicsView): def __init__(self, parent): QGraphicsView.__init__(self) self.init(parent) self.initShape() def init(self, parent): self.whex = parent self.bdiff = self.whex.bdiff #Init scene self.scene = QGraphicsScene() self.setScene(self.scene) #Get bdiff stuff self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setAlignment(Qt.AlignLeft) def setItems(self): self.scene.addItem(self.whex.offsetitem) self.scene.addItem(self.whex.hexitem) self.scene.addItem(self.whex.asciitem) def initShape(self): self.initHeads() #Line decoration offsetLine = QGraphicsLineItem(QLineF(90, 0, 90, 700)) asciiLine = QGraphicsLineItem(QLineF(480, 0, 480, 700)) #Add to scene self.scene.addItem(offsetLine) self.scene.addItem(asciiLine) def initHeads(self): self.offHead = QGraphicsTextItem() self.hexHead = QGraphicsTextItem() self.asciiHead = QGraphicsTextItem() #Set Color self.offHead.setDefaultTextColor(QColor(Qt.red)) self.hexHead.setDefaultTextColor(QColor(Qt.black)) self.asciiHead.setDefaultTextColor(QColor(Qt.darkCyan)) #Create Font self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(14) #Set Font self.offHead.setFont(self.font) self.hexHead.setFont(self.font) self.asciiHead.setFont(self.font) #Set Text self.offHead.setPlainText("Offset") self.hexHead.setPlainText( "0 1 2 3 4 5 6 7 8 9 A B C D E F") self.asciiHead.setPlainText("Ascii") #Position self.offHead.setPos(20, 0) self.hexHead.setPos(95, 0) self.asciiHead.setPos(520, 0) #Add to scene self.scene.addItem(self.offHead) self.scene.addItem(self.hexHead) self.scene.addItem(self.asciiHead) headLine = QGraphicsLineItem(QLineF(0, 20, 615, 20)) self.scene.addItem(headLine) def setSyncView(self, whexview): self.whexviewsync = whexview def move(self, step, way): #step: line = 1 * bytesPerLine, page = pagesize, wheel = 3 * bytesPerLine offset = self.bdiff.currentOffset # print offset if way == 0: #UP if (offset - (step * self.bdiff.bytesPerLine)) >= 0: self.bdiff.readOffset(offset - (step * self.bdiff.bytesPerLine)) if self.bdiff.scrollbar.isLFMOD(): self.bdiff.scrollbar.setValue( self.bdiff.scrollbar.offsetToValue( offset - (step * self.bdiff.bytesPerLine))) else: self.bdiff.scrollbar.setValue( self.bdiff.scrollbar.value() - step) else: self.bdiff.readOffset(0) self.bdiff.scrollbar.setValue(0) elif way == 1: #Down if (offset + (step * self.bdiff.bytesPerLine)) <= ( self.bdiff.masterFileSize - (step * self.bdiff.bytesPerLine)): self.bdiff.readOffset(offset + (step * self.bdiff.bytesPerLine)) if self.bdiff.scrollbar.isLFMOD(): self.bdiff.scrollbar.setValue( self.bdiff.scrollbar.offsetToValue( offset + (step * self.bdiff.bytesPerLine))) else: self.bdiff.scrollbar.setValue( self.bdiff.scrollbar.value() + step) else: self.bdiff.readOffset(self.bdiff.masterFileSize - 5 * (self.bdiff.bytesPerLine)) self.bdiff.scrollbar.setValue(self.bdiff.scrollbar.max) #################################### # Navigation Operations # #################################### def wheelEvent(self, event): offset = self.bdiff.currentOffset if event.delta() > 0: self.move(3, 0) self.whexviewsync.move(3, 0) else: self.move(3, 1) self.whexviewsync.move(3, 1) def keyPressEvent(self, keyEvent): off = self.bdiff.currentOffset if keyEvent.matches(QKeySequence.MoveToNextPage): self.move(self.bdiff.pageSize / self.bdiff.bytesPerLine, 1) self.whexviewsync.move( self.bdiff.pageSize / self.bdiff.bytesPerLine, 1) elif keyEvent.matches(QKeySequence.MoveToPreviousPage): self.move(self.bdiff.pageSize / self.bdiff.bytesPerLine, 0) self.whexviewsync.move( self.bdiff.pageSize / self.bdiff.bytesPerLine, 0) elif keyEvent.matches(QKeySequence.MoveToNextLine): self.move(1, 1) self.whexviewsync.move(1, 1) elif keyEvent.matches(QKeySequence.MoveToPreviousLine): self.move(1, 0) self.whexviewsync.move(1, 0)
def _init_ui(self): # Styles self.setStyleSheet("""QRadioButton { max-width: 40px; }""") bold_font = QFont() bold_font.setBold(True) title_label = QLabel(self) title_label.setText("PyPass3") title_label.move(10, 0) title_label.setMinimumSize(300, 20) title_label.setFont(bold_font) length_label = QLabel(self) length_label.setText("Length") length_label.move(192, 185) length_label.setMinimumSize(200, 20) length_label.setFont(bold_font) main_label = QLabel(self) main_label.setText("Make robust secrets with random characters,\n" "words, or numbers. Or choose number of dice\n" "and rolls for words type passphrase. Defaults\n" "to 5 dice and 5 rolls.\n") main_label.setMinimumSize(280, 100) main_label.move(10, 15) type_label = QLabel(self) type_label.setText("Secret type") type_label.move(10, 87) type_label.setFont(bold_font) dice_label = QLabel(self) dice_label.setText("Number of dice") dice_label.move(10, 138) dice_label.setMinimumSize(280, 20) dice_label.setFont(bold_font) rolls_label = QLabel(self) rolls_label.setText("Number of rolls") rolls_label.move(10, 190) rolls_label.setMinimumSize(280, 20) rolls_label.setFont(bold_font) self.textbox = QTextEdit(self) self.textbox.setMinimumSize(280, 100) self.textbox.move(10, 245) self.textbox.setFontFamily("Courier New") self.length_textline = QLineEdit(self) self.length_textline.setMinimumSize(100, 20) self.length_textline.move(190, 210) min_width = 125 # max_width = 150 # Add Generate button generate_btn = QPushButton('Generate', self) generate_btn.setToolTip('Click to generate secret') # generate_btn.clicked.connect(on_click) generate_btn.clicked.connect(self._on_click) generate_btn.move(10, 355) generate_btn.setMinimumWidth(min_width) # Add Quit button quit_btn = QPushButton('Quit', self) quit_btn.setToolTip('Quit this application') quit_btn.clicked.connect(exit) quit_btn.move(165, 355) quit_btn.setMinimumWidth(min_width) # Add Copy button copy_btn = QPushButton('Copy', self) copy_btn.setToolTip('Copy your secret') copy_btn.clicked.connect(self._copy_textbox) copy_btn.move(250, 320) copy_btn.setMaximumWidth(35) copy_btn.setMaximumHeight(20) copy_btn.setStyleSheet('font-size: 11px;') # Add Help button help_btn = QPushButton('Help', self) help_btn.setToolTip('Get help about this application') help_btn.clicked.connect(self._open_help) help_btn.move(240, 80) help_btn.setMaximumWidth(35) help_btn.setMaximumHeight(20) help_btn.setStyleSheet('font-size: 11px;') hr1 = QFrame(self) hr1.setFrameShape(QFrame.HLine) hr1.move(10, 125) hr1.setMinimumWidth(280) hr1.setStyleSheet("color: #d0d0d0;") hr2 = QFrame(self) hr2.setFrameShape(QFrame.HLine) hr2.move(10, 175) hr2.setMinimumWidth(100) hr2.setStyleSheet("color: #d0d0d0;") # Add secret type radio buttons self.words_radio_btn = QRadioButton('words', self) self.words_radio_btn.move(10, 110) self.words_radio_btn.clicked.connect(self._set_word_defaults) self.words_radio_btn.setStyleSheet('max-width: 80px;') self.mixed_radio_btn = QRadioButton('mixed', self) self.mixed_radio_btn.move(90, 110) self.mixed_radio_btn.clicked.connect(self._disabled_unused) self.mixed_radio_btn.setStyleSheet('max-width: 80px;') self.numbers_radio_btn = QRadioButton('numbers', self) self.numbers_radio_btn.move(170, 110) self.numbers_radio_btn.clicked.connect(self._disabled_unused) self.numbers_radio_btn.setStyleSheet('max-width: 100px;') # Add dice roll radio buttons self.num_dice4 = QRadioButton('4', self) self.num_dice4.move(10, 160) self.num_dice5 = QRadioButton('5', self) self.num_dice5.move(60, 160) self.num_rolls3 = QRadioButton('3', self) self.num_rolls3.move(10, 212) self.num_rolls4 = QRadioButton('4', self) self.num_rolls4.move(60, 212) self.num_rolls5 = QRadioButton('5', self) self.num_rolls5.move(110, 212) self.radio_type_group = QButtonGroup(self) self.radio_type_group.addButton(self.words_radio_btn) self.radio_type_group.addButton(self.mixed_radio_btn) self.radio_type_group.addButton(self.numbers_radio_btn) self.radio_dice_group = QButtonGroup(self) self.radio_dice_group.addButton(self.num_dice4) self.radio_dice_group.addButton(self.num_dice5) self.radio_rolls_group = QButtonGroup(self) self.radio_rolls_group.addButton(self.num_rolls3) self.radio_rolls_group.addButton(self.num_rolls4) self.radio_rolls_group.addButton(self.num_rolls5) self.setGeometry(100, 100, 300, 400) self.setWindowTitle('Password Generator') self.setWindowIcon(QIcon('../images/lock_icon_bkgrd.png'))
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) self.initLexer() self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setWrapMode(QsciScintilla.WrapWord) self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor(QColor('#2e3436')) self.setSelectionBackgroundColor(QColor('#babdb6')) # Show line numbers self.setMarginWidth(1, '000') self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor('#2e3436')) self.setMarginsBackgroundColor(QColor('#babdb6')) # Highlight current line self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor('#d3d7cf')) # Folding self.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf')) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor('#eeeeec')) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) # Autocomletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) # Load font from Python console settings settings = QSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', 10)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) self.defaultFont.setStretch(QFont.SemiCondensed) self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0) self.defaultFont.setBold(False) self.boldFont = QFont(self.defaultFont) self.boldFont.setBold(True) self.italicFont = QFont(self.defaultFont) self.italicFont.setItalic(True) self.setFont(self.defaultFont) self.setMarginsFont(self.defaultFont)
def setLexers(self): self.lexer = QsciLexerPython() loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace") fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int) font = QFont(loadFont) font.setFixedPitch(True) font.setPointSize(fontSize) font.setStyleHint(QFont.TypeWriter) font.setStretch(QFont.SemiCondensed) font.setLetterSpacing(QFont.PercentageSpacing, 87.0) font.setBold(False) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1) self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5) self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8) self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9) self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15) self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12) self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4) self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3) self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6) self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7) self.lexer.setColor(QColor(Qt.red), 14) self.lexer.setFont(font, 1) self.lexer.setFont(font, 2) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) for style in range(0, 33): paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white))) self.lexer.setPaper(paperColor, style) self.setLexer(self.lexer)
def __init__(self, parent=None): QWidget.__init__(self, parent) icon = QIcon() icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.resize(400, 400) self.mainLayout = QVBoxLayout() self.setLayout(self.mainLayout) boldFont = QFont() boldFont.setBold(True) # Control bar self.controlRow = QHBoxLayout() self.mainLayout.addLayout(self.controlRow) self.standbyIcon = QIcon.fromTheme("system-shutdown") recordFallbackIcon = QIcon(":/multimedia/record.png") self.recordIcon = QIcon.fromTheme("media-record", recordFallbackIcon) stopFallbackIcon = QIcon(":/multimedia/stop.png") self.stopIcon = QIcon.fromTheme("media-playback-stop", stopFallbackIcon) self.pauseIcon = QIcon.fromTheme("media-playback-pause") self.resumeIcon = QIcon.fromTheme("media-playback-start") self.headphoneIcon = QIcon() self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"), QIcon.Normal, QIcon.Off) self.standbyPushButton = QPushButton("Standby") self.standbyPushButton.setToolTip("Standby") self.standbyPushButton.setMinimumSize(QSize(0, 40)) self.standbyPushButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.standbyPushButton.setIcon(self.standbyIcon) self.standbyPushButton.setCheckable(True) self.standbyPushButton.setObjectName("standbyButton") self.controlRow.addWidget(self.standbyPushButton) self.recordPushButton = QPushButton("Record") self.recordPushButton.setToolTip("Record") self.recordPushButton.setMinimumSize(QSize(0, 40)) self.recordPushButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.recordPushButton.setIcon(self.recordIcon) self.recordPushButton.setHidden(True) self.recordPushButton.setEnabled(False) self.recordPushButton.setCheckable(True) self.recordPushButton.setObjectName("recordButton") self.controlRow.addWidget(self.recordPushButton) self.connect(self.recordPushButton, SIGNAL("toggled(bool)"), self.setRecordIcon) self.pauseToolButton = QToolButton() self.pauseToolButton.setText("Pause") self.pauseToolButton.setToolTip("Pause") self.pauseToolButton.setIcon(self.pauseIcon) self.pauseToolButton.setMinimumSize(QSize(40, 40)) self.pauseToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.pauseToolButton.setHidden(True) self.pauseToolButton.setEnabled(False) self.pauseToolButton.setCheckable(True) self.controlRow.addWidget(self.pauseToolButton) self.connect(self.pauseToolButton, SIGNAL("toggled(bool)"), self.setPauseIcon) playbackIcon = QIcon.fromTheme("video-x-generic") self.playPushButton = QPushButton() self.playPushButton.setText("Play Video") self.playPushButton.setToolTip("Play last recorded Video") self.playPushButton.setIcon(playbackIcon) self.playPushButton.setMinimumSize(QSize(40, 40)) self.playPushButton.setMaximumSize(QSize(120, 40)) self.playPushButton.setHidden(True) self.playPushButton.setEnabled(False) self.playPushButton.setCheckable(True) self.controlRow.addWidget(self.playPushButton) # Filter bar self.filterBarLayout = QVBoxLayout() self.mainLayout.addLayout(self.filterBarLayout) self.filterBarLayoutRow_1 = QHBoxLayout() self.filterBarLayout.addLayout(self.filterBarLayoutRow_1) self.eventLabel = QLabel("Event") self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.eventComboBox = QComboBox() self.eventLabel.setBuddy(self.eventComboBox) self.roomLabel = QLabel("Room") self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.roomComboBox = QComboBox() self.roomLabel.setBuddy(self.roomComboBox) self.dateLabel = QLabel("Date") self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.dateComboBox = QComboBox() self.dateLabel.setBuddy(self.dateComboBox) self.filterBarLayoutRow_1.addWidget(self.eventLabel) self.filterBarLayoutRow_1.addWidget(self.eventComboBox) self.filterBarLayoutRow_1.addWidget(self.roomLabel) self.filterBarLayoutRow_1.addWidget(self.roomComboBox) self.filterBarLayoutRow_1.addWidget(self.dateLabel) self.filterBarLayoutRow_1.addWidget(self.dateComboBox) self.filterBarLayoutRow_2 = QHBoxLayout() self.filterBarLayout.addLayout(self.filterBarLayoutRow_2) self.talkLabel = QLabel("Talk ") self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.talkComboBox = QComboBox() self.talkComboBox.setFont(boldFont) self.talkComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum) self.talkComboBox.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLength) self.filterBarLayoutRow_2.addWidget(self.talkLabel) self.filterBarLayoutRow_2.addWidget(self.talkComboBox) # Preview Layout self.previewLayout = QHBoxLayout() self.mainLayout.addLayout(self.previewLayout) self.previewWidget = QWidget() self.audioSlider = QSlider() self.audioSlider.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.audioSlider.setEnabled(False) self.previewLayout.addWidget(self.previewWidget) self.previewLayout.addWidget(self.audioSlider) self.statusLabel = QLabel() self.mainLayout.addWidget(self.statusLabel) # Audio Feedback Checkbox self.audioFeedbackCheckbox = QCheckBox() self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft) self.audioFeedbackCheckbox.setIcon(self.headphoneIcon) self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback") self.mainLayout.addWidget(self.audioFeedbackCheckbox)
def _get_font_from_string(self, font): if (font.isEmpty()): return QFont("Monospace", 11) listFont = font.remove(' ').split(',') return QFont(listFont[0], listFont[1].toInt()[0])
def showDialog(self): font = QFont() result, checkState = KFontDialog.getFont(font) if result == QDialog.Accepted: self.fontLabel.setFont(font)
class ScriptEdit(QsciScintilla): LEXER_PYTHON = 0 LEXER_R = 1 def __init__(self, parent=None): QsciScintilla.__init__(self, parent) self.lexer = None self.api = None self.lexerType = -1 self.setCommonOptions() self.initShortcuts() def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) self.initLexer() self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setWrapMode(QsciScintilla.WrapWord) self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor(QColor('#2e3436')) self.setSelectionBackgroundColor(QColor('#babdb6')) # Show line numbers self.setMarginWidth(1, '000') self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor('#2e3436')) self.setMarginsBackgroundColor(QColor('#babdb6')) # Highlight current line self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor('#d3d7cf')) # Folding self.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf')) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor('#eeeeec')) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) # Autocomletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) # Load font from Python console settings settings = QSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', 10)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) self.defaultFont.setStretch(QFont.SemiCondensed) self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0) self.defaultFont.setBold(False) self.boldFont = QFont(self.defaultFont) self.boldFont.setBold(True) self.italicFont = QFont(self.defaultFont) self.italicFont.setItalic(True) self.setFont(self.defaultFont) self.setMarginsFont(self.defaultFont) def initShortcuts(self): (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16) # Disable some shortcuts self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl) #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl) #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl) # Use Ctrl+Space for autocompletion self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.shortcutAutocomplete.setContext(Qt.WidgetShortcut) self.shortcutAutocomplete.activated.connect(self.autoComplete) def autoComplete(self): self.autoCompleteFromAll() def setLexerType(self, lexerType): self.lexerType = lexerType self.initLexer() def initLexer(self): if self.lexerType == self.LEXER_PYTHON: self.lexer = QsciLexerPython() colorDefault = QColor('#2e3436') colorComment = QColor('#c00') colorCommentBlock = QColor('#3465a4') colorNumber = QColor('#4e9a06') colorType = QColor('#4e9a06') colorKeyword = QColor('#204a87') colorString = QColor('#ce5c00') self.lexer.setDefaultFont(self.defaultFont) self.lexer.setDefaultColor(colorDefault) self.lexer.setColor(colorComment, 1) self.lexer.setColor(colorNumber, 2) self.lexer.setColor(colorString, 3) self.lexer.setColor(colorString, 4) self.lexer.setColor(colorKeyword, 5) self.lexer.setColor(colorString, 6) self.lexer.setColor(colorString, 7) self.lexer.setColor(colorType, 8) self.lexer.setColor(colorCommentBlock, 12) self.lexer.setColor(colorString, 15) self.lexer.setFont(self.italicFont, 1) self.lexer.setFont(self.boldFont, 5) self.lexer.setFont(self.boldFont, 8) self.lexer.setFont(self.italicFont, 12) self.api = QsciAPIs(self.lexer) settings = QSettings() useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) elif self.lexerType == self.LEXER_R: # R lexer self.lexer = LexerR() self.setLexer(self.lexer)
def setConnectionWindow(self): # Draw the connection windows and set window Icon self.resize(700, 500) self.setWindowTitle('Naopy') self.setWindowIcon( QtGui.QIcon('C:/Users/zeyu/Desktop/NaoGUI/image/Icon.png')) # Set background for connection window connectBG_image = QtGui.QPixmap() connectBG_image.load( 'C:/Users/zeyu/Desktop/NaoGUI/image/connectBG.png') connectBG = QtGui.QPalette() connectBG.setBrush(self.backgroundRole(), QtGui.QBrush(connectBG_image)) self.setPalette(connectBG) self.setAutoFillBackground(True) # Draw the label and input widget for user to enter IP and Port number self.Title = QtGui.QLabel("Welcome to Connect Nao's World!", self) self.Title.move(150, 90) self.Title.setFont(QFont("Consolas", 18)) self.labelIP = QtGui.QLabel("Robot IP", self) self.labelIP.move(180, 150) self.labelIP.setFont(QFont("Consolas", 12)) self.labelPORT = QtGui.QLabel("Robot PORT", self) self.labelPORT.move(180, 200) self.labelPORT.setFont(QFont("Consolas", 12)) self.inputIP = QtGui.QPlainTextEdit(self) self.inputIP.resize(200, 30) self.inputIP.move(300, 145) self.inputIP.setFont(QFont("Consolas", 12)) self.inputPORT = QtGui.QPlainTextEdit(self) self.inputPORT.resize(200, 30) self.inputPORT.move(300, 195) self.inputPORT.setFont(QFont("Consolas", 12)) # Draw the button for the connection winsow, contains conect and enter mainmenu # Connect button will check the robot IP and Port, show the user valid result self.connect_button = QtGui.QPushButton("Connect", self) self.connect_button.resize(100, 40) self.connect_button.move(300, 240) self.connect_button.setFont(QFont("Consolas", 12)) self.enter_button = QtGui.QPushButton("Enter MainMenu", self) self.enter_button.resize(150, 40) self.enter_button.move(300, 320) self.enter_button.setFont(QFont("Consolas", 12)) self.enter_button.setDisabled(True) self.invalidlabel = QtGui.QLabel("", self) self.invalidlabel.setFont(QFont("Consolas", 12)) self.invalidlabel.move(200, 285) self.invalidlabel.resize(300, 30) pe = QtGui.QPalette() pe.setColor(QtGui.QPalette.WindowText, Qt.red) self.invalidlabel.setPalette(pe) self.validlabel = QtGui.QLabel("", self) self.validlabel.setFont(QFont("Consolas", 12)) self.validlabel.move(200, 285) self.validlabel.resize(400, 30) pe1 = QtGui.QPalette() pe1.setColor(QtGui.QPalette.WindowText, Qt.black) self.validlabel.setPalette(pe1) self.connect(self.connect_button, QtCore.SIGNAL('clicked()'), self.check_Connect) self.connect(self.enter_button, QtCore.SIGNAL('clicked()'), self.showMainMenu)
import decimal from decimal import Decimal from PyQt4 import QtGui from PyQt4.QtGui import QFont, QHBoxLayout, QFrame, QLineEdit from PyQt4 import QtCore import config RawRole = QtCore.Qt.UserRole + 1 """DataRole that is considered "raw" / "non-human-readable." For example, the hex data of a human-readable script. """ monospace_font = QFont('Monospace') monospace_font.setPointSize(9) monospace_font.setStyleHint(QFont.TypeWriter) script_file_filter = 'Coinscripts (*.coinscript);;Text files (*.txt);;All files (*.*)' def HBox(*widgets): """Create an HBoxLayout with the widgets passed.""" hbox = QHBoxLayout() for w in widgets: hbox.addWidget(w) return hbox def floated_buttons(btns, left=False):
def def_pref(prm): prm["pref"] = {} prm["pref"]["general"] = {} #prm["pref"]["phones"] = {} prm["pref"]["sound"] = {} prm["pref"]["email"] = {} prm["pref"]["exp"] = {} prm["pref"]["interface"] = {} prm["pref"]["resp_box"] = {} prm["pref"]["appearance"] = {} prm["pref"]["general"]["triggerONOFF"] = False prm["pref"]["general"]["ONTrigger"] = 254 prm["pref"]["general"]["OFFTrigger"] = 253 prm["pref"]["general"]["triggerDur"] = 1 prm["pref"]["general"]["defaultISI"] = "500" prm["pref"]["general"]["preTrialSilence"] = "200" prm["pref"]["general"]["responseLightDuration"] = "500" prm["pref"]["general"]["maxRecursionDepth"] = sys.getrecursionlimit() prm["pref"]["general"]["startupCommand"] = "" prm["pref"]["general"]["showBlockProgBar"] = True prm["pref"]["general"]["endMessageFiles"] = [] prm["pref"]["general"]["endMessageFilesID"] = [] prm["pref"]["general"]["endMessageFilesUse"] = [] prm["pref"]["general"]["endMessageLevels"] = [] prm["pref"]["general"]["defaultShuffle"] = QApplication.translate( "", "Ask", "") prm["pref"]["general"]["defaultResponseMode"] = QApplication.translate( "", "Real Listener", "") prm["pref"]["general"]["listenerNameWarn"] = True prm["pref"]["general"]["sessionLabelWarn"] = True prm["pref"]["general"]["playEndMessage"] = False prm["pref"]["general"]["processResultsEnd"] = True prm["pref"]["interface"]["responseButtonSize"] = 20 prm['pref']["general"]['resFileFormat'] = 'fixed' prm['pref']["general"]['resFileFixedString'] = 'test.txt' prm['pref']["general"]["csvSeparator"] = ';' prm['pref']["general"]["fullFileSuffix"] = '_trial' prm['pref']["general"]["sessSummResFileSuffix"] = '_sess' prm['pref']["general"]["resTableFileSuffix"] = '_table' prm['pref']["general"]["automaticFileExtension"] = True prm["pref"]["general"]["nBlocksCustomCommand"] = "" prm["pref"]["general"]["atEndCustomCommand"] = "" prm["pref"]["general"]["dprimeCorrection"] = True prm["pref"]["general"]["precision"] = 12 # 'variable' prm["pref"]["email"]["notifyEnd"] = False prm["pref"]["email"]["nBlocksNotify"] = 1 prm["pref"]["email"]['sendData'] = False prm["pref"]["email"]['SMTPServer'] = 'localhost' prm["pref"]["email"]['SMTPServerPort'] = 25 prm["pref"]["email"]['SMTPServerSecurity'] = "TLS/SSL (a)" prm["pref"]["email"]["serverRequiresAuthentication"] = True prm["pref"]["email"]['fromUsername'] = '' if sys.version_info[0] == 2: #with python2.x there are problems here passwd = "" encoded_passwd = "" elif sys.version_info[0] == 3: passwd = bytes('default', 'utf-8') encoded_passwd = base64.b64encode(passwd) encoded_passwd = str(encoded_passwd, "utf-8") prm["pref"]["email"]['fromPassword'] = encoded_passwd prm['pref']['language'] = QApplication.translate("", "en", "") prm['pref']['country'] = QApplication.translate("", "US", "") prm['pref']['responseBoxLanguage'] = QApplication.translate("", "en", "") prm['pref']['responseBoxCountry'] = QApplication.translate("", "US", "") #Appearance #prm["pref"]["appearance"]["style"] = QApplication.translate("","Default","") #Sound preferences prm["pref"]["sound"]["defaultNBits"] = "32" prm["pref"]["sound"]["defaultSampleRate"] = "48000" prm["pref"]["sound"]["writewav"] = True prm["pref"]["sound"]["writeSndSeqSegments"] = False prm["pref"]["sound"]["wavmanager"] = "scipy" prm["pref"]["sound"]["bufferSize"] = 1024 prm["pref"]["sound"]["appendSilence"] = 0 if platform.system() == 'Windows': prm["pref"]["sound"]["playCommand"] = "winsound" prm["pref"]["sound"]["playCommandType"] = "winsound" elif platform.system() == 'Darwin': prm["pref"]["sound"]["playCommand"] = "afplay" prm["pref"]["sound"]["playCommandType"] = QApplication.translate( "", "custom", "") else: prm["pref"]["sound"]["playCommand"] = "aplay" prm["pref"]["sound"]["playCommandType"] = QApplication.translate( "", "custom", "") if alsaaudioAvailable == True: prm["pref"]["sound"]["alsaaudioDevice"] = "default" if pyaudioAvailable == True: prm["pref"]["sound"]["pyaudioDevice"] = 0 prm["pref"]["resp_box"]["responseBoxButtonFont"] = QFont( 'Sans Serif', 24, QFont.Bold, False).toString() prm["pref"]["resp_box"]["correctLightColor"] = QColor(0, 255, 0) prm["pref"]["resp_box"]["incorrectLightColor"] = QColor(255, 0, 0) prm["pref"]["resp_box"]["neutralLightColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["offLightColor"] = QColor(0, 0, 0) prm["pref"]["resp_box"]["responseLightFont"] = QFont( 'Sans Serif', 20, QFont.Bold, False).toString() prm["pref"]["resp_box"][ "correctTextFeedback"] = "CORRECT" #QApplication.translate("","Yes","") #self.tr("CORRECT") prm["pref"]["resp_box"]["incorrectTextFeedback"] = "INCORRECT" prm["pref"]["resp_box"]["neutralTextFeedback"] = "DONE" prm["pref"]["resp_box"]["offTextFeedback"] = "" prm["pref"]["resp_box"]["correctTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["incorrectTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["neutralTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["offTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["correctTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["incorrectTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["neutralTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["offTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["userSetCorrectTextFeedback"] = "" prm["pref"]["resp_box"]["userSetIncorrectTextFeedback"] = "" prm["pref"]["resp_box"]["userSetNeutralTextFeedback"] = "" prm["pref"]["resp_box"]["userSetOffTextFeedback"] = "" #PHONES prm["phones"] = {} prm["phones"]["phonesChoices"] = ["Phones 1", "Phones 2"] prm["phones"]["phonesMaxLevel"] = [100, 100] prm["phones"]["phonesID"] = ['0', '1'] prm["phones"]["defaultPhones"] = ["\u2713", "\u2012"] #EXPERIMENTERS prm["experimenter"] = {} prm["experimenter"]["defaultExperimenter"] = ["\u2713", "\u2012"] prm["experimenter"]["experimenter_id"] = [ "Experimenter 1", "Experimenter 2" ] prm["experimenter"]["experimenter_name"] = ["", ""] prm["experimenter"]["experimenter_surname"] = ["", ""] prm["experimenter"]["experimenter_email"] = ["", ""] prm["experimenter"]["experimenter_address"] = ["", ""] prm["experimenter"]["experimenter_address2"] = ["", ""] prm["experimenter"]["experimenter_telephone"] = ["", ""] prm["experimenter"]["experimenter_mobile"] = ["", ""] prm["warningInterval"] = False prm["preTrialInterval"] = False prm["precursorInterval"] = False prm["postcursorInterval"] = False prm["intervalLights"] = QApplication.translate("", "Yes", "") return prm
def __init__(self, parent=None): super(MikiHighlighter, self).__init__(parent) baseFontSize = 12 NUM = 16 self.patterns = [] regexp = [0] * NUM font = [0] * NUM color = [0] * NUM color_settings = Mikibook.highlighterColors() # 0: html tags - <pre></pre> # less naive html regex regexp[ 0] = r'</?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?>' font[0] = QFont("monospace", baseFontSize, -1) color[0] = QColor(color_settings[0]) # 1: h1 - # regexp[1] = '^#[^#]+' color[1] = QColor(color_settings[1]) font[1] = QFont("decorative", 2 * baseFontSize, QFont.Bold) # 2: h2 - ## regexp[2] = '^##[^#]+' color[2] = QColor(color_settings[2]) font[2] = QFont("serif", 5.0 / 3 * baseFontSize, QFont.Bold) # 3: h3 - ### regexp[3] = '^###[^#]+' color[3] = QColor(color_settings[3]) font[3] = QFont("serif", 4.0 / 3 * baseFontSize, QFont.Bold) # 4: h4 and more - #### regexp[4] = '^####.+' color[4] = QColor(color_settings[4]) font[4] = QFont("serif", baseFontSize, QFont.Bold) # 5: html symbols - > regexp[5] = '&[^; ].+;' color[5] = QColor(color_settings[5]) font[5] = QFont("monospace", baseFontSize, -1) # 6: html comments - <!-- --> regexp[6] = '<!--.+-->' color[6] = QColor(color_settings[6]) font[6] = QFont(None, baseFontSize, -1) # 7: delete - ~~delete~~ regexp[7] = DEL_RE color[7] = QColor(color_settings[7]) font[7] = QFont(None, baseFontSize, -1) # 8: insert - __insert__ regexp[8] = INS_RE font[8] = QFont(None, baseFontSize, -1) font[8].setUnderline(True) # 9: strong - **strong** regexp[9] = STRONG_RE color[9] = QColor(color_settings[9]) font[9] = QFont(None, baseFontSize, QFont.Bold) # 10: emphasis - //emphasis// regexp[10] = EMPH_RE color[10] = QColor(color_settings[10]) font[10] = QFont(None, baseFontSize, -1, True) # 11: links - (links) after [] or links after []: regexp[11] = (r'(?<=(\]\())[^\(\)]*(?=\))|' '(<https?://[^>]+>)|' '(<[^ >]+@[^ >]+>)') font[11] = QFont(None, baseFontSize, -1, True) font[11].setUnderline(True) #.setUnderlineColor("#204A87") # 12: link/image references - [] or ![] regexp[12] = r'!?\[[^\[\]]*\]' color[12] = QColor(color_settings[12]) font[12] = QFont(None, baseFontSize, -1) # 13: blockquotes and lists - > or - or * or 0. regexp[ 13] = r'(^>+)|(^(?: |\t)*[0-9]+\. )|(^(?: |\t)*- )|(^(?: |\t)*\* )' color[13] = QColor(color_settings[13]) font[13] = QFont(None, baseFontSize, -1) # 14: fence - ``` or ~~~ regexp[14] = '^(?:~{3,}|`{3,}).*$' color[14] = QColor(color_settings[14]) font[14] = QFont(None, baseFontSize, QFont.Bold) # 15: math - $$ regexp[15] = r'^(?:\${2}).*$' color[15] = QColor(color_settings[15]) font[15] = QFont(None, baseFontSize, QFont.Bold) for i in range(NUM): p = re.compile(regexp[i]) f = QTextCharFormat() if font[i] != 0: f.setFont(font[i]) if color[i] != 0: f.setForeground(color[i]) self.patterns.append((p, f)) self.speller = parent.speller fenced_font = QFont("monospace", baseFontSize, -1) self.fenced_block = re.compile("^(?:~{3,}|`{3,}).*$") self.fenced_format = QTextCharFormat() self.fenced_format.setFont(fenced_font) math_font = QFont("monospace", baseFontSize, -1) self.math_block = re.compile(r"^(?:\${2}).*$") self.math_format = QTextCharFormat() self.math_format.setFont(math_font) self.settext_h1 = re.compile('^=+$') self.settext_h2 = re.compile('^-+$')
def createWidgets (self): """ Create qt widgets """ # prepare menu self.toolbar = QToolBar(self) self.toolbar.setStyleSheet("QToolBar { border: 0px }") # remove 3D border self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.toolbarPlugins = QToolBar(self) self.toolbarPlugins.setStyleSheet("QToolBar { border: 0px }") # remove 3D border self.toolbarPlugins.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.pluginsBox = QGroupBox("Plugins") self.pluginsBox.setStyleSheet( """ QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } QGroupBox::title { subcontrol-position: bottom center;} """ ) layoutPlugins = QHBoxLayout() layoutPlugins.addWidget(self.toolbarPlugins) layoutPlugins.setContentsMargins(0,0,0,0) self.pluginsBox.setLayout(layoutPlugins) self.pluginsBox.hide() self.exportBox = QGroupBox("Exports") self.exportBox.setStyleSheet( """ QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } QGroupBox::title { subcontrol-position: bottom center;} """ ) layoutExports = QHBoxLayout() layoutExports.addWidget(self.toolbar) layoutExports.setContentsMargins(0,0,0,0) self.exportBox.setLayout(layoutExports) self.exportBox.setMaximumHeight(70) layout = QVBoxLayout() if self.toXml: self.txtEdit = QtHelper.RawXmlEditor(parent=self) self.txtEdit.setText( self.__data ) # self.txtEdit.setUtf8(True) self.txtEdit.setFont( QFont("Courier", 9) ) else: self.txtEdit = QWebView(parent=self) # convert to qbyte array to support qt5 tmp_ = QByteArray() tmp_.append(self.__data) self.cacheHtml = self.__data self.txtEdit.setContent( tmp_, "text/html; charset=utf-8") layoutToolbars = QHBoxLayout() layoutToolbars.addWidget(self.exportBox) layoutToolbars.addWidget(self.pluginsBox) layoutToolbars.addStretch(1) layoutToolbars.setContentsMargins(5,0,0,0) layout.addLayout(layoutToolbars) layout.addWidget(self.txtEdit) self.setLayout(layout)
class NumberBar(QWidget): '''class that deifnes textEditor numberBar''' def __init__(self, editor): QWidget.__init__(self, editor) self.editor = editor self.editor.blockCountChanged.connect(self.updateWidth) self.editor.updateRequest.connect(self.updateContents) self.font = QFont() self.numberBarColor = QColor("#e8e8e8") def paintEvent(self, event): painter = QPainter(self) painter.fillRect(event.rect(), self.numberBarColor) block = self.editor.firstVisibleBlock() # Iterate over all visible text blocks in the document. while block.isValid(): blockNumber = block.blockNumber() block_top = self.editor.blockBoundingGeometry(block).translated(self.editor.contentOffset()).top() # Check if the position of the block is out side of the visible area. if not block.isVisible() or block_top >= event.rect().bottom(): break # We want the line number for the selected line to be bold. if blockNumber == self.editor.textCursor().blockNumber(): self.font.setBold(True) painter.setPen(QColor("#000000")) else: self.font.setBold(False) painter.setPen(QColor("#717171")) painter.setFont(self.font) # Draw the line number right justified at the position of the line. paint_rect = QRect(0, block_top, self.width(), self.editor.fontMetrics().height()) painter.drawText(paint_rect, Qt.AlignRight, str(blockNumber + 1)) block = block.next() painter.end() QWidget.paintEvent(self, event) def getWidth(self): count = self.editor.blockCount() width = self.fontMetrics().width(str(count)) + 10 return width def updateWidth(self): width = self.getWidth() if self.width() != width: self.setFixedWidth(width) self.editor.setViewportMargins(width, 0, 0, 0) def updateContents(self, rect, scroll): if scroll: self.scroll(0, scroll) else: self.update(0, rect.y(), self.width(), rect.height()) if rect.contains(self.editor.viewport().rect()): fontSize = self.editor.currentCharFormat().font().pointSize() self.font.setPointSize(fontSize) self.font.setStyle(QFont.StyleNormal) self.updateWidth()
def restoreSettings(self): settings = QSettings() self.spinBox.setValue( settings.value("pythonConsole/fontsize", 10, type=int)) self.spinBoxEditor.setValue( settings.value("pythonConsole/fontsizeEditor", 10, type=int)) self.fontComboBox.setCurrentFont( QFont(settings.value("pythonConsole/fontfamilytext", "Monospace"))) self.fontComboBoxEditor.setCurrentFont( QFont( settings.value("pythonConsole/fontfamilytextEditor", "Monospace"))) self.preloadAPI.setChecked( settings.value("pythonConsole/preloadAPI", True, type=bool)) self.lineEdit.setText( settings.value("pythonConsole/preparedAPIFile", "", type=str)) itemTable = settings.value("pythonConsole/userAPI", []) if itemTable: self.tableWidget.setRowCount(0) for i in range(len(itemTable)): self.tableWidget.insertRow(i) self.tableWidget.setColumnCount(2) pathSplit = itemTable[i].split("/") apiName = pathSplit[-1][0:-4] self.tableWidget.setItem(i, 0, QTableWidgetItem(apiName)) self.tableWidget.setItem(i, 1, QTableWidgetItem(itemTable[i])) self.autoSaveScript.setChecked( settings.value("pythonConsole/autoSaveScript", False, type=bool)) self.autoCompThreshold.setValue( settings.value("pythonConsole/autoCompThreshold", 2, type=int)) self.autoCompThresholdEditor.setValue( settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int)) self.groupBoxAutoCompletionEditor.setChecked( settings.value("pythonConsole/autoCompleteEnabledEditor", True, type=bool)) self.groupBoxAutoCompletion.setChecked( settings.value("pythonConsole/autoCompleteEnabled", True, type=bool)) self.enableObjectInspector.setChecked( settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.autoCloseBracketEditor.setChecked( settings.value("pythonConsole/autoCloseBracketEditor", False, type=bool)) self.autoCloseBracket.setChecked( settings.value("pythonConsole/autoCloseBracket", False, type=bool)) self.autoInsertionImportEditor.setChecked( settings.value("pythonConsole/autoInsertionImportEditor", True, type=bool)) self.autoInsertionImport.setChecked( settings.value("pythonConsole/autoInsertionImport", True, type=bool)) if settings.value("pythonConsole/autoCompleteSource") == 'fromDoc': self.autoCompFromDoc.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromAPI': self.autoCompFromAPI.setChecked(True) elif settings.value( "pythonConsole/autoCompleteSource") == 'fromDocAPI': self.autoCompFromDocAPI.setChecked(True) if settings.value( "pythonConsole/autoCompleteSourceEditor") == 'fromDoc': self.autoCompFromDocEditor.setChecked(True) elif settings.value( "pythonConsole/autoCompleteSourceEditor") == 'fromAPI': self.autoCompFromAPIEditor.setChecked(True) elif settings.value( "pythonConsole/autoCompleteSourceEditor") == 'fromDocAPI': self.autoCompFromDocAPIEditor.setChecked(True) ## Setting font lexer color self.defaultFontColor.setColor( QColor( settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.defaultFontColorEditor.setColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(Qt.black)))) self.keywordFontColor.setColor( QColor( settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen)))) self.keywordFontColorEditor.setColor( QColor( settings.value("pythonConsole/keywordFontColorEditor", QColor(Qt.darkGreen)))) self.classFontColor.setColor( QColor( settings.value("pythonConsole/classFontColor", QColor(Qt.blue)))) self.classFontColorEditor.setColor( QColor( settings.value("pythonConsole/classFontColorEditor", QColor(Qt.blue)))) self.methodFontColor.setColor( QColor( settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray)))) self.methodFontColorEditor.setColor( QColor( settings.value("pythonConsole/methodFontColorEditor", QColor(Qt.darkGray)))) self.decorFontColor.setColor( QColor( settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue)))) self.decorFontColorEditor.setColor( QColor( settings.value("pythonConsole/decorFontColorEditor", QColor(Qt.darkBlue)))) self.commentFontColor.setColor( QColor( settings.value("pythonConsole/commentFontColor", QColor(Qt.gray)))) self.commentFontColorEditor.setColor( QColor( settings.value("pythonConsole/commentFontColorEditor", QColor(Qt.gray)))) self.commentBlockFontColor.setColor( QColor( settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray)))) self.commentBlockFontColorEditor.setColor( QColor( settings.value("pythonConsole/commentBlockFontColorEditor", QColor(Qt.gray)))) self.paperBackgroundColor.setColor( QColor( settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))) self.paperBackgroundColorEditor.setColor( QColor( settings.value("pythonConsole/paperBackgroundColorEditor", QColor(Qt.white)))) self.caretLineColor.setColor( QColor( settings.value("pythonConsole/caretLineColor", QColor("#fcf3ed")))) self.caretLineColorEditor.setColor( QColor( settings.value("pythonConsole/caretLineColorEditor", QColor("#fcf3ed")))) self.cursorColor.setColor( QColor( settings.value("pythonConsole/cursorColor", QColor(Qt.black)))) self.cursorColorEditor.setColor( QColor( settings.value("pythonConsole/cursorColorEditor", QColor(Qt.black)))) self.stderrFontColor.setColor( QColor( settings.value("pythonConsole/stderrFontColor", QColor(Qt.red)))) self.singleQuoteFontColor.setColor( settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))) self.singleQuoteFontColorEditor.setColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(Qt.blue))) self.doubleQuoteFontColor.setColor( settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))) self.doubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(Qt.blue))) self.tripleSingleQuoteFontColor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))) self.tripleSingleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColorEditor", QColor(Qt.blue))) self.tripleDoubleQuoteFontColor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))) self.tripleDoubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(Qt.blue)))
# -*- coding: utf-8 -*- import os, sys import os.path as osp from PyQt4.QtGui import QLabel, QIcon, QPixmap, QFont, QFontDatabase # Local import from utils.userconfig import UserConfig, get_home_dir DATA_DEV_PATH = osp.dirname(__file__) DATA_PATH = DATA_DEV_PATH SANS_SERIF = [ 'Sans Serif', 'DejaVu Sans', 'Bitstream Vera Sans', 'Bitstream Charter', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', 'sans-serif' ] SANS_SERIF.insert(0, unicode(QFont().family())) MONOSPACE = [ 'Monospace', 'DejaVu Sans Mono', 'Courier New', 'Bitstream Vera Sans Mono', 'Andale Mono', 'Liberation Mono', 'Monaco', 'Courier', 'monospace', 'Fixed', 'Terminal' ] MEDIUM = 11 SMALL = 9 App_Name = 'Creator' DEFAULTS = [ ('main', { 'translation': True, 'window/size': (800, 600),
def composer(self, setData, flag=True): paperWidth = setData["Width"] paperHeight = setData["Height"] mapRenderer = define._canvas.mapRenderer() # comp = None comp = QgsComposition(mapRenderer) comp.setPlotStyle(QgsComposition.Print) comp.setPaperSize(paperWidth, paperHeight) # rectangleAll = QgsComposerShape(comp) # rectangleAll.setItemPosition(3, 3, paperWidth - 3, paperHeight - 3) # rectangleAll.setShapeType(1) # comp.addItem(rectangleAll) self.txt1 = QgsComposerLabel(comp) self.txt1.setItemPosition(20, 20) self.txt1.setFrameEnabled(False) font = QFont("Arial", 10) self.txt1.setFont(font) self.txt1.setText(setData["TextData"][0]) self.txt1.adjustSizeToText() comp.addItem(self.txt1) self.txt2 = QgsComposerLabel(comp) self.txt2.setItemPosition(int(paperWidth / 2) + 10, 20) self.txt2.setFrameEnabled(False) font = QFont("Arial", 10) self.txt2.setFont(font) self.txt2.setText(setData["TextData"][1]) self.txt2.adjustSizeToText() comp.addItem(self.txt2) self.txt3 = QgsComposerLabel(comp) self.txt3.setItemPosition(paperWidth - 40, 20) self.txt3.setFrameEnabled(False) font = QFont("Arial", 10) self.txt3.setFont(font) self.txt3.setText(setData["TextData"][2]) self.txt3.adjustSizeToText() comp.addItem(self.txt3) w = int((paperWidth - 40) / 4) self.txt4 = QgsComposerLabel(comp) self.txt4.setItemPosition(20, 35) self.txt4.setFrameEnabled(False) font = QFont("Arial", 10) self.txt4.setFont(font) self.txt4.setText(setData["TextData"][3]) self.txt4.adjustSizeToText() comp.addItem(self.txt4) self.txt5 = QgsComposerLabel(comp) self.txt5.setItemPosition(20 + w, 35) self.txt5.setFrameEnabled(False) font = QFont("Arial", 10) self.txt5.setFont(font) self.txt5.setText(setData["TextData"][4]) self.txt5.adjustSizeToText() comp.addItem(self.txt5) self.txt6 = QgsComposerLabel(comp) self.txt6.setItemPosition(20 + w * 2, 35) self.txt6.setFrameEnabled(False) font = QFont("Arial", 10) self.txt6.setFont(font) self.txt6.setText(setData["TextData"][5]) self.txt6.adjustSizeToText() comp.addItem(self.txt6) self.txt7 = QgsComposerLabel(comp) self.txt7.setItemPosition(20 + w * 3, 35) self.txt7.setFrameEnabled(False) font = QFont("Arial", 10) self.txt7.setFont(font) self.txt7.setText(setData["TextData"][6]) self.txt7.adjustSizeToText() comp.addItem(self.txt7) # if flag: x, y = 20, 45 composerMap = QgsComposerMap(comp, x, y, paperWidth - 40, 150) # composerMap.setPreviewMode(QgsComposerMap.Render) # composerMap.setGridEnabled(False) #rect = composerMap.currentMapExtent () renderer = composerMap.mapRenderer() newExtent = renderer.extent() #Make sure the width/height ratio is the same as in current composer map extent. #This is to keep the map item frame and the page layout fixed currentMapExtent = composerMap.currentMapExtent() currentWidthHeightRatio = currentMapExtent.width( ) / currentMapExtent.height() newWidthHeightRatio = newExtent.width() / newExtent.height() if currentWidthHeightRatio < newWidthHeightRatio: #enlarge height of new extent, ensuring the map center stays the same newHeight = newExtent.width() / currentWidthHeightRatio deltaHeight = newHeight - newExtent.height() newExtent.setYMinimum(newExtent.yMinimum() - deltaHeight / 2) newExtent.setYMaximum(newExtent.yMaximum() + deltaHeight / 2) else: #enlarge width of new extent, ensuring the map center stays the same newWidth = currentWidthHeightRatio * newExtent.height() deltaWidth = newWidth - newExtent.width() newExtent.setXMinimum(newExtent.xMinimum() - deltaWidth / 2) newExtent.setXMaximum(newExtent.xMaximum() + deltaWidth / 2) composerMap.beginCommand("Map extent changed") composerMap.setNewExtent(newExtent) composerMap.endCommand() # composerMap.setNewScale(3500) composerMap.setFrameEnabled(True) composerMap.setFrameOutlineWidth(1.0) composerMap.setPreviewMode(QgsComposerMap.Render) composerMap.updateCachedImage() composerMap.setGridEnabled(True) composerMap.setGridPenColor(QColor(255, 255, 255, 0)) composerMap.setGridPenWidth(0.0) #composerMap.setGridStyle(QgsComposerMap.FrameAnnotationsOnly) composerMap.setGridIntervalX(1.0) composerMap.setGridIntervalY(1.0) # mySymbol1 = composerMap.gridLineSymbol () # mySymbol1.setAlpha(0) #composerMap.setGridLineSymbol(mySymbol1) composerMap.setShowGridAnnotation(True) composerMap.setGridAnnotationFormat(1) composerMap.setGridAnnotationPrecision(0) composerMap.setGridAnnotationDirection(1, 0) composerMap.setGridAnnotationDirection(1, 1) comp.addItem(composerMap) w = int((paperWidth - 40) / 3) self.txt8 = QgsComposerLabel(comp) self.txt8.setItemPosition(20, 225) self.txt8.setFrameEnabled(False) font = QFont("Arial", 10) self.txt8.setFont(font) self.txt8.setText(setData["TextData"][7]) self.txt8.adjustSizeToText() comp.addItem(self.txt8) self.txt9 = QgsComposerLabel(comp) self.txt9.setItemPosition(20 + w, 225) self.txt9.setFrameEnabled(False) font = QFont("Arial", 10) self.txt9.setFont(font) self.txt9.setText(setData["TextData"][8]) self.txt9.adjustSizeToText() comp.addItem(self.txt9) self.txt10 = QgsComposerLabel(comp) self.txt10.setItemPosition(20 + w * 2, 225) self.txt10.setFrameEnabled(False) font = QFont("Arial", 10) self.txt10.setFont(font) self.txt10.setText(setData["TextData"][9]) self.txt10.adjustSizeToText() comp.addItem(self.txt10) # profileRect = QgsComposerPicture(comp) # profileRect.setItemPosition(20, 200, paperWidth - 40, 50) # comp.addItem(profileRect) self.txt11 = QgsComposerLabel(comp) self.txt11.setItemPosition(20, paperHeight - 30) self.txt11.setFrameEnabled(False) font = QFont("Arial", 10) self.txt11.setFont(font) self.txt11.setText(setData["TextData"][10]) self.txt11.adjustSizeToText() comp.addItem(self.txt11) self.txt12 = QgsComposerLabel(comp) self.txt12.setItemPosition(20 + w, paperHeight - 30) self.txt12.setFrameEnabled(False) font = QFont("Arial", 10) self.txt12.setFont(font) self.txt12.setText(setData["TextData"][11]) self.txt12.adjustSizeToText() comp.addItem(self.txt12) self.txt13 = QgsComposerLabel(comp) self.txt13.setItemPosition(20 + w * 2, paperHeight - 30) self.txt13.setFrameEnabled(False) font = QFont("Arial", 10) self.txt13.setFont(font) self.txt13.setText(setData["TextData"][12]) self.txt13.adjustSizeToText() comp.addItem(self.txt13) # gpw = QGraphicsProxyWidget() self.tblView = QTableView() tableHeight = None tableWidth = None if self.tableChangedValue == None: self.tblView.setFixedWidth(paperWidth - 40) tableHeight = 50 tableWidth = paperWidth - 40 self.tblView.setFixedHeight(tableHeight) else: self.tblView.setFixedWidth(self.tableChangedValue["Width"]) self.tblView.setFixedHeight(self.tableChangedValue["Height"]) tableHeight = self.tableChangedValue["Height"] tableWidth = self.tableChangedValue["Width"] self.tblView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.tblView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) hHeder = self.tblView.horizontalHeader() hHeder.setVisible(False) vHeder = self.tblView.verticalHeader() vHeder.setVisible(False) # if flag: self.stdModel = QStandardItemModel() self.data.__setitem__("TableWidth", tableWidth) self.data.__setitem__("TableHeight", tableHeight) self.setTableView(self.tblView, self.stdModel, self.data) self.calcALT() self.calcTimeRate() self.gpw = QGraphicsProxyWidget() self.gpw.setWidget(self.tblView) # gpw.setWidget(tblView) if self.tableChangedValue == None: self.gpw.setPos(20, 210) font = QFont() font.setPixelSize(2) self.gpw.setFont(font) else: self.gpw.setPos(self.tableChangedValue["X"], self.tableChangedValue["Y"]) font = QFont() font.setPixelSize(self.tableChangedValue["FontSize"]) self.gpw.setFont(font) # tblView.setFrameRect(QRect(20, 210, paperWidth - 40, 50)) comp.addItem(self.gpw) self.connect(self.stdModel, SIGNAL("itemChanged(QStandardItem *)"), self.stdModel_itemChanged) return comp
def __init__(self, *args): QPlainTextEdit.__init__(self, *args) # toPlainText() takes a lot of time on long texts, therefore it is cached self._cachedText = None self._eol = self._DEFAULT_EOL self._indenter = Indenter(self) self.lineLengthEdge = None self.lineLengthEdgeColor = Qt.red self._atomicModificationDepth = 0 self.drawIncorrectIndentation = True self.drawAnyWhitespace = False self._rectangularSelection = RectangularSelection(self) """Sometimes color themes will be supported. Now black on white is hardcoded in the highlighters. Hardcode same palette for not highlighted text """ palette = self.palette() palette.setColor(QPalette.Base, QColor('#ffffff')) palette.setColor(QPalette.Text, QColor('#000000')) self.setPalette(palette) self._highlighter = None self._bracketHighlighter = BracketHighlighter() self._lines = Lines(self) self.completionThreshold = self._DEFAULT_COMPLETION_THRESHOLD self.completionEnabled = self._DEFAULT_COMPLETION_ENABLED self._completer = Completer(self) self._initActions() self._lineNumberArea = qutepart.sideareas.LineNumberArea(self) self._countCache = (-1, -1) self._markArea = qutepart.sideareas.MarkArea(self) self._bookmarks = qutepart.bookmarks.Bookmarks(self, self._markArea) self._userExtraSelections = [ ] # we draw bracket highlighting, current line and extra selections by user self._userExtraSelectionFormat = QTextCharFormat() self._userExtraSelectionFormat.setBackground(QBrush(QColor('#ffee00'))) self._lintMarks = {} self.blockCountChanged.connect(self._updateLineNumberAreaWidth) self.updateRequest.connect(self._updateSideAreas) self.cursorPositionChanged.connect(self._updateExtraSelections) self.textChanged.connect(self._dropUserExtraSelections) self.textChanged.connect(self._resetCachedText) self.textChanged.connect(self._clearLintMarks) fontFamilies = {'Windows': 'Courier New', 'Darwin': 'Menlo'} fontFamily = fontFamilies.get(platform.system(), 'Monospace') self.setFont(QFont(fontFamily)) self._updateLineNumberAreaWidth(0) self._updateExtraSelections()
def look_and_feel(app, font=None, adjust_width=None, adjust_height=None, default=None): """ Look and feel. Arguments: app - QApplication. font - User provided font size (default None) adjust_width - User provided width adjustment (default None) adjust_height - User provided height adjustment (default None) default - Default values (default None) Return: Style sheet """ if font is not None: font = float(font) else: font = float(default[0][0]['Font'][0]) if adjust_width is not None: adjust_width = float(adjust_width) else: adjust_width = float(default[0][1]['Width adjustment'][0]) if adjust_height is not None: adjust_height = float(adjust_height) else: adjust_height = float(default[0][2]['Height adjustment'][0]) start_button_width = float(default[0][3]['Start button'][0]) notification_edit_width = float(default[0][4]['Notification edit'][0]) notification_check_width = float(default[0][5]['Notification check'][0]) notification_button_width = float(default[0][6]['Notification button'][0]) mount_button_width = float(default[0][7]['Mount button'][0]) frame_entry_width = float(default[0][8]['Frame entry'][0]) frame_button_width = float(default[0][9]['Frame button'][0]) frame_label_width = float(default[0][10]['Frame label'][0]) setting_widget_width = float(default[0][11]['Setting widget'][0]) status_name_width = float(default[0][12]['Status name'][0]) status_info_width = float(default[0][13]['Status info'][0]) status_quota_width = float(default[0][14]['Status quota'][0]) widget_height = float(default[0][15]['Widget height'][0]) app.setFont(QFont('Verdana', font)) start_button_width = '{0}px'.format(font * start_button_width * adjust_width) notification_edit_width = '{0}px'.format(font * notification_edit_width * adjust_width) notification_check_width = '{0}px'.format(font * notification_check_width * adjust_width) notification_button_width = '{0}px'.format(font * notification_button_width * adjust_width) mount_button_width = '{0}px'.format(font * mount_button_width * adjust_width) frame_entry_width = '{0}px'.format(font * frame_entry_width * adjust_width) frame_button_width = '{0}px'.format(font * frame_button_width * adjust_width) frame_label_width = '{0}px'.format(font * frame_label_width * adjust_width) setting_widget_width = '{0}px'.format(font * setting_widget_width * adjust_width) status_name_width = '{0}px'.format(font * status_name_width * adjust_width) status_info_width = '{0}px'.format(font * status_info_width * adjust_width) status_quota_width = '{0}px'.format(font * status_quota_width * adjust_width) widget_height = '{0}px'.format(font * widget_height * adjust_height) # Style sheet style_widgets = """ QWidget#central {{ background-color: qradialgradient( cx:0, cy:0, fx:0, fy:0, radius:1.2, stop:0 lightgrey, stop:0.8 lightgrey, stop:0.94 white, stop:1 white ) }} QWidget#tab {{ background-color: {0}}} QWidget {{ background-color: {0}}} QTabBar {{ background-color: {0}}} QTabBar::tab {{ min-width: 120px }} """.format('lightgrey') button_style = """ QPushButton {{ min-height: {5}}} QPushButton {{ background-color: qradialgradient( cx:0.5, cy:0.5, fx:0.5, fy:0.5, radius:1, stop:0 white, stop:1 pink ); border-width: 1px; border-style: inset; padding: 1px; border-radius: 5px }} QPushButton:pressed {{ background-color: qradialgradient( cx:0.5, cy:0.5, fx:0.5, fy:0.5, radius:1, stop:0 white, stop:1 pink ); border-width: 1px; border-style: outset; padding: 1px; border-radius: 5px }} QPushButton#button {{ min-width: {0}; max-width: {0} }} QPushButton#frame {{ max-width: {1}; min-width: {1} }} QPushButton#button_entry {{ max-width: {2}; min-width: {2} }} QPushButton#mount {{ max-width: {3}; min-width: {3} }} QPushButton#notification {{ max-width: {4}; min-width: {4} }} """.format( start_button_width, frame_label_width, frame_button_width, mount_button_width, notification_button_width, widget_height ) label_style = """ QLabel#picture {{ background-color: transparent }} QLabel#status_name {{ max-width: {3}; min-width: {1}; background-color: {0}; min-height: {5}; max-height: {5} }} QLabel#status_info {{ max-width: {3}; min-width: {2}; background-color: {0}; min-height: {5}; max-height: {5} }} QLabel#status_quota {{ max-width: {3}; min-width: {3}; background-color: {0}; min-height: {5}; max-height: {5} }} QLabel#setting {{ max-width: {4}; min-width: {4}; background-color: {0}; min-height: {5}; max-height: {5} }} """.format( 'transparent', status_name_width, status_info_width, status_quota_width, setting_widget_width, widget_height ) edit_style = """ QLineEdit {{ max-height: {7}; min-height: {7}; background-color: white }} QLineEdit#default_settings {{ min-width: {1}; max-width: 9999; background-color: white }} QLineEdit:disabled {{ background-color: {6} }} QLineEdit#setting:enabled {{ max-width: {1}; min-width: {1}; background-color: {0}; min-height: {7}; max-height: {7} }} QLineEdit#noti_edit:enabled {{ max-width: {2}; min-width: {2}; background-color: {5}; min-height: {7}; max-height: {7} }} QLineEdit#frame:enabled {{ max-width: {3}; min-width: {3}; background-color: {0}; min-height: {7}; max-height: {7} }} QLineEdit#entry:enabled {{ max-width: {4}; min-width: {4}; background-color: {0}; min-height: {7}; max-height: {7} }} """.format( 'white', setting_widget_width, notification_edit_width, frame_label_width, frame_entry_width, 'rgba(102,205,170,20)', 'rgba(205,102,170,20)', widget_height ) #'rgba(102,205,170,100)', check_style = """ QCheckBox {{ min-height: {1}; max-height: {1}; background-color: white }} QCheckBox#noti_check {{ max-width: {0}; min-width: {0}; background-color: white }} """.format(notification_check_width, widget_height) combo_style = """ QComboBox {{ min-width: {4}; max-width: {4}; min-height: {3}; max-height: {3}; background-color: white }} QComboBox QAbstractItemView {{ background-color: white; selection-color: black; selection-background-color: lightgray }} QComboBox#default_settings {{ min-width: {1}; max-width: 9999; background-color: white }} QComboBox:disabled {{ background-color: {2} }} QComboBox#noti_edit:enabled {{ max-width: {1}; min-width: {1}; background-color: {0} }} """.format( 'rgba(102,205,170,20)', notification_edit_width, 'rgba(195,152,180,20)', widget_height, setting_widget_width ) style = '\n'.join([style_widgets, button_style, label_style, edit_style, check_style, combo_style]) return style
def cb_connected(self, connected_reason): if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT: while True: try: self.ipcon.enumerate() break except Error as e: self.error_msg.showMessage('Enumerate Error: ' + str(e.description)) time.sleep(1) if __name__ == "__main__": argv = sys.argv if sys.platform == 'win32': argv += ['-style', 'windowsxp'] if sys.platform == 'darwin': # fix macOS 10.9 font # http://successfulsoftware.net/2013/10/23/fixing-qt-4-for-mac-os-x-10-9-mavericks/ # https://bugreports.qt-project.org/browse/QTBUG-32789 QFont.insertSubstitution('.Lucida Grande UI', 'Lucida Grande') # fix macOS 10.10 font # https://bugreports.qt-project.org/browse/QTBUG-40833 QFont.insertSubstitution('.Helvetica Neue DeskInterface', 'Helvetica Neue') sys.exit(WeatherStation(argv).exec_())