Python PyQt5.QtGui 模块,QFont() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtGui.QFont()。
def fontValuepixmap(font):
f = QFont(font)
img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied)
img.fill(0)
p = QPainter(img)
p.setRenderHint(QPainter.TextAntialiasing, True)
p.setRenderHint(QPainter.Antialiasing, True)
f.setPointSize(13)
p.setFont(f)
t = QTextOption()
t.setAlignment(Qt.AlignCenter)
p.drawText(QRectF(0, 0, 16), 'A', t)
p.end()
return Qpixmap.fromImage(img)
def __init__(self, parent=None):
super(self.__class__, self).__init__()
self.parent = parent
font = QFont()
font.setPointSize(16)
model = QStringListModel()
model.setStringList(wordlist)
completer = Completer()
completer.setModel(model)
self.setFont(font)
self.setCompleter(completer)
self.setAlignment(Qt.AlignCenter)
#self.setPlaceholderText("Enter invite code")
def __initUI(self):
"""Initialize the UI"""
self.__layout = QtWidgets.QVBoxLayout()
self.__console = QtWidgets.QTextEdit(self)
self.__console.setFont(QtGui.QFont("Ubuntu Mono"))
self.__console.setMinimumWidth(400)
self.__console.setMinimumHeight(100)
self.__console.setReadOnly(True)
self.__layout.addWidget(self.__console)
self.setLayout(self.__layout)
with open(Resources.consoleStyle, "r") as CSS:
self.__console.setStyleSheet(CSS.read())
# Connect Signals
self.readStdout.connect(self.printToConsole)
def data(self, index, role=Qt.displayRole):
row = index.row()
if row >= len(self.message_type):
return
label = self.message_type[row]
if role == Qt.displayRole:
return label.name
elif role == Qt.CheckStateRole:
return label.show
elif role == Qt.BackgroundColorRole:
return constants.LABEL_COLORS[label.color_index]
elif role == Qt.FontRole:
font = QFont()
font.setItalic(label.field_type is None)
return font
def initUI(self):
"""
Initialize the MarqueeLabel layout.
"""
self.setFixedSize(433, 40)
self.font = QFont("Arial", GEOMETRY[b3.getPlatform()]['MARQUEE_LABEL_FONT_SIZE'])
self.font.setItalic(True)
self.setFont(self.font)
self.setStyleSheet("""
QLabel {
background: transparent;
color: #484848;
}
""")
self.setVisible(B3App.Instance().settings.value('show_RSS_news', type=bool))
def setupUi(self, topicslist):
topicslist.setobjectName("topicslist")
topicslist.resize(642, 730)
self.verticalLayout = QtWidgets.QVBoxLayout(topicslist)
self.verticalLayout.setobjectName("verticalLayout")
self.label = QtWidgets.QLabel(topicslist)
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setobjectName("label")
self.verticalLayout.addWidget(self.label)
self.filterText = QtWidgets.QLineEdit(topicslist)
self.filterText.setobjectName("filterText")
self.verticalLayout.addWidget(self.filterText)
self.listWidget = QtWidgets.QListView(topicslist)
self.listWidget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.listWidget.setobjectName("listWidget")
self.verticalLayout.addWidget(self.listWidget)
self.retranslateUi(topicslist)
QtCore.QMetaObject.connectSlotsByName(topicslist)
def setupUi(self, Dialog):
Dialog.setobjectName("Dialog")
Dialog.resize(540, 393)
self.gridLayout = QtWidgets.qgridLayout(Dialog)
self.gridLayout.setobjectName("gridLayout")
self.label = QtWidgets.QLabel(Dialog)
self.label.setText("")
self.label.setpixmap(QtGui.Qpixmap(":/newPrefix/images/image3487.png"))
self.label.setobjectName("label")
self.gridLayout.addWidget(self.label, 1, 1)
self.textbrowser = QtWidgets.QTextbrowser(Dialog)
font = QtGui.QFont()
font.setFamily("Arial")
self.textbrowser.setFont(font)
self.textbrowser.setopenExternalLinks(True)
self.textbrowser.setobjectName("textbrowser")
self.gridLayout.addWidget(self.textbrowser, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def setupUi(self, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def setupUi(self, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def setupUi(self, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def __init__(self, parent):
super(HomographyScene, self).__init__(parent)
self.points = []
self.main_pixmap_item = None # Either None or a QGraphicspixmapItem representing the loaded image
# Point configuration
self.point_rad = 12 # Radius,in pixels
self.point_pen_color = QtGui.QColor(255, 74, 13, 230) # R,G,B,A
self.point_pen = QtGui.QPen(self.point_pen_color, 6)
self.point_brush_color = QtGui.QColor(195, 255, 20) # R,A
self.point_brush = QtGui.QBrush(self.point_brush_color)
self.point_selected = False
self.selected_point = None
font = QtGui.QFont()
font.setPixelSize(48)
font.setBold(True)
self.label_font = font
self.label_pen_color = QtGui.QColor(0, 0) # R,B
self.label_pen = QtGui.QPen(self.label_pen_color, 2)
self.label_brush_color = QtGui.QColor(255, 255) # R,B
self.label_brush = QtGui.QBrush(self.label_brush_color)
def setupUi(self, mainWindow):
mainWindow.setobjectName("mainWindow")
mainWindow.resize(604, 100)
mainWindow.setMinimumSize(QtCore.QSize(604, 100))
mainWindow.setMaximumSize(QtCore.QSize(604, 100))
self.lineEdit = QtWidgets.QLineEdit(mainWindow)
self.lineEdit.setGeometry(QtCore.QRect(0, 601, 101))
self.lineEdit.setMinimumSize(QtCore.QSize(601, 101))
self.lineEdit.setMaximumSize(QtCore.QSize(601, 101))
font = QtGui.QFont()
font.setPointSize(28)
self.lineEdit.setFont(font)
self.lineEdit.setobjectName("lineEdit")
self.retranslateUi(mainWindow)
QtCore.QMetaObject.connectSlotsByName(mainWindow)
def setupUi(self, Form):
Form.setobjectName("Form")
Form.resize(376, 68)
Form.setMinimumSize(QtCore.QSize(376, 68))
Form.setMaximumSize(QtCore.QSize(376, 68))
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(0, 381, 71))
self.lineEdit.setMinimumSize(QtCore.QSize(381, 71))
self.lineEdit.setMaximumSize(QtCore.QSize(381, 71))
font = QtGui.QFont()
font.setPointSize(20)
self.lineEdit.setFont(font)
self.lineEdit.setobjectName("lineEdit")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def __init__(self,
timeSpan=30.0,
yMin=-1.0,
yMax=1.0,
yOriginValue=0.0,
xTickInterval=5.0,
yTickInterval=0.2,
labelFont=QFont("Segoe UI", 10),
refreshRate=0.1,
**kwds):
# validate inputs
assert timeSpan > 0.0
self._timeSpan = timeSpan
self._lastUpdate = time.time()
self._refreshRate = refreshRate
self._refreshTimer = QTimer()
self._refreshTimer.timeout.connect(self._refresh_plots)
self._refreshTimer.start(self._refreshRate * 1000.0)
super(QPlot2DTime, self).__init__(
xMin=timeSpan,
xMax=0.0,
yMin=yMin,
yMax=yMax,
xOriginValue=0.0,
yOriginValue=yOriginValue,
xTickInterval=xTickInterval,
yTickInterval=yTickInterval,
labelFont=labelFont,
**kwds)
# P U B L I C M E T H O D S
#===========================================================================
def setupUi(self, Form):
Form.setobjectName("Form")
Form.resize(529, 329)
self.selInfoWidget = QtWidgets.QWidget(Form)
self.selInfoWidget.setGeometry(QtCore.QRect(260, 10, 264, 222))
self.selInfoWidget.setobjectName("selInfoWidget")
self.gridLayout = QtWidgets.qgridLayout(self.selInfoWidget)
self.gridLayout.setContentsMargins(0, 0)
self.gridLayout.setobjectName("gridLayout")
self.selDescLabel = QtWidgets.QLabel(self.selInfoWidget)
self.selDescLabel.setText("")
self.selDescLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.selDescLabel.setWordWrap(True)
self.selDescLabel.setobjectName("selDescLabel")
self.gridLayout.addWidget(self.selDescLabel, 1)
self.selNameLabel = QtWidgets.QLabel(self.selInfoWidget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.selNameLabel.setFont(font)
self.selNameLabel.setText("")
self.selNameLabel.setobjectName("selNameLabel")
self.gridLayout.addWidget(self.selNameLabel, 1)
self.selectedTree = DataTreeWidget(self.selInfoWidget)
self.selectedTree.setobjectName("selectedTree")
self.selectedTree.headerItem().setText(0, "1")
self.gridLayout.addWidget(self.selectedTree, 2)
self.hoverText = QtWidgets.QTextEdit(Form)
self.hoverText.setGeometry(QtCore.QRect(0, 240, 521, 81))
self.hoverText.setobjectName("hoverText")
self.view = FlowchartGraphicsView(Form)
self.view.setGeometry(QtCore.QRect(0, 256, 192))
self.view.setobjectName("view")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def default_visual(self):
# Pallete
default_palette = self.text_widget.palette()
# Background
default_background_color = QtGui.QColor()
default_background_color.setNamedColor('#2B2B2B')
default_palette.setColor(QtGui.QPalette.Base, default_background_color)
# Font Color
default_font_color = QtGui.QColor()
default_font_color.setNamedColor('#F8F8F2')
default_palette.setColor(QtGui.QPalette.Text, default_font_color)
# Font Type
default_font = QtGui.QFont('Consolas', 13)
self.text_widget.setFont(default_font)
self.text_widget.setPalette(default_palette)
def get_monospace_font():
preferred = ['Consolas', 'DejaVu Sans Mono', 'Monospace', 'Lucida Console', 'Monaco']
for name in preferred:
font = QFont(name)
if QFontInfo(font).fixedPitch():
logger.debug('Preferred monospace font: %r', font.toString())
return font
font = QFont()
font.setStyleHint(QFont().Monospace)
font.setFamily('monospace')
logger.debug('Using fallback monospace font: %r', font.toString())
return font
def onSelectFontUserInterface( self, *args ):
font = QtGui.QFont( self.ui_face, self.ui_point_size )
font, ok = QtWidgets.QFontDialog.getFont( font, self, T_('Choose font') )
if ok:
self.ui_face = font.family()
self.ui_point_size = font.pointSize()
self.ui_font_text.setText( '%s %dpt ' % (self.ui_face, self.ui_point_size) )
self.ui_font_text.setFont( font )
def onSelectFontCode( self, *args ):
font = QtGui.QFont( self.code_face, self.code_point_size )
font, T_('Choose font') )
if ok:
self.code_face = font.family()
self.code_point_size = font.pointSize()
self.code_font_text.setText( '%s %dpt ' % (self.code_face, self.code_point_size) )
self.code_font_text.setFont( font )
def __init__( self, args:List[str] ) -> None:
self.__all_singletons = {} # type: Dict[str,None]
self.__code_font = None # type: QtGui.QFont
all_factories, all_messages = wb_scm_factories.allScmFactories()
# convert to a dict
self.all_factories = dict( [(f.scmName(), f) for f in all_factories] )
extra_loggers = []
for factory in self.all_factories.values():
extra_loggers.extend( factory.extraLoggers() )
super().__init__( ('Scm', 'Workbench'), args, debug_class=wb_scm_debug.WbScmDebug, extra_loggers=extra_loggers, )
for msg in all_messages:
self.log.info( msg )
def writePreferences( self ) -> None:
super().writePreferences()
self.setAppStyles()
p = self.prefs.font_code
if p.face is None or p.point_size is None:
self.__code_font = self.font()
else:
self.__code_font = QtGui.QFont( p.face, p.point_size )
# place fix style changes in this list
def getCodeFont( self ) -> 'QtGui.QFont':
return self.__code_font
def __init__( self, app, parent, name=None ):
super().__init__( parent )
self.name = name
self.style_normal = self.STYLE_DEFAULT
self.style_line_numbers = self.STYLE_LASTPredefineD + 1
self.style_line_numbers_for_diff = self.STYLE_LASTPredefineD
self.emptyUndobuffer()
self.setMarginWidth( 0, 0 )
self.setMarginWidth( 1, 0 )
self.setMarginWidth( 2, 0 )
# make some styles
self.styleSetFromSpec( self.style_normal,
'size:%d,face:%s,fore:#000000,back:#e0e0e0' % (wb_config.point_size, wb_config.face) )
self.styleSetFromSpec( self.style_line_numbers,back:#f0f0f0' % (wb_config.point_size, wb_config.face) )
self.styleSetFromSpec( self.style_line_numbers_for_diff,back:#d0d0d0' % (wb_config.point_size, wb_config.face) )
# Calculate space for 6 digits
font = QtGui.QFont( wb_config.face, wb_config.point_size )
self.setFont( font )
fontmetrics = QtGui.QFontMetrics( font )
width = fontmetrics.width( '123456' )
self.setScrollWidth( width )
self.setMaximumWidth( width )
self.setMinimumWidth( width )
# no scroll bars on the line number control
self.setVScrollBar( False )
self.setHScrollBar( False )
def setupUi(self, Dialog):
Dialog.setobjectName("Dialog")
Dialog.resize(491, 81)
self.gridLayout = QtWidgets.qgridLayout(Dialog)
self.gridLayout.setobjectName("gridLayout")
self.label = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(13)
self.label.setFont(font)
self.label.setobjectName("label")
self.gridLayout.addWidget(self.label, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def __init__(self):
super().__init__()
self.setGeometry(600, 200, 420, 320)
self.setwindowTitle('Help')
self.setwindowIcon(QIcon(ICON_PATH))
label = QLabel('Press anything on your keyboard to see what it does.')
self.actionLabel = QLabel('Press something!')
self.img = QLabel('img', self)
self.img.setpixmap(Qpixmap(HELP_IMG_PATH))
grid = qgridLayout()
grid.setSpacing(4)
grid.addWidget(self.img, 0)
grid.addWidget(label, 0)
grid.addWidget(self.actionLabel, 2, 0)
myFont=QFont()
myFont.setBold(True)
myFont.setPixelSize(24)
self.actionLabel.setFont(myFont)
palette = QPalette()
palette.setColor(QPalette.Foreground,Qt.green)
self.actionLabel.setPalette(palette)
self.setLayout(grid)
self.show()
def addGraphicsItems(self):
self.mainRect = QGraphicsRectItem(QRectF(-15, -15, 30, 30), self)
self.nodeTitle = qgraphicstextitem(type(self).name, self)
titleFont = QFont()
titleFont.setBold(True)
self.nodeTitle.setFont(titleFont)
self.selectedChanged(self.isSelected())
def updateSheets(self):
if self.sheets is not None and self.ownsheet is not None:
self.listSheetItems = {}
self.listWidget.clear()
for sheetId in self.sheets:
if not sheetId == self.ownsheet:
newItem = QListWidgetItem(self.sheets[sheetId])
newItem.setToolTip(str(sheetId))
newItem.setData(Qt.UserRole, sheetId)
self.listSheetItems[sheetId] = newItem
self.listWidget.addItem(newItem)
if sheetId == self.selectedSheet:
boldFont = QFont()
boldFont.setBold(True)
newItem.setFont(boldFont)
def listClicked(self, item):
normalFont = QFont()
boldFont = QFont()
boldFont.setBold(True)
for i in range(self.listWidget.count()):
itemnormal = self.listWidget.item(i)
itemnormal.setFont(normalFont)
self.selectedSheet = item.data(Qt.UserRole)
self.sendDataToImplementations({"subsheetid": self.selectedSheet})
item.setFont(boldFont)
def initTheme(self) -> None:
qApp.setStyle(VideoStyleDark() if self.theme == 'dark' else VideoStyleLight())
self.fonts = [
QFontDatabase.addApplicationFont(':/fonts/FuturaLT.ttf'),
QFontDatabase.addApplicationFont(':/fonts/NotoSans.ttc')
]
self.style().loadQSS(self.theme, self.parent.devmode)
QApplication.setFont(QFont('Noto Sans UI', 12 if sys.platform == 'darwin' else 10, 300))
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
# Click pos
self.clickPos = QtCore.QPoint(50, 50)
# App Icon
self.icon_Label = QtWidgets.QLabel()
self.icon_Label.setpixmap(QtGui.Qpixmap(":/resources/bcts.png").scaled(QtCore.QSize(40, 40)))
self.icon_Label.setFixedWidth(40)
# Title font
self.title_font = QtGui.QFont("Segoe UI")
self.title_font.setPointSize(11)
self.title_font.setBold(True)
# Title
self.title_Label = QtWidgets.QLabel("")
self.title_Label.setFont(self.title_font)
self.title_Label.setAlignment(QtCore.Qt.AlignCenter)
#?Button
self.closeApp_btn = QtWidgets.QToolButton()
self.closeApp_btn.setIcon(QtGui.QIcon(":/resources/close.png"))
self.closeApp_btn.setobjectName("closeButton")
self.titlelayout = QtWidgets.QHBoxLayout()
self.titlelayout.addWidget(self.icon_Label)
self.titlelayout.addWidget(self.title_Label)
self.titlelayout.addWidget(self.closeApp_btn)
self.titlelayout.setSpacing(0)
self.titlelayout.setContentsMargins(5, 5, 5)
# Stylesheet
self.setStyleSheet("QLabel{background:#ffffff; color:#859ba6; font-family:'Segoe UI'; font-size:12pt;} QToolButton{border:none;} QPushButton:hover{background:#6e66cc;border:1px solid #373366;} QToolButton:hover{background:#fa7064;}")
self.setLayout(self.titlelayout)
# Slots & signals
self.closeApp_btn.clicked.connect(parent.close)
def __init__(self, parent)
# Add new font
self.titleFont = QtGui.QFont('Caviar Dreams', 20)
self.titleFont.setLetterSpacing(QtGui.QFont.AbsoluteSpacing, 2.0)
# Parent widget,application window
self.parent = parent
# Mouse
self.clickPos = QtCore.QPoint(50, 50)
# Layout
self.titleLayout = QtWidgets.QHBoxLayout()
# Icon
self.iconLabel = QtWidgets.QLabel()
self.iconLabel.setpixmap(QtGui.Qpixmap(":/resources/bcts.png").scaled(QtCore.QSize(100, 100)))
self.iconLabel.setAlignment(QtCore.Qt.AlignCenter)
# Title text
self.titleLabel = QtWidgets.QLabel("BATS")
self.titleLabel.setFont(self.titleFont)
# Stylesheet
self.setStyleSheet("QLabel{color:#ffffff;}")
# Add widget
self.titleLayout.addWidget(self.iconLabel)
self.titleLayout.addWidget(self.titleLabel)
# Set layout
self.titleLayout.setContentsMargins(20, 20, 0)
self.titleLayout.setSpacing(30)
self.titleLayout.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(self.titleLayout)
# Side Menu
def __init__(self, parent)
# Customize widget
self.setobjectName("Option")
# Layout
optionLayout = QtWidgets.QHBoxLayout()
# Option font
optionFont = QtGui.QFont("Caviar Dreams")
optionFont.setPointSize(12)
optionFont.setBold(False)
optionFont.setLetterSpacing(QtGui.QFont.AbsoluteSpacing, 1.0)
# Set widgets
# Separator
optionSep = QtWidgets.QWidget()
optionSep.setStyleSheet("QWidget{background:#4da8e8;}")
optionSep.setFixedWidth(2)
# Doc button
docButton = QtWidgets.QPushButton()
docButton.setIcon(QtGui.QIcon(":/resources/doc.png"))
docButton.setIconSize(QtCore.QSize(40, 40))
docButton.setText("Documentation")
docButton.setFont(optionFont)
docButton.setCursor(QtCore.Qt.PointingHandCursor)
# Layout
optionLayout.addWidget(docButton, 10)
# self.optionLayout.setAlignment(QtCore.Qt.AlignCenter)
optionLayout.setContentsMargins(0, 0)
optionLayout.setSpacing(0)
optionLayout.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(optionLayout)
# Stylesheet
self.setStyleSheet("QWidget {margin: 0 0 0 0; padding: 0 0 0 0;} QPushButton{background:transparent; border:none; border-top: 2px solid #4da8e8; padding: 0 10px 0 10px; color: #ffffff; outline: none;} QPushButton:hover{background:#45c8dc;}")
# Actiond
docButton.clicked.connect(self.openDoc)
def __init__(self, parent)
self.setupUi(self)
# Store plot
self.parent = parent
self.table_file = None
self.plot_file = {}
self.exportTable_flag = self.exportPlot_flag = 0
# Set font size amd color for log console
self.log_tabWidget.setCurrentIndex(0)
self.log_tabWidget.setTabIcon(0, QtGui.QIcon(":/resources/tab_log.png"))
self.log_tabWidget.setTabIcon(1, QtGui.QIcon(":/resources/tab_info_disabled.png"))
self.log_tabWidget.tabBar().setTabTextColor(0, QtGui.QColor("#4f8a10"))
self.log_tabWidget.tabBar().setStyleSheet("QTabBar:tab:selected{ border-color: #4f8a10;}")
font = QtGui.QFont("Segoe UI", 10)
self.logConsole.setFont(font)
self.configConsole.setFont(font)
self.configConsole.setTextColor(QtGui.QColor("#00529B"))
self.verticalHeaderFont = font
self.logConsole.setTextColor(norMAL_LOG_COLOR)
# Link the stdout to log textedit
self.originalsys = sys.stdout
sys.stdout = StdOutStream()
# self.wheelfilter = WheelFilter()
# self.graph_comboBox.installEventFilter(self.wheelfilter)
# Set current index to the comboBox
# self.graph_comboBox.setCurrentIndex(-1)
# Action
self.log_tabWidget.currentChanged.connect(self.changeTab)
sys.stdout.textWritten.connect(self.writeLog)
self.logClear_btn.clicked.connect(self.clearLog)
# self.graph_comboBox.currentIndexChanged.connect(self.changeGraph)
self.tableExport_btn.clicked.connect(self.exportTable)
self.plotExport_btn.clicked.connect(self.exportPlot)
# Function for the log tab
def __init__(self, parent=None):
super().__init__(parent)
s = Settings()
browser_font_size = int(s.value('browser_font', 9))
self.title_font = QtGui.QFont('Open Sans Extrabold', browser_font_size)
self.summary_font = QtGui.QFont('Open Sans',
browser_font_size * 0.95,
QtGui.QFont.Bold)
self.title_font_metrics = QtGui.QFontMetrics(self.title_font)
self.summary_font_metrics = QtGui.QFontMetrics(self.title_font)
self.last_icon_size = self.parent().iconSize().height()
def placeholder_thumb_generator(title, size=150):
"""Returns a Qpixmap of size with the first letter of each word in title"""
initials = ' '.join([x[0] for x in title.split(' ') if len(x) > 2])
key = 'placeholder' + initials
img = QtGui.QpixmapCache.find(key)
if img:
return img
qsize = QtCore.QSize(size, size)
circle_color = QtGui.QColor(50, 50, 50)
text_color = QtGui.QColor(75, 75, 75)
rect = QtCore.QRect(QtCore.QPoint(0, 0), QtCore.QPoint(size, size))
center = QtCore.QPoint(size / 2, size / 2)
img = QtGui.Qpixmap(qsize)
img.fill(QtCore.Qt.transparent)
p = QtGui.QPainter(img)
p.setFont(QtGui.QFont('Open Sans', size / 4, weight=QtGui.QFont.Bold))
p.setBrush(QtGui.QBrush(circle_color))
p.setPen(circle_color)
p.setRenderHint(QtGui.QPainter.Antialiasing, True)
p.drawEllipse(center, size / 2 - 1, size / 2 - 1)
p.setPen(text_color)
p.drawText(rect, QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, initials)
QtGui.QpixmapCache.insert(key, img)
return img
def show_indicator(self):
self.indicator = self.scene.addText(
'Loading', QtGui.QFont('Helvetica', 1))
self.indicator.setDefaultTextColor(QtGui.QColor('red'))
viwport_center = self.ui.view.mapToScene(
self.ui.view.viewport().geometry().center())
self.indicator.setPos(viwport_center - self.indicator.boundingRect().center())
def __init__(self, stream, func, buffer_len, kill_signal,
parent=None):
super(MainWindow, self).__init__(parent)
self.Feedback = QLabel()
self.Feedback.setText("Waiting for Feedback ...")
self.Feedback.setAlignment(QtCore.Qt.AlignCenter)
font = QtGui.QFont()
font.setPointSize(24)
self.Feedback.setFont(font)
self.layout = QVBoxLayout()
self.layout.addWidget(self.Feedback)
self.setLayout(self.layout)
self.setwindowTitle("Feedback")
self.resize(300, 200)
self.worker = Worker(stream=stream,
func=func,
args=args,
buffer_len=buffer_len,
kill_signal=kill_signal)
self.worker.refresh_signal.connect(self.update)
self.worker.start()
def setupUi(self, Dialog):
Dialog.setobjectName("Dialog")
Dialog.resize(389, 239)
Dialog.setStyleSheet("font: 10pt \"Arial\";")
self.gridLayout = QtWidgets.qgridLayout(Dialog)
self.gridLayout.setobjectName("gridLayout")
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setorientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setobjectName("buttonBox")
self.gridLayout.addWidget(self.buttonBox, 1)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setobjectName("verticalLayout")
self.label = QtWidgets.QLabel(Dialog)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setItalic(False)
self.label.setFont(font)
self.label.setobjectName("label")
self.verticalLayout.addWidget(self.label, QtCore.Qt.AlignTop)
self.comboBox = QtWidgets.QComboBox(Dialog)
self.comboBox.setobjectName("comboBox")
self.verticalLayout.addWidget(self.comboBox)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
spacerItem1 = QtWidgets.QSpacerItem(20, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem1)
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setobjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.plainTextEditDescription = QtWidgets.QPlainTextEdit(Dialog)
self.plainTextEditDescription.setReadOnly(True)
self.plainTextEditDescription.setobjectName("plainTextEditDescription")
self.verticalLayout.addWidget(self.plainTextEditDescription)
self.gridLayout.addLayout(self.verticalLayout, 1)
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(Dialog.accept)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def switch_to_text(self, text):
font = QFont()
font.setPointSize(self.__height_to_point(self.PIX.height()))
graphics_text_item = qgraphicstextitem(text)
graphics_text_item.setFlag(QGraphicsItem.ItemIsMovable)
graphics_text_item.setFont(font)
self.scene().addItem(graphics_text_item)
graphics_text_item.setPos(
QPoint(self.item.boundingRect().x(), self.item.boundingRect().y()))
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.scene().addItem(self.item)
def otherUIFont():
"""
Returns an auxiliary UI font.
"""
font = QFont()
pointSize = 9
if sys.platform == "win32":
font.setFamily("Segoe UI")
elif sys.platform == "darwin":
try:
platform
except NameError:
import platform
if platform.mac_ver()[0].startswith("10.10"):
font.setFamily("Lucida Grande")
pointSize = 12
elif sys.platform.startswith("linux"):
font.setFamily("Luxi Sans")
font.setPointSize(pointSize)
return font
# ----
# Keys
# ----
def set_rect(self, rect):
scale = config.get('display', 'id_font_scale')
bold = config.get('display', 'id_font_bold')
self._text.setFont(QFont('', rect.width()*0.08*scale))
self._text.setPos(rect.x(), rect.y() + 0.6*rect.height())
self._text.setDefaultTextColor(QColor(config.get('display', 'id_font_color')))
if self._display_mode == 0:
if bold:
self._text.setHtml('<b>P(' + str(self._id) + ')</b>')
else:
self._text.setHtml('P(' + str(self._id) + ')')
self._graphics_item.setRect(rect.x(), rect.y(), rect.width(), rect.height())
self._items[0].setRect(rect.x() + rect.width()/5, rect.width()/5, rect.height())
self._items[1].setRect(rect.x() + rect.width()/5 * 3, rect.height())
elif self._display_mode == 1:
self._text.setPlainText('')
self._graphics_item.setRect(rect.x(), rect.height())
def set_rect(self, rect):
if self._carried is not None:
rect = self._carried.get_rect()
scale = config.get('display', rect.y() + 0.4*rect.height())
self._text.setDefaultTextColor(QColor(config.get('display', 'id_font_color')))
if self._display_mode == 0:
if bold:
self._text.setHtml('<b>S(' + str(self._id) + ')</b>')
else:
self._text.setHtml('S(' + str(self._id) + ')')
self._graphics_item.setRect(rect.x() + 0.25*rect.width(),
rect.y() + 0.25*rect.height(),
rect.width()*0.5,
rect.height()*0.5)
self._graphics_carried.setRect(rect.x() + 0.325*rect.width(),
rect.y() + 0.325*rect.height(),
rect.width()*0.35,
rect.height()*0.35)
elif self._display_mode == 1:
self._text.setPlainText('')
self._graphics_item.setRect(rect.x() + 0.05*rect.width(),
rect.y() + 0.05*rect.height(),
rect.width()*0.9,
rect.height()*0.9)
self._graphics_carried.setRect(rect.x() + 0.125*rect.width(),
rect.y() + 0.125*rect.height(),
rect.width()*0.75,
rect.height()*0.75)
def set_rect(self, rect.y() + 0.2*rect.height())
self._text.setDefaultTextColor(QColor(config.get('display', 'id_font_color')))
if self._display_mode == 0:
if bold:
self._text.setHtml('<b>R(' + str(self._id) + ')</b>')
else:
self._text.setHtml('R(' + str(self._id) + ')')
self._graphics_item.setRect(rect.x() + 0.25*rect.width(),
rect.height()*0.5,)
elif self._display_mode == 1:
self._text.setPlainText('')
self._graphics_item.setRect(rect.x() + 0.05*rect.width(),
rect.height()*0.9)
if self._carries is not None:
self._carries.set_rect(rect)
def set_rect(self, 'id_font_bold')
font = QFont('', rect.width()*0.08*scale)
self._text.setFont(font)
self._text.setPos(rect.x(), 'id_font_color')))
if self._display_mode == 0:
ss = ''
if bold:
ss = '<b>'
for key in self._ids:
count = 0
for ii in self._ids[key]:
if count == 0:
ss = ss + '(' + key + ': ' + ii[0]
else:
ss = ss + ',' + ii[0]
count += 1
ss = ss + ')\n'
if bold:
ss += '</b>'
self._text.setHtml(ss)
self._graphics_item.setRect(rect.x(), rect.height())
elif self._display_mode == 1:
self._text.setPlainText('')
self._graphics_item.setRect(rect.x(), rect.height())
def __init__(self, brown_object, family_name, size, weight, italic):
"""
Args:
brown_object (Brush): The object this interface belongs to
family_name (str): The name of the font family
size (Unit): The size of the font
weight (int or None): The font weight. If `None`,
a normal weight will be used.
italic (bool): Italicized or not
"""
super().__init__(brown_object)
self.family_name = family_name
self.size = size
self.weight = weight
self.italic = italic
self.qt_object = QtGui.QFont(
self.family_name,
GraphicUnit(self.size).value,
self.weight if self.weight is not None else -1,
self.italic)
self._qt_font_info_object = QtGui.QFontInfo(self.qt_object)
self._qt_font_metrics_object = QtGui.QFontMetricsF(
self.qt_object,
brown._app_interface.view)
######## PUBLIC PROPERTIES ########
def test_init_qt_attribute_transfer(self):
test_font = FontInterface(None, 'Bravura', MockUnit(12), False)
assert(isinstance(test_font.qt_object, QtGui.QFont))
assert(test_font.qt_object.bold() is False)
assert(test_font.qt_object.italic() is False)
assert(test_font.qt_object.pointSize() == 6)
assert(test_font.qt_object.weight() == 1)