def data(self, index, role): source_index = self.mapToSource(index) source_model = self.sourceModel() if not source_index.isValid(): return QVariant() source_data = source_model.data(source_index, role) if index.column() == source_model.columns_types.index('is_member') \ and role == Qt.DisplayRole: value = {True: self.tr('yes'), False: self.tr('no'), None: self.tr('offline')} return value[source_data] if index.column() == source_model.columns_types.index('pubkey') \ and role == Qt.DisplayRole: return source_data[:5] if role == Qt.TextAlignmentRole: if source_index.column() == source_model.columns_types.index('address') or source_index.column() == self.sourceModel().columns_types.index('current_block'): return Qt.AlignRight | Qt.AlignVCenter if source_index.column() == source_model.columns_types.index('is_member'): return Qt.AlignCenter if role == Qt.FontRole: is_root_col = source_model.columns_types.index('is_root') index_root_col = source_model.index(source_index.row(), is_root_col) if source_model.data(index_root_col, Qt.DisplayRole): font = QFont() font.setBold(True) return font return source_data
def show_modulation_info(self): show = not self.has_default_modulation or self.modulators[0] != Modulator("Modulation") if not show: self.ui.btnEditModulation.setStyleSheet("background: orange") font = QFont() font.setBold(True) self.ui.btnEditModulation.setFont(font) else: self.ui.btnEditModulation.setStyleSheet("") self.ui.btnEditModulation.setFont(QFont()) cur_ind = self.ui.cBoxModulations.currentIndex() cur_mod = self.modulators[cur_ind] self.ui.lCarrierFreqValue.setText(cur_mod.carrier_frequency_str) self.ui.lCarrierPhaseValue.setText(cur_mod.carrier_phase_str) self.ui.lBitLenValue.setText(cur_mod.bit_len_str) self.ui.lSampleRateValue.setText(cur_mod.sample_rate_str) mod_type = cur_mod.modulation_type_str self.ui.lModTypeValue.setText(mod_type) if mod_type == "ASK": prefix = "Amplitude" elif mod_type == "PSK": prefix = "Phase" elif mod_type in ("FSK", "GFSK"): prefix = "Frequency" else: prefix = "Unknown Modulation Type (This should not happen...)" self.ui.lParamForZero.setText(prefix + " for 0:") self.ui.lParamForZeroValue.setText(cur_mod.param_for_zero_str) self.ui.lParamForOne.setText(prefix + " for 1:") self.ui.lParamForOneValue.setText(cur_mod.param_for_one_str)
def convertParsedQFont(chars_sets, font): name = font['name'] qfont = QFont( font['family'], int(font['pointsize']) ) qfont.setBold( font['bold'] ) # convert and return return NFontConverter.convertQFont( chars_sets, name, qfont )
def __init__(self): super().__init__() self.setGeometry(600, 200, 420, 320) self.setWindowTitle('Help') self.setWindowIcon(QIcon(ICON_PATH)) label = QLabel('Press anything on your keyboard to see what it does.') self.actionLabel = QLabel('Press something!') self.img = QLabel('img', self) self.img.setPixmap(QPixmap(HELP_IMG_PATH)) grid = QGridLayout() grid.setSpacing(4) grid.addWidget(self.img, 0, 0) grid.addWidget(label, 1, 0) grid.addWidget(self.actionLabel, 2, 0) myFont=QFont() myFont.setBold(True) myFont.setPixelSize(24) self.actionLabel.setFont(myFont) palette = QPalette() palette.setColor(QPalette.Foreground,Qt.green) self.actionLabel.setPalette(palette) self.setLayout(grid) self.show()
def __init__(self, parent = None, message = None, itemType = "log"): QListWidgetItem.__init__(self) self.itemType = itemType if (itemType == "log"): self.setText("--- " + str(message)) elif (itemType == "in"): self.setText("<<< " + str(message)) elif (itemType == "out"): self.setText(">>> " + str(message)) else: self.setText(str(message)) font = QFont() font.setFamily("Monospace") if (itemType == "in") or (itemType == "out"): font.setBold(True) font.setWeight(75) else: font.setBold(False) font.setWeight(50) self.setFont(font) brush = QBrush(QColor(0, 0, 0)) if (itemType == "in"): brush = QBrush(QColor(0, 0, 85)) elif (itemType == "out"): brush = QBrush(QColor(0, 85, 0)) brush.setStyle(Qt.NoBrush) self.setForeground(brush)
def _get_pos_widget(name, backgroundColor, foregroundColor): label = QLabel() label.setAttribute(Qt.WA_TransparentForMouseEvents, True) pixmap = QPixmap(25 * 10, 25 * 10) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) pen = QPen(foregroundColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) font = QFont() font.setBold(True) font.setPixelSize(25 * 10 - 30) path = QPainterPath() path.addText(QPointF(50, 25 * 10 - 50), font, name) brush = QBrush(foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation) label.setPixmap(pixmap) spinbox = DelayedSpinBox(750) spinbox.setAlignment(Qt.AlignCenter) spinbox.setToolTip("{0} Spin Box".format(name)) spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons) spinbox.setMaximumHeight(20) font = spinbox.font() font.setPixelSize(14) spinbox.setFont(font) sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name()) spinbox.setStyleSheet(sheet) return label, spinbox
def __createTexts(self): """ Private method to create the text items of the module item. """ if self.model is None: return boldFont = QFont(self.font) boldFont.setBold(True) classes = self.model.getClasses() x = self.margin + self.rect().x() y = self.margin + self.rect().y() self.header = QGraphicsSimpleTextItem(self) self.header.setFont(boldFont) self.header.setText(self.model.getName()) self.header.setPos(x, y) y += self.header.boundingRect().height() + self.margin if classes: txt = "\n".join(classes) else: txt = " " self.classes = QGraphicsSimpleTextItem(self) self.classes.setFont(self.font) self.classes.setText(txt) self.classes.setPos(x, y)
def data(self, index, role): row = index.row() column = index.column() if role == Qt.DisplayRole: text = "({},{})".format(row, column) return text elif role == Qt.FontRole: if row == 0 and column == 0: # change font only for cell(0,0) my_font = QFont() my_font.setBold(True) my_font.setItalic(True) my_font.setUnderline(True) return my_font elif role == Qt.BackgroundRole: if row == 1 and column == 2: # change background only for cell(1,2) my_background = QBrush(Qt.red) return my_background elif role == Qt.TextAlignmentRole: if row == 1 and column == 1: # change text alignment only for cell(1,1) return Qt.AlignRight + Qt.AlignVCenter elif role == Qt.CheckStateRole: if row == 0 and column == 1: # add checkbox only for cell(0,1) return Qt.Checked elif row == 0 and column == 2: # add checkbox only for cell(0,2) return Qt.Unchecked return QVariant() # see http://doc.qt.io/qt-5/qvariant.html#details
def 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 draw_frequency_marker(self, x_pos, frequency): if frequency is None: self.clear_frequency_marker() return y1 = self.sceneRect().y() y2 = self.sceneRect().y() + self.sceneRect().height() if self.frequency_marker is None: pen = QPen(constants.LINECOLOR, 0) self.frequency_marker = [None, None] self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen) self.frequency_marker[1] = self.addSimpleText("") self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR)) font = QFont() font.setBold(True) font.setPointSize(int(font.pointSize() * 1.25)+1) self.frequency_marker[1].setFont(font) self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2) scale_x, scale_y = self.__calc_x_y_scale(self.sceneRect()) self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False) self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3)) font_metric = QFontMetrics(self.frequency_marker[1].font()) text_width = font_metric.width("Tune to") * scale_x text_width += (font_metric.width(" ") * scale_x) / 2 self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
def data(self, column, role=Qt.DisplayRole): data = abstractItem.data(self, column, role) E = self.enum if role == Qt.DisplayRole or role == Qt.EditRole: if data == "" and column == E.revisions: return [] else: return data elif role == Qt.DecorationRole and column == E.title: if self.customIcon(): return QIcon.fromTheme(self.data(E.customIcon)) if self.isFolder(): return QIcon.fromTheme("folder") elif self.isText(): return QIcon.fromTheme("text-x-generic") elif role == Qt.CheckStateRole and column == E.compile: return Qt.Checked if self.compile() else Qt.Unchecked elif role == Qt.FontRole: f = QFont() if column == E.wordCount and self.isFolder(): f.setItalic(True) elif column == E.goal and self.isFolder() and not self.data(E.setGoal): f.setItalic(True) if self.isFolder(): f.setBold(True) return f
def initUi(self, options, enabledOptions, headerOptions, singleSelectionMode): boldFont = QFont() boldFont.setBold(True) # set the selection mode if not singleSelectionMode: self.listView_options.setSelectionMode(QAbstractItemView.ExtendedSelection) # create enableItems if none if enabledOptions is None: enabledOptions = [True for idx in range(len(options))] # Insert the choices self.standaredItemModel = QStandardItemModel(self.listView_options) self.standaredItemModel.itemChanged.connect(self.onItemChanged) for idx in range(len(options)): standaredItem = QStandardItem(options[idx]) standaredItem.setSelectable(enabledOptions[idx]) if idx in headerOptions: standaredItem.setFont(boldFont) self.standaredItemModel.appendRow(standaredItem) self.listView_options.setModel(self.standaredItemModel) # disable select all / de select all buttons if in single selection # mode if singleSelectionMode: self.pushButton_sellectAll.setDisabled(True) self.pushButton_deSellectAll.setDisabled(True)
def __init__(self): """The constructor initializes the class AboutDialog.""" super().__init__() self.setAttribute(Qt.WA_DeleteOnClose) # initialize class constants self._BUTTON_MIN_WIDTH = 110 self._OXYGEN_PATH_48 = os.path.join("resources", "icons", "oxygen", "48") # fonts and margins settings hlFont = QFont() hlFont.setBold(True) hlFont.setPointSize(14) # scientific logo logo = QLabel(pixmap=QPixmap(os.path.join(self._OXYGEN_PATH_48, "applications-science.png"))) logoLayout = QVBoxLayout() logoLayout.addWidget(logo) logoLayout.addStretch() # begin the content # headline and description text self.headline = QLabel() self.headline.setFont(hlFont) self.description = QLabel(wordWrap=True) # the list with the open button self.listWidget = QListWidget() self.listWidget.setMinimumWidth(420) self.createArticles() self.openButton = QPushButton() self.openButton.clicked.connect(self.openAction) listLayout = QHBoxLayout() listLayout.addWidget(self.listWidget) listLayout.addWidget(self.openButton, alignment=Qt.AlignTop) # create a close button line = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.HLine) self.closeButton = QPushButton() self.closeButton.setFixedWidth(self._BUTTON_MIN_WIDTH) self.closeButton.clicked.connect(self.close) # content layout contentLayout = QVBoxLayout() contentLayout.addWidget(self.headline) contentLayout.addWidget(self.description) contentLayout.addLayout(listLayout) contentLayout.addWidget(line) contentLayout.addWidget(self.closeButton, alignment=Qt.AlignRight) # main layout layout = QHBoxLayout(self) layout.addLayout(logoLayout) layout.addLayout(contentLayout) # translate the graphical user interface self.retranslateUi()
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 _setupUi(self): self.setWindowTitle(tr("Schedule Modification Scope")) self.resize(333, 133) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(tr("Do you want this change to affect all future occurrences of this schedule?")) font = QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.label_2 = QLabel(tr( "You can force global scope (in other words, changing all future occurrences) by " "holding Shift when you perform the change." )) self.label_2.setWordWrap(True) self.verticalLayout.addWidget(self.label_2) self.horizontalLayout = QHBoxLayout() self.cancelButton = QPushButton(tr("Cancel")) self.cancelButton.setShortcut("Esc") self.horizontalLayout.addWidget(self.cancelButton) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.globalScopeButton = QPushButton(tr("All future occurrences")) self.globalScopeButton.setAutoDefault(False) self.horizontalLayout.addWidget(self.globalScopeButton) self.localScopeButton = QPushButton(tr("Just this one")) self.localScopeButton.setAutoDefault(False) self.localScopeButton.setDefault(True) self.horizontalLayout.addWidget(self.localScopeButton) self.verticalLayout.addLayout(self.horizontalLayout)
def refresh(self): """ Public method to refresh the tree. """ QApplication.setOverrideCursor(Qt.WaitCursor) self.__itemChangingBlock = True self.clear() boldFont = QFont() boldFont.setBold(True) self.__topItem = QTreeWidgetItem(self) self.__topItem.setText(0, self.__subscription.title()) self.__topItem.setFont(0, boldFont) self.addTopLevelItem(self.__topItem) allRules = self.__subscription.allRules() index = 0 for rule in allRules: item = QTreeWidgetItem(self.__topItem) item.setText(0, rule.filter()) item.setData(0, Qt.UserRole, index) if self.__subscription.canEditRules(): item.setFlags(item.flags() | Qt.ItemIsEditable) self.__adjustItemFeatures(item, rule) index += 1 self.expandAll() self.showRule(None) self.__itemChangingBlock = False QApplication.restoreOverrideCursor() QApplication.processEvents()
def data(self, index, role): source_index = self.mapToSource(index) model = self.sourceModel() source_data = model.data(source_index, role) state_col = model.columns_types.index('state') state_index = model.index(source_index.row(), state_col) state_data = model.data(state_index, Qt.DisplayRole) if role == Qt.DisplayRole: if source_index.column() == model.columns_types.index('uid'): return source_data if source_index.column() == model.columns_types.index('date'): return QLocale.toString( QLocale(), QDateTime.fromTime_t(source_data).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) ) if source_index.column() == model.columns_types.index('payment') or \ source_index.column() == model.columns_types.index('deposit'): if source_data is not "": amount_ref = self.account.units_to_diff_ref(source_data, self.community) # if referential type is quantitative... if self.account.ref_type() == 'q': # display int values return QLocale().toString(float(amount_ref), 'f', 0) else: # display float values return QLocale().toString(amount_ref, 'f', 6) if role == Qt.FontRole: font = QFont() if state_data == Transfer.AWAITING: font.setItalic(True) elif state_data == Transfer.REFUSED: font.setItalic(True) elif state_data == Transfer.TO_SEND: font.setBold(True) else: font.setItalic(False) return font if role == Qt.ForegroundRole: if state_data == Transfer.REFUSED: return QColor(Qt.red) elif state_data == Transfer.TO_SEND: return QColor(Qt.blue) if role == Qt.TextAlignmentRole: if source_index.column() == self.sourceModel().columns_types.index( 'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'): return Qt.AlignRight | Qt.AlignVCenter if source_index.column() == self.sourceModel().columns_types.index('date'): return Qt.AlignCenter if role == Qt.ToolTipRole: if source_index.column() == self.sourceModel().columns_types.index('date'): return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate) return source_data
def set_font_style(self, family, size, form): font = QFont() font.setFamily(family) font.setPointSize(size) boldFlag, italicFlag = self.interprete_font_form(form) font.setBold(boldFlag) font.setItalic(italicFlag) self.setFont(font)
def fontForID(self, fontId): result = QFont(QApplication.font()) if fontId == FontID.Title: result.setPointSize(self.TITLE_FONT_SIZE) result.setBold(True) else: result.setPointSize(self.LEGEND_FONT_SIZE) return result
def createTitleLabel(self, title): titleLabel = QLabel(title) font = QFont() font.setBold(True) font.setPointSize(18) titleLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) titleLabel.setFont(font) return titleLabel
def createTitle(self): title = QLabel(self.bot1.name + ' vs ' + self.bot2.name) font = QFont() font.setBold(True) font.setPointSize(12) title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) title.setFont(font) return title
def lbl3(self): font = QFont() font.setFamily("Quicksand") font.setBold(True) font.setPointSize(15) lbl3 = QLabel('Don\'t show this at start up' ,self) lbl3.setFont(font) lbl3.setStyleSheet("QLabel { color : white; }") lbl3.move(580, 650)
def lbl2(self): font = QFont() font.setFamily("Quicksand") font.setBold(True) font.setPointSize(19) lbl2 = QLabel('Welcome to Revolution OS, under this text you find usefull Links to get started.',self) lbl2.setFont(font) lbl2.setStyleSheet("QLabel { color : white; }") lbl2.move(15, 200)
def headingFont(): font = QFont() font.setStyleStrategy(QFont.PreferAntialias) font.setPixelSize(23) font.setBold(True) font.setFamily('Verdana') return font;
def _getData(self, row, column, role): if role == Qt.FontRole: font = QFont(self.view.font()) font.setBold(row.is_bold) return font if column.name == 'status': return self._getStatusData(row, role) else: return Table._getData(self, row, column, role)
def __init__(self): super(PayrecWidget, self).__init__() self.ui = Ui_PayrecWidget() self.ui.setupUi(self) font = QFont() font.setFamily("Comic Sans MS") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.ui.rec_label.setFont(font) self.ui.gsf_label.setFont(font)
def __init__(self, page): font = QFont(QApplication.font()) font.setBold(True) fm = QFontMetrics(font) titleBase = page.viewPrinter.title titleLineCount = len(titleBase.split("\n")) titleHeight = fm.height() * titleLineCount rect = QRect(page.pageRect.topLeft(), QSize(page.pageRect.width(), titleHeight)) LayoutElement.__init__(self, rect) self.page = page self.font = font
def makeTable(self): self.table = QTableWidget(3,4) for column in range(len(header)): table_item = QTableWidgetItem(header[column]) header_font = QFont() header_font.setBold(True) table_item.setFont(header_font) self.table.setHorizontalHeaderItem(column, table_item) self.table.setColumnWidth(column, header_size[column]) self.layout.addWidget(self.table, QtCore.Qt.AlignTop) self.setCentralWidget(self.table) pass
def refresh(self): self.text.setPlainText("?" if not self.model_item else self.model_item.shortname) if hasattr(self.model_item, "simulate") and self.model_item.simulate: font = QFont() font.setBold(True) self.text.setFont(font) self.text.setDefaultTextColor(Qt.darkGreen) self.line.setPen(QPen(Qt.darkGreen, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) else: self.text.setFont(QFont()) self.text.setDefaultTextColor(constants.LINECOLOR) self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))
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 show_bin_list(self, tbody): selector = etree.HTML(tbody) # 转换为lxml解析的对象 contents = selector.xpath( '//div/div[@data-type="folder"]/div[@data-type="folder"]/a/text()' ) # 这里返回的是一个列表 messages = selector.xpath( '//div/div[@data-type="folder"]/div/div[@class="commit-details"]/a/text()' ) # 这里返回的是一个列表 timeagos = selector.xpath( '//div/div[@data-type="folder"]/div/span[@class="timeago"]/@datetime' ) # 这里返回的是一个列表 print(contents) print(messages) print(timeagos) self.TableWidget = QTableWidget() self.TableWidget.setColumnCount(4) # 表格共有四列 self.TableWidget.verticalHeader().setVisible(False) # 隐藏垂直表头 self.TableWidget.horizontalHeader().setVisible(True) # 显示水平表头 font = QFont('微软雅黑', 10) font.setBold(True) #设置字体加粗 self.TableWidget.horizontalHeader().setFont(font) #设置表头字体 # self.TableWidget.setFrameShape(QFrame.NoFrame) ##设置无表格的外框 self.TableWidget.horizontalHeader().setFixedHeight(25) ##设置表头高度 self.TableWidget.horizontalHeader().setSectionResizeMode( 0, QHeaderView.Stretch) #设置第一列宽度自动调整,充满屏幕 # self.TableWidget.horizontalHeader().setStretchLastSection(True) ##设置最后一列拉伸至最大 self.TableWidget.setHorizontalHeaderLabels( ['固件名称', '固件版本', '更新日期', '操作']) #设置表头内容 self.TableWidget.horizontalHeader().setSectionsClickable(False) self.TableWidget.horizontalHeader().setStyleSheet( 'QHeaderView::section{background:green}') #设置表头的背景色为绿色 self.TableWidget.setEditTriggers( QAbstractItemView.NoEditTriggers) # 不可编辑 self.TableWidget.setSelectionBehavior( QAbstractItemView.SelectRows) #只能选择整行 self.TableWidget.setColumnWidth(1, 100) self.TableWidget.setColumnWidth(2, 130) self.TableWidget.setColumnWidth(3, 100) rows = self.TableWidget.rowCount() rows_index = 0 if not messages: for i in range(len(contents)): messages.append("获取失败") if not timeagos: for i in range(len(contents)): timeagos.append("获取失败") for content, message, timeago in zip(contents, messages, timeagos): content = content.strip() # 去掉字符左右的空格 if content.find('@') > 0: message = message.strip() timeago = timeago.strip() self.TableWidget.setRowCount(rows_index + 1) self.TableWidget.setItem(rows_index, 0, QTableWidgetItem(content)) self.TableWidget.setItem(rows_index, 1, QTableWidgetItem(message)) self.TableWidget.setItem(rows_index, 2, QTableWidgetItem(timeago)) self.TableWidget.setCellWidget(rows_index, 3, self.buttonForRow(rows_index)) rows_index += 1 self.TableWidget.setGeometry(15, 10, 300, 300) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.TableWidget) return 0
def paintEvent(self, event): if not self.customStyle: return QGroupBox.paintEvent(self, event) p = QStylePainter(self) opt = QStyleOptionGroupBox() self.initStyleOption(opt) style = qApp.style() groupBox = opt # // Draw frame textRect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxLabel) checkBoxRect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxCheckBox) p.save() titleRect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxFrame) # r.setBottom(style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxContents).top()) titleRect.setHeight(textRect.height()) titleRect.moveTop(textRect.top()) p.setBrush(QBrush(QColor(Qt.blue).lighter(190))) p.setPen(Qt.NoPen) p.drawRoundedRect(titleRect, 10, 10) p.restore() if groupBox.subControls & QStyle.SC_GroupBoxFrame: frame = QStyleOptionFrame() # frame.operator=(groupBox) frame.state = groupBox.state frame.features = groupBox.features frame.lineWidth = groupBox.lineWidth frame.midLineWidth = groupBox.midLineWidth frame.rect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxFrame) p.save() region = QRegion(groupBox.rect) if groupBox.text: ltr = groupBox.direction == Qt.LeftToRight finalRect = QRect() if groupBox.subControls & QStyle.SC_GroupBoxCheckBox: finalRect = checkBoxRect.united(textRect) finalRect.adjust(-4 if ltr else 0, 0, 0 if ltr else 4, 0) else: finalRect = textRect region -= QRegion(finalRect) p.setClipRegion(region) style.drawPrimitive(style.PE_FrameGroupBox, frame, p) p.restore() # // Draw title if groupBox.subControls & QStyle.SC_GroupBoxLabel and groupBox.text: # textColor = QColor(groupBox.textColor) # if textColor.isValid(): # p.setPen(textColor) # alignment = int(groupBox.textAlignment) # if not style.styleHint(QStyle.SH_UnderlineShortcut, opt): # alignment |= Qt.TextHideMnemonic # style.drawItemText(p, textRect, Qt.TextShowMnemonic | Qt.AlignHCenter | alignment, # groupBox.palette, groupBox.state & style.State_Enabled, groupBox.text, # QPalette.NoRole if textColor.isValid() else QPalette.WindowText) p.save() topt = QTextOption(Qt.AlignHCenter | Qt.AlignVCenter) f = QFont() f.setBold(True) p.setFont(f) p.setPen(Qt.darkBlue) p.drawText(QRectF(titleRect), groupBox.text.replace("&", ""), topt) p.restore() if groupBox.state & style.State_HasFocus: fropt = QStyleOptionFocusRect() # fropt.operator=(groupBox) fropt.state = groupBox.state fropt.rect = textRect style.drawPrimitive(style.PE_FrameFocusRect, fropt, p)
def create_main_layout(self): """Create startin layouy""" ### WIDGETS self.display_description = QLineEdit() self.display_code = QTextEdit() self.display_title = QLabel('Title') self.display_step = QLabel('Steps') self.picture_button = QPushButton() self.finish_button = QPushButton('Finish') self.next_button = QPushButton('Next') self.alpha_button = QPushButton('α') self.beta_button = QPushButton('β') self.pi_button = QPushButton('π') self.omega_button = QPushButton('Ω') self.lambda_button = QPushButton('λ') self.mi_button = QPushButton('µ') self.sigma_button = QPushButton('σ') self.sum_button = QPushButton('Σ') self.delta_button = QPushButton('Δ') self.gamma_button = QPushButton('Γ') self.not_equal_button = QPushButton('≠') self.approx_equal_button = QPushButton('≈') self.sqrt_button = QPushButton('√') self.gt_button = QPushButton('≥') self.lt_button = QPushButton('≤') self.degree_button = QPushButton('°') self.icon_black = QIcon(os.path.join('imgs', 'picture.png')) self.icon_red = QIcon(os.path.join('imgs', 'picture_red.png')) self.picture_button.setIcon(self.icon_black) ### GRIDS self.main_grid = QGridLayout() self.right_grid = QGridLayout() self.symbols_grid = QGridLayout() ### ADD WIDGETS self.symbols_grid.addWidget(self.alpha_button, 0, 0) self.symbols_grid.addWidget(self.beta_button, 0, 1) self.symbols_grid.addWidget(self.pi_button, 0, 2) self.symbols_grid.addWidget(self.omega_button, 0, 3) self.symbols_grid.addWidget(self.lambda_button, 0, 4) self.symbols_grid.addWidget(self.mi_button, 0, 5) self.symbols_grid.addWidget(self.sigma_button, 0, 6) self.symbols_grid.addWidget(self.sum_button, 0, 7) self.symbols_grid.addWidget(self.delta_button, 1, 0) self.symbols_grid.addWidget(self.gamma_button, 1, 1) self.symbols_grid.addWidget(self.not_equal_button, 1, 2) self.symbols_grid.addWidget(self.approx_equal_button, 1, 3) self.symbols_grid.addWidget(self.sqrt_button, 1, 4) self.symbols_grid.addWidget(self.gt_button, 1, 5) self.symbols_grid.addWidget(self.lt_button, 1, 6) self.symbols_grid.addWidget(self.degree_button, 1, 7) self.right_grid.addWidget(self.display_step, 0, 0) self.right_grid.addWidget(self.picture_button, 1, 0) self.right_grid.addWidget(self.finish_button, 2, 0) self.right_grid.addWidget(self.next_button, 3, 0) self.main_grid.addItem(self.symbols_grid, 2, 0) self.main_grid.addWidget(self.display_description, 0, 0) self.main_grid.addWidget(self.display_code, 1, 0) self.main_grid.addWidget(self.display_title, 0, 1) self.main_grid.addItem(self.right_grid, 1, 1) ### LAYOUT FORMATION font = QFont('Calibri', 15) font.setBold(True) self.display_description.setMaximumWidth(600) self.display_description.setAlignment(Qt.AlignHCenter) self.display_code.setMaximumWidth(600) self.display_code.setMinimumWidth(600) self.display_code.setMaximumHeight(500) self.display_title.setFont(font) self.display_title.setAlignment(Qt.AlignHCenter) self.display_step.setAlignment(Qt.AlignCenter) self.display_step.setFont(font) self.finish_button.setMinimumHeight(60) self.next_button.setMinimumHeight(60) self.main_widget = QWidget() self.main_widget.setLayout(self.main_grid) #### BEHAVIOURS #### self.finish_button.clicked.connect(self.finish_button_method) self.next_button.clicked.connect(self.next_button_method) self.picture_button.clicked.connect(self.picture_button_method) self.alpha_button.clicked.connect(self.alpha_button_method) self.beta_button.clicked.connect(self.beta_button_method) self.pi_button.clicked.connect(self.pi_button_method) self.omega_button.clicked.connect(self.omega_button_method) self.lambda_button.clicked.connect(self.lambda_button_method) self.mi_button.clicked.connect(self.mi_button_method) self.sigma_button.clicked.connect(self.sigma_button_method) self.sum_button.clicked.connect(self.sum_button_method) self.delta_button.clicked.connect(self.delta_button_method) self.gamma_button.clicked.connect(self.gamma_button_method) self.not_equal_button.clicked.connect(self.not_equal_button_method) self.approx_equal_button.clicked.connect( self.approx_equal_button_method) self.sqrt_button.clicked.connect(self.sqrt_button_method) self.gt_button.clicked.connect(self.gt_button_method) self.lt_button.clicked.connect(self.lt_button_method) self.degree_button.clicked.connect(self.degree_button_method)
def similarHomeZesDisplay_NOGRID(self): """ Group Box which displays zestimate info for homes which are similar to the currect and their difference :return: """ widget = QGroupBox() titlerow = QHBoxLayout() row1 = QHBoxLayout() row2 = QHBoxLayout() row3 = QHBoxLayout() row4 = QHBoxLayout() vlayout = QVBoxLayout() simZes = QLabel() myFont = QFont() myFont.setBold(True) simZes.setFont(myFont) simZes.setText("Similar home's avg value") filler1 = QLabel() filler2 = QLabel() diff = QLabel('Difference Between Own and Avg Similar Home') titlerow.addWidget(filler1) titlerow.addWidget(filler2) titlerow.addWidget(diff) row1Lab = QLabel("Zestimate:") zillowZestimate = QLabel() zillowZestimate.setText( locale.currency( self.propertyObj.zillowAnalysis.comp_mean_weighted_sim, grouping=True)) if self.propertyObj.zillowAnalysis.price is not None and self.propertyObj.zillowAnalysis.comp_mean_weighted_sim is not None: d1 = str(self.propertyObj.zillowAnalysis.price - self.propertyObj.zillowAnalysis.comp_mean_weighted_sim) else: d1 = "None" d1lab = QLabel(d1) row1.addWidget(d1lab) row1.addWidget(row1Lab) row1.addWidget(zillowZestimate) row2Lab = QLabel("Upper Valuation:") zillowUpper = QLabel() zillowUpper.setText( locale.currency( self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_high, grouping=True)) row2.addWidget(row2Lab) row2.addWidget(zillowUpper) row3Lab = QLabel("Lower Valuation: ") zillowLower = QLabel() zillowLower.setText( locale.currency( self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_low, grouping=True)) row3.addWidget(row3Lab) row3.addWidget(zillowLower) row4Lab = QLabel("30 Day Change: ") zillowChange = QLabel() zillowChange.setText( locale.currency( self.propertyObj.zillowAnalysis.comp_change_mean_weighted_sim, grouping=True)) row4.addWidget(row4Lab) row4.addWidget(zillowChange) vlayout.addWidget(simZes) vlayout.addLayout(titlerow) vlayout.addLayout(row1) vlayout.addLayout(row2) vlayout.addLayout(row3) vlayout.addLayout(row4) widget.setLayout(vlayout) return widget
class CountTable(QDialog): """ Tool to precisely verify the scans of the project. It is composed of push buttons on its top, each one corresponding to a tag selected by the user. When, the "Count scans" button is clicked, a table is created with all the combinations possible for the values of the first n-1 tags. Then, the m values that can take the last tag are displayed in the header of the m last columns of the table. The cells are then filled with a green plus or a red cross depending on if there is at least a scan that has all the tags values or not. .. Methods: - add_tag: adds a tag to visualize in the count table - count_scans: counts the number of scans depending on the selected tags and displays the result in the table - fill_first_tags: fills the cells of the table corresponding to the (n-1) first selected tags - fill_headers: fills the headers of the table depending on the selected tags - fill_last_tag: fills the cells corresponding to the last selected tag - fill_values: fill values_list depending on the visualized tags - prepare_filter: prepares the filter in order to fill the count table - refresh_layout: updates the layout of the widget - remove_tag: removes a tag to visualize in the count table - select_tag: opens a pop-up to select which tag to visualize in the count table :Example: Assume that the current project has scans for two patients (P1 and P2) and three time points (T1, T2 and T3). For each (patient, time point), several sequences have been made (two RARE, one MDEFT and one FLASH). Selecting [PatientName, TimePoint, SequenceName] as tags, the table will be: +-------------+-----------+------+-------+-------+ | PatientName | TimePoint | RARE | MDEFT | FLASH | +=============+===========+======+=======+=======+ | P1 | T1 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P1 | T2 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P1 | T3 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P2 | T1 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P2 | T2 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P2 | T3 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ with v(n) meaning that n scans corresponds of the selected values for (PatientName, TimePoint,SequenceName). If no scans corresponds for a triplet value, a red cross will be displayed. For example, if the user forgets to import one RARE for P1 at T2 and one FLASH for P2 at T3. The table will be: +-------------+-----------+------+-------+-------+ | PatientName | TimePoint | RARE | MDEFT | FLASH | +=============+===========+======+=======+=======+ | P1 | T1 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P1 | T2 | v(1) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P1 | T3 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P2 | T1 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P2 | T2 | v(2) | v(1) | v(1) | +-------------+-----------+------+-------+-------+ | P2 | T3 | v(2) | v(1) | x | +-------------+-----------+------+-------+-------+ Thus, thanks to the CountTable tool, he or she directly knows if some scans are missing. """ def __init__(self, project): """ Initialization of the Count Table :param project: current project in the software """ super().__init__() self.project = project # Issue #147: Allow to interact with database while the popup is open # self.setModal(True) self.setWindowTitle("Count table") # Font self.font = QFont() self.font.setBold(True) # values_list will contain the different values of each selected tag self.values_list = [[], []] self.label_tags = QLabel('Tags: ') # Each push button will allow the user to add a tag to the count table push_button_tag_1 = QPushButton() push_button_tag_1.setText("Tag n°1") push_button_tag_1.clicked.connect(lambda: self.select_tag(0)) push_button_tag_2 = QPushButton() push_button_tag_2.setText("Tag n°2") push_button_tag_2.clicked.connect(lambda: self.select_tag(1)) # The list of all the push buttons # (the user can add as many as he or she wants) self.push_buttons = [] self.push_buttons.insert(0, push_button_tag_1) self.push_buttons.insert(1, push_button_tag_2) # Labels to add/remove a tag (a push button) sources_images_dir = Config().getSourceImageDir() self.remove_tag_label = ClickableLabel() remove_tag_picture = QPixmap( os.path.relpath(os.path.join(sources_images_dir, "red_minus.png"))) remove_tag_picture = remove_tag_picture.scaledToHeight(20) self.remove_tag_label.setPixmap(remove_tag_picture) self.remove_tag_label.clicked.connect(self.remove_tag) self.add_tag_label = ClickableLabel() self.add_tag_label.setObjectName('plus') add_tag_picture = QPixmap( os.path.relpath(os.path.join(sources_images_dir, "green_plus.png"))) add_tag_picture = add_tag_picture.scaledToHeight(15) self.add_tag_label.setPixmap(add_tag_picture) self.add_tag_label.clicked.connect(self.add_tag) # Push button that is pressed to launch the computations self.push_button_count = QPushButton() self.push_button_count.setText('Count scans') self.push_button_count.clicked.connect(self.count_scans) # The table that will be filled self.table = QTableWidget() # Layouts self.v_box_final = QVBoxLayout() self.setLayout(self.v_box_final) self.refresh_layout() def add_tag(self): """ Adds a tag to visualize in the count table """ idx = len(self.push_buttons) push_button = QPushButton() push_button.setText('Tag n°' + str(len(self.push_buttons) + 1)) push_button.clicked.connect(lambda: self.select_tag(idx)) self.push_buttons.insert(len(self.push_buttons), push_button) self.refresh_layout() def count_scans(self): """Counts the number of scans depending on the selected tags and displays the result in the table """ for tag_values in self.values_list: if len(tag_values) == 0: return if self.project.session.get_field( COLLECTION_CURRENT, self.push_buttons[-1].text()) is None: return # Clearing the table self.table.clear() # nb_values will contain, for each index, the number of # different values that a tag can take self.nb_values = [] for values in self.values_list: self.nb_values.append(len(values)) # The number of rows will be the multiplication of all these # values self.nb_row = reduce(operator.mul, self.nb_values[:-1], 1) # The number of columns will be the addition of the number of # selected tags (minus 1) and the number of different values # that can take the last selected tag self.nb_col = len(self.values_list) - 1 + self.nb_values[-1] self.table.setRowCount(self.nb_row) self.table.setColumnCount(self.nb_col) self.fill_headers() self.fill_first_tags() self.fill_last_tag() self.table.resizeColumnsToContents() def fill_first_tags(self): """Fills the cells of the table corresponding to the (n-1) first selected tags """ cell_text = [] for col in range(len(self.values_list) - 1): # cell_text will contain the n-1 element to display cell_text.append(self.values_list[col][0]) # Filling the last "Total" column item = QTableWidgetItem() item.setText(str(self.nb_values[col])) item.setFont(self.font) self.table.setItem(self.nb_row, col, item) # Filling the cells of the n-1 first tags for row in range(self.nb_row): for col in range(len(self.values_list) - 1): item = QTableWidgetItem() tag_name = self.push_buttons[col].text() tag_type = self.project.session.get_field( COLLECTION_CURRENT, tag_name).field_type set_item_data(item, cell_text[col], tag_type) self.table.setItem(row, col, item) # Looping from the (n-1)th tag col_checked = len(self.values_list) - 2 # Flag up will be True when all values of the tag # have been iterated flag_up = False while col_checked >= 0: if flag_up: # In this case, the value of the right column has # reach its last value # This value has been reset to the first value if (cell_text[col_checked] == self.values_list[col_checked] [-1]): # If the value that has been displayed is the # last one, the flag stays the same, the value of # the column on the left has to be changed cell_text[col_checked] = self.values_list[col_checked][ 0] else: # Else we iterate on the next value idx = self.values_list[col_checked].index( cell_text[col_checked]) cell_text[col_checked] = self.values_list[col_checked][ idx + 1] flag_up = False if (col_checked > 0 and len(self.values_list) - 1 > 1) or ( len(self.values_list) - 1 == 1): if cell_text[col_checked] == self.values_list[col_checked][ -1]: # If the value that has been displayed is the last one, # the flag is set to True, the value of the column # on the left has to be changed cell_text[col_checked] = self.values_list[col_checked][ 0] flag_up = True else: # Else we iterate on the next value and reset the flag idx = self.values_list[col_checked].index( cell_text[col_checked]) cell_text[col_checked] = self.values_list[col_checked][ idx + 1] flag_up = False if not flag_up: # If there is nothing to do, we quit the loop break col_checked -= 1 def fill_headers(self): """ Fills the headers of the table depending on the selected tags """ idx_end = 0 # Headers for idx in range(len(self.values_list) - 1): header_name = self.push_buttons[idx].text() item = QTableWidgetItem() item.setText(header_name) self.table.setHorizontalHeaderItem(idx, item) idx_end = idx # idx_last_tag corresponds to the index of the (n-1)th tag self.idx_last_tag = idx_end last_tag = self.push_buttons[len(self.values_list) - 1].text() last_tag_type = self.project.session.get_field(COLLECTION_CURRENT, last_tag).field_type for header_name in self.values_list[-1]: idx_end += 1 item = QTableWidgetItem() set_item_data(item, header_name, last_tag_type) self.table.setHorizontalHeaderItem(idx_end, item) # Adding a "Total" row and to count the scans self.table.insertRow(self.nb_row) item = QTableWidgetItem() item.setText('Total') item.setFont(self.font) self.table.setVerticalHeaderItem(self.nb_row, item) def fill_last_tag(self): """ Fills the cells corresponding to the last selected tag """ # Cells of the last tag for col in range(self.idx_last_tag + 1, self.nb_col): nb_scans_ok = 0 # Creating a tag_list that will contain # couples tag_name/tag_value that # will then querying the Database for row in range(self.nb_row): tag_list = [] for idx_first_columns in range(self.idx_last_tag + 1): tag_name = self.table.horizontalHeaderItem( idx_first_columns).text() tag_type = self.project.session.get_field( COLLECTION_CURRENT, tag_name).field_type value_str = self.table.item(row, idx_first_columns).data( Qt.EditRole) value_database = table_to_database(value_str, tag_type) tag_list.append([tag_name, value_database]) tag_last_columns = self.push_buttons[-1].text() tag_last_columns_type = self.project.session.get_field( COLLECTION_CURRENT, tag_last_columns).field_type value_last_columns_str = self.table.horizontalHeaderItem( col).data(Qt.EditRole) value_last_columns_database = table_to_database( value_last_columns_str, tag_last_columns_type) tag_list.append( [tag_last_columns, value_last_columns_database]) item = QTableWidgetItem() item.setFlags(QtCore.Qt.ItemIsEnabled) # Getting the list of the scans that corresponds to the couples # tag_name/tag_values generator_scans = self.project.session.filter_documents( COLLECTION_CURRENT, self.prepare_filter(tag_list)) # List of scans created, given the generator list_scans = [ getattr(scan, TAG_FILENAME) for scan in generator_scans ] sources_images_dir = Config().getSourceImageDir() if list_scans: icon = QIcon( os.path.join(sources_images_dir, 'green_v.png')) length = len(list_scans) nb_scans_ok += length text = str(length) item.setText(text) tool_tip = '' # Setting as tooltip all the corresponding scans for tpl in list_scans: tool_tip += (tpl + '\n') tool_tip = tool_tip[:-1] item.setToolTip(tool_tip) else: icon = QIcon( os.path.join(sources_images_dir, 'red_cross.png')) item.setIcon(icon) self.table.setItem(row, col, item) item = QTableWidgetItem() item.setText(str(nb_scans_ok)) item.setFont(self.font) self.table.setItem(self.nb_row, col, item) def fill_values(self, idx): """ Fill values_list depending on the visualized tags :param idx: index of the select tag """ tag_name = self.push_buttons[idx].text() values = [] for scan in self.project.session.get_documents_names( COLLECTION_CURRENT): current_value = self.project.session.get_value( COLLECTION_CURRENT, scan, tag_name) if current_value is not None: values.append(current_value) idx_to_fill = len(self.values_list) while len(self.values_list) <= idx: self.values_list.insert(idx_to_fill, []) idx_to_fill += 1 if self.values_list[idx] is not None: self.values_list[idx] = [] for value in values: if value not in self.values_list[idx]: self.values_list[idx].append(value) @staticmethod def prepare_filter(couples): """ Prepares the filter in order to fill the count table :param couples: (tag, value) couples :return: Str query of the corresponding filter """ query = "" and_to_write = False for couple in couples: tag = couple[0] value = couple[1] # No AND for the first condition if and_to_write: query += " AND " and_to_write = True if isinstance(value, list): query += "({" + tag + "} == " + str(value) + ")" else: query += "({" + tag + "} == \"" + str(value) + "\")" query = "(" + query + ")" return query def refresh_layout(self): """ Updates the layout of the widget """ self.h_box_top = QHBoxLayout() self.h_box_top.setSpacing(10) self.h_box_top.addWidget(self.label_tags) for tag_label in self.push_buttons: self.h_box_top.addWidget(tag_label) self.h_box_top.addWidget(self.add_tag_label) self.h_box_top.addWidget(self.remove_tag_label) self.h_box_top.addWidget(self.push_button_count) self.h_box_top.addStretch(1) self.v_box_final.addLayout(self.h_box_top) self.v_box_final.addWidget(self.table) def remove_tag(self): """ Removes a tag to visualize in the count table """ push_button = self.push_buttons[-1] push_button.deleteLater() push_button = None del self.push_buttons[-1] del self.values_list[-1] self.refresh_layout() def select_tag(self, idx): """ Opens a pop-up to select which tag to visualize in the count table :param idx: the index of the selected push button """ pop_up = PopUpSelectTagCountTable( self.project, self.project.session.get_fields_names(COLLECTION_CURRENT), self.push_buttons[idx].text()) if pop_up.exec_(): if pop_up.selected_tag is not None: self.push_buttons[idx].setText(pop_up.selected_tag) self.fill_values(idx)
def setupUi(self, MainWindow): resolution = QDesktopWidget().screenGeometry(self) # MainWindow.setGeometry(QRect(0,0,0,0)) MainWindow.setFixedSize(resolution.size().width()*0.99, resolution.size().height()*0.90)#1200 800 # self.setWindowState(Qt.WindowMaximized) print("resol : ", MainWindow.size()) #메인 화면 색상py self.setStyleSheet("color: black;" "background-color: white;") font = QFont() font.setFamily("NanumGothic") MainWindow.setFont(font) self.centralwidget = QWidget(MainWindow) self.label = QLabel(self.centralwidget) self.label.setGeometry(QRect(20, 20, 130, 35)) font = QFont() font.setFamily("NanumGothic") font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.button_add = QPushButton(self.centralwidget) self.button_add.setGeometry(QRect(MainWindow.size().width()*0.05, MainWindow.size().height() - 80, 131, 34)) #버튼 스타일 변경 self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_add.setFont(staticValues.buttonFont) self.button_modi = QPushButton(self.centralwidget) self.button_modi.setGeometry(QRect(MainWindow.size().width()*0.20, MainWindow.size().height() - 80, 131, 34)) self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_modi.setFont(staticValues.buttonFont) self.button_del = QPushButton(self.centralwidget) self.button_del.setGeometry(QRect(MainWindow.size().width()*0.35, MainWindow.size().height() - 80, 131, 34)) self.button_del.setStyleSheet(staticValues.redButtonStyleSheet) self.button_del.setFont(staticValues.buttonFont) self.button_upload = QPushButton(self.centralwidget) self.button_upload.setGeometry(QRect(MainWindow.size().width()*0.7, MainWindow.size().height() - 80, 131, 34)) self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_upload.setFont(staticValues.buttonFont) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QRect(10, 70, MainWindow.size().width()-15, MainWindow.size().height() - 180)) self.tab = QWidget() self.tab.layout = QVBoxLayout() self.tabWidget.addTab(self.tab, "회원 목록") self.tableWidget = QTableWidget(self.tab) self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25)) self.tableWidget.setColumnCount(13) self.tableWidget.setRowCount(0) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근" , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"]) self.tab2 = QWidget() self.tab2.layout = QVBoxLayout() self.tabWidget.addTab(self.tab2, "중복 회원") self.label_updateDate = QLabel(self.tab2) self.label_updateDate.set self.tableWidget2 = QTableWidget(self.tab2) self.tableWidget2.setGeometry(QRect(0, 30, self.tabWidget.size().width()-5, self.tabWidget.size().height()-55)) self.tableWidget2.setColumnCount(3) self.tableWidget2.setRowCount(0) self.tableWidget2.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "현재 단톡방", "중복 단톡방"]) self.edit_search = QLineEdit(self.centralwidget) self.edit_search.setGeometry(QRect(MainWindow.size().width()-280, 35, 200, 30)) self.edit_search.setStyleSheet(staticValues.solidStyleSheet) self.button_search = QPushButton(self.centralwidget) self.button_search.setGeometry(QRect(MainWindow.size().width()-80, 35, 70, 30)) self.button_search.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_search.setFont(staticValues.buttonFont) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
def load(self, path): if path == self._path: return self._path = path with open(os.path.join(self._path, "theme.json")) as f: Logger.log("d", "Loading theme file: %s", os.path.join(self._path, "theme.json")) data = json.load(f) self._initializeDefaults() if "colors" in data: for name, color in data["colors"].items(): c = QColor(color[0], color[1], color[2], color[3]) self._colors[name] = c fontsdir = os.path.join(self._path, "fonts") if os.path.isdir(fontsdir): for file in os.listdir(fontsdir): if "ttf" in file: QFontDatabase.addApplicationFont( os.path.join(fontsdir, file)) if "fonts" in data: for name, font in data["fonts"].items(): f = QFont() f.setFamily( font.get("family", QCoreApplication.instance().font().family())) f.setBold(font.get("bold", False)) f.setLetterSpacing(QFont.AbsoluteSpacing, font.get("letterSpacing", 0)) f.setItalic(font.get("italic", False)) f.setPixelSize(font.get("size", 1) * self._em_height) f.setCapitalization(QFont.AllUppercase if font.get( "capitalize", False) else QFont.MixedCase) self._fonts[name] = f if "sizes" in data: for name, size in data["sizes"].items(): s = QSizeF() s.setWidth(round(size[0] * self._em_width)) s.setHeight(round(size[1] * self._em_height)) self._sizes[name] = s iconsdir = os.path.join(self._path, "icons") if os.path.isdir(iconsdir): for icon in os.listdir(iconsdir): name = os.path.splitext(icon)[0] self._icons[name] = QUrl.fromLocalFile( os.path.join(iconsdir, icon)) imagesdir = os.path.join(self._path, "images") if os.path.isdir(imagesdir): for image in os.listdir(imagesdir): name = os.path.splitext(image)[0] self._images[name] = QUrl.fromLocalFile( os.path.join(imagesdir, image)) styles = os.path.join(self._path, "styles.qml") if os.path.isfile(styles): c = QQmlComponent(self._engine, styles) context = QQmlContext(self._engine, self._engine) context.setContextProperty("Theme", self) self._styles = c.create(context) if c.isError(): for error in c.errors(): Logger.log("e", error.toString()) Logger.log("d", "Loaded theme %s", self._path) self.themeLoaded.emit()
def __init__(self, parent=None): super(Main_DB, self).__init__(parent) self.setWindowTitle("EXADATA") self.setFixedSize(800, 600) self.setWindowIcon(QIcon("icono.jpg")) self.centralwidget = QtWidgets.QWidget(self) self.centralwidget.setObjectName("centralwidget") # FRAME paleta = QPalette() paleta.setColor(QPalette.Background, QColor(51, 0, 102)) frame = QFrame(self) frame.setFrameShape(QFrame.NoFrame) frame.setFrameShadow(QFrame.Sunken) frame.setAutoFillBackground(True) frame.setPalette(paleta) frame.setFixedWidth(800) frame.setFixedHeight(100) frame.move(0, 0) labelIcono = QLabel(frame) labelIcono.setFixedWidth(65) labelIcono.setFixedHeight(65) labelIcono.setPixmap( QPixmap("icono.jpg").scaled(65, 65, Qt.KeepAspectRatio, Qt.SmoothTransformation)) labelIcono.move(10, 28) fuenteTitulo = QFont() fuenteTitulo.setPointSize(25) fuenteTitulo.setBold(True) labelTitulo = QLabel("<font color='white'>EXADATA</font>", frame) labelTitulo.setFont(fuenteTitulo) labelTitulo.move(85, 30) fuenteSubtitulo = QFont() fuenteSubtitulo.setPointSize(13) labelSubtitulo = QLabel("<font color='white'>Análisis de Tweets ", frame) labelSubtitulo.setFont(fuenteSubtitulo) labelSubtitulo.move(85, 68) #BARRA self.progressBar = QtWidgets.QProgressBar(self.centralwidget) self.progressBar.setGeometry(QtCore.QRect(10, 400, 375, 23)) self.progressBar.setProperty("value", 24) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") #inicio tabla self.tabla = QtWidgets.QTableWidget(self.centralwidget) self.tabla.setGeometry(QtCore.QRect(10, 110, 500, 400)) self.tabla.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.tabla.setSizeAdjustPolicy( QtWidgets.QAbstractScrollArea.AdjustToContents) self.tabla.setColumnCount(3) self.tabla.setObjectName("tabla") self.tabla.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(2, item) self.tabla.horizontalHeader().setDefaultSectionSize(165) self.tabla.horizontalHeader().setStretchLastSection(True) self.tabla.verticalHeader().setStretchLastSection(False) self.tabla.cellClicked.connect(self.clic) #fin tabla self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(510, 70, 151, 16)) self.label.setObjectName("label") #qlineedit nombre base self.input_nombre_bd = QtWidgets.QLineEdit(self.centralwidget) self.input_nombre_bd.setGeometry(QtCore.QRect(550, 130, 170, 20)) self.input_nombre_bd.setObjectName("input_nombre_bd") # label #label nombre_bd self.label_nombre_base = QtWidgets.QLabel(self.centralwidget) self.label_nombre_base.setGeometry(QtCore.QRect(550, 110, 180, 20)) self.label_nombre_base.setObjectName("label_nombre_base") # label editar_bd self.label_editar_bd = QtWidgets.QLabel(self.centralwidget) self.label_editar_bd.setGeometry(QtCore.QRect(550, 230, 180, 16)) self.label_editar_bd.setObjectName("label_editar_bd") # BOTONES #boton importar self.bt_importar = QtWidgets.QPushButton(self.centralwidget) self.bt_importar.setGeometry(QtCore.QRect(550, 160, 170, 21)) self.bt_importar.setObjectName("bt_importar") # boton agregar_bd self.bt_agregar_bd = QtWidgets.QPushButton(self.centralwidget) self.bt_agregar_bd.setGeometry(QtCore.QRect(550, 260, 170, 21)) self.bt_agregar_bd.setObjectName("bt_agregar_bd") self.bt_agregar_bd.clicked.connect(self.Anadir) # boton eliminar_bd self.bt_eliminar_bt = QtWidgets.QPushButton(self.centralwidget) self.bt_eliminar_bt.setGeometry(QtCore.QRect(550, 290, 170, 21)) self.bt_eliminar_bt.setObjectName("bt_eliminar_bt") self.bt_eliminar_bt.clicked.connect(self.BorrarTabla) # boton exportar_bd self.bt_exportar_bd = QtWidgets.QPushButton(self.centralwidget) self.bt_exportar_bd.setGeometry(QtCore.QRect(550, 320, 170, 21)) self.bt_exportar_bd.setObjectName("bt_exportar_bd") self.bt_exportar_bd.clicked.connect(self.ExportarBase) # boton recarga_bd self.bt_recarga_bd = QtWidgets.QPushButton(self.centralwidget) self.bt_recarga_bd.setGeometry(QtCore.QRect(10, 520, 500, 21)) self.bt_recarga_bd.setObjectName("bt_recarga_bd") self.bt_recarga_bd.clicked.connect(self.CargarTabla) #================================================================================= self.setCentralWidget(self.centralwidget) # BARRA MENU self.menubar = QtWidgets.QMenuBar(self) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName("menubar") self.Programas = QtWidgets.QMenu(self.menubar) self.BaseDeDatos = QtWidgets.QAction(self) self.menubar.addAction(self.Programas.menuAction()) self.Programas.addAction(self.BaseDeDatos) self.Ayuda = QtWidgets.QMenu(self.menubar) self.SobreQue = QtWidgets.QAction(self) self.menubar.addAction(self.Ayuda.menuAction()) self.Ayuda.addAction(self.SobreQue) self.retranslateUi() self.tabla_master() self.CargarTabla() self.progressBar.hide()
class RmsFrame(QFrame): def __init__(self, cu): super().__init__() self.cu = cu self.session = RaceSession() self.resetRMS() self.buildframe() self.driverBtn = {} self.driverObj = {} self.lapcount = {} self.totalTime = {} self.laptime = {} self.bestlaptime = {} self.fuelbar = {} self.pits = {} # QBAcolor = QByteArray() # QBAcolor.append('color') # self.animation = anim = QPropertyAnimation(self, QBAcolor, self) # anim.setDuration(250) # anim.setLoopCount(2) # anim.setStartValue(QColor(230,230, 0)) # anim.setEndValue(QColor(0, 0, 0)) # anim.setKeyValueAt(0.5, QColor(150,100,0)) def buildframe(self): self.vLayout = QVBoxLayout(self) self.hBtnLayout = QHBoxLayout() self.vLayout.addLayout(self.hBtnLayout) # Add driver to grid self.addDriverBtn = QPushButton('(A)dd Driver') self.addDriverKey = QShortcut(QKeySequence("a"), self) self.hBtnLayout.addWidget(self.addDriverBtn) self.addDriverBtn.clicked.connect(self.addDriver) self.addDriverKey.activated.connect(self.addDriver) # Assign Controller self.assignCtrlBtn = QPushButton('Assign Controller') self.hBtnLayout.addWidget(self.assignCtrlBtn) self.assignCtrlBtn.clicked.connect(self.openCtrlDialog) # Setup a race self.setupRace = QPushButton('Setup a Race') self.hBtnLayout.addWidget(self.setupRace) self.setupRace.clicked.connect(self.openRaceDlg) # Code cars self.codeBtn = QPushButton('(C)ode') self.codeKey = QShortcut(QKeySequence("c"), self) self.hBtnLayout.addWidget(self.codeBtn) self.codeBtn.clicked.connect(self.pressCode) self.codeKey.activated.connect(self.pressCode) # Start pace car self.paceBtn = QPushButton('(P)ace') self.paceKey = QShortcut(QKeySequence("p"), self) self.hBtnLayout.addWidget(self.paceBtn) self.paceBtn.clicked.connect(self.setPace) self.paceKey.activated.connect(self.setPace) # set Speed self.setSpeedBtn = QPushButton('Set (S)peed') self.setSpeedKey = QShortcut(QKeySequence("s"), self) self.hBtnLayout.addWidget(self.setSpeedBtn) self.setSpeedBtn.clicked.connect(self.setSpeed) self.setSpeedKey.activated.connect(self.setSpeed) # set Brakes self.setBrakeBtn = QPushButton('Set (B)rake') self.setBrakeKey = QShortcut(QKeySequence("b"), self) self.hBtnLayout.addWidget(self.setBrakeBtn) self.setBrakeBtn.clicked.connect(self.setBrake) self.setBrakeKey.activated.connect(self.setBrake) # Set Fuel self.setFuelBtn = QPushButton('Set (F)uel') self.setFuelKey = QShortcut(QKeySequence("f"), self) self.hBtnLayout.addWidget(self.setFuelBtn) self.setFuelBtn.clicked.connect(self.setFuel) self.setFuelKey.activated.connect(self.setFuel) # Reset CU self.resetBtn = QPushButton('(R)eset') self.resetKey = QShortcut(QKeySequence("r"), self) self.hBtnLayout.addWidget(self.resetBtn) self.resetBtn.clicked.connect(self.resetRMS) self.resetKey.activated.connect(self.resetRMS) # Start/Pause Race Enter self.startRaceBtn = QPushButton( 'Start Race or Enter changed Settings (Spacebar)') self.startRaceBtn.clicked.connect(self.racestart) self.spacekey = QShortcut(QKeySequence("Space"), self) self.spacekey.activated.connect(self.racestart) self.hStartBtnLayout = QHBoxLayout() self.hStartBtnLayout.addStretch(1) self.hStartBtnLayout.addWidget(self.startRaceBtn) self.hStartBtnLayout.setAlignment(self.startRaceBtn, Qt.AlignHCenter) self.hStartBtnLayout.addStretch(1) self.pitLaneStatus = QLabel() self.hStartBtnLayout.addWidget(QLabel('Pitlane')) self.hStartBtnLayout.addWidget(self.pitLaneStatus) self.fuelmode = QLabel() self.hStartBtnLayout.addWidget(QLabel('Fuel Mode')) self.hStartBtnLayout.addWidget(self.fuelmode) self.lapCounter = QLabel() self.hStartBtnLayout.addWidget(QLabel('Lap Counter')) self.hStartBtnLayout.addWidget(self.lapCounter) self.vLayout.addLayout(self.hStartBtnLayout) self.vLayout.setAlignment(self.hStartBtnLayout, Qt.AlignTop) # self.sepline = QFrame() # self.sepline.setFrameShape(QFrame.HLine) # self.sepline.setFrameShadow(QFrame.Sunken) # self.vLayout.addWidget(self.sepline) # self.vLayout.setAlignment(self.sepline, Qt.AlignTop) # Driver Grid self.vLayout.addLayout(self.buildGrid()) # Session Info self.racemode = QLabel('No Race Started') self.racemode.setAlignment(Qt.AlignCenter) self.racemode.setStyleSheet( "QLabel{ border-radius: 10px; background-color: grey; center; color: blue; font: 30pt}" ) self.vLayout.addWidget(self.racemode) self.vLayout.setAlignment(self.racemode, Qt.AlignBottom) def buildGrid(self): self.mainLayout = QGridLayout() self.mainLayout.setSpacing(10) self.mainLayout.setHorizontalSpacing(10) self.headerFont = QFont() self.headerFont.setPointSize(14) self.headerFont.setBold(True) self.labelArr = [ 'Pos', 'Driver', 'Total', 'Laps', 'Laptime', 'Best Lap', 'Fuel', 'Pits' ] for index, label in enumerate(self.labelArr): self.headerLabel = QLabel(label) self.headerLabel.setFont(self.headerFont) self.mainLayout.addWidget(self.headerLabel, 0, index, Qt.AlignHCenter) self.mainLayout.setColumnStretch(1, 1) self.mainLayout.setColumnStretch(2, 1) self.mainLayout.setColumnStretch(3, 2) self.mainLayout.setColumnStretch(4, 3) self.mainLayout.setColumnStretch(5, 3) self.mainLayout.setColumnStretch(6, 2) self.mainLayout.setColumnStretch(7, 1) return self.mainLayout def openCtrlDialog(self): self.ctrlDialog = CtrlDialog(self.driverArr) if self.ctrlDialog.exec_(): self.driverArr = self.ctrlDialog.newDriverArr def openRaceDlg(self): self.setupRaceDlg = RaceModeDialog() self.session.session = None self.session.type = None if self.setupRaceDlg.exec_(): for driver in self.driverArr: driver.bestLapTime = None driver.time = None driver.lapcount = 0 driver.pitcount = 0 self.session.setRace(self.setupRaceDlg.getRaceModeInfo()) self.racemode.setText(self.session.session + ' ' + str(self.session.amount) + ' ' + self.session.type) self.clearCU() self.cu.start() else: self.setupRaceDlg.close() def getColor(self): if self.mainLayout.itemAtPosition(1, 1): return self.mainLayout.itemAtPosition(1, 1).widget().palette().text() else: return None def setColor(self, color): PBwidget = self.mainLayout.itemAtPosition(1, 1).widget() palette = PBwidget.palette() palette.setColor(PBwidget.foregroundRole(), color) PBwidget.setFlat(True) PBwidget.setAutoFillBackground(True) PBwidget.setPalette(palette) color = pyqtProperty(QColor, getColor, setColor) def addDriver(self): driverRow = self.mainLayout.rowCount() if driverRow > 8: return driver = self.driverArr[driverRow - 1] self.posFont = QFont() self.posFont.setPointSize(35) self.posFont.setBold(True) self.driverPos = QLabel(str(driverRow)) self.driverPos.setStyleSheet( "QLabel{ border-radius: 10px; border-color: black; border: 5px solid black; background-color: white}" ) self.driverPos.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) self.driverPos.setFont(self.posFont) self.mainLayout.addWidget(self.driverPos, driverRow, 0) self.driverBtn[driverRow] = driver.getNameBtn() self.driverBtn[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.mainLayout.addWidget(self.driverBtn[driverRow], driverRow, 1) self.driverObj[driverRow] = driver self.driverBtn[driverRow].clicked.connect(lambda: self.changeDriver( self.driverBtn[driverRow], self.driverObj[driverRow])) self.lapcount[driverRow] = driver.getLapCountLCD() self.lapcount[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.mainLayout.addWidget(self.lapcount[driverRow], driverRow, 3) self.totalFont = QFont() self.totalFont.setPointSize(25) self.totalFont.setBold(True) self.totalTime[driverRow] = QLabel('00:00') self.totalTime[driverRow].setStyleSheet( "QLabel{ border-radius: 10px; border-color: black; border: 5px solid black; background-color: white}" ) self.totalTime[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.totalTime[driverRow].setFont(self.totalFont) self.mainLayout.addWidget(self.totalTime[driverRow], driverRow, 2) self.laptime[driverRow] = driver.getLapLCD() self.laptime[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.mainLayout.addWidget(self.laptime[driverRow], driverRow, 4) self.bestlaptime[driverRow] = driver.getBestLapLCD() self.bestlaptime[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.mainLayout.addWidget(self.bestlaptime[driverRow], driverRow, 5) self.fuelbar[driverRow] = driver.getFuelBar() self.fuelbar[driverRow].setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) self.mainLayout.addWidget(self.fuelbar[driverRow], driverRow, 6) self.pits[driverRow] = driver.getPits() self.pits[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.mainLayout.addWidget(self.pits[driverRow], driverRow, 7) def racestart(self): self.cu.start() # self.mainLayout.itemAtPosition(1, 5).widget().setPits('Pit') # self.mainLayout.itemAtPosition(1, 5).widget().setPits('Track') def resetRMS(self): if hasattr(self, 'driverArr'): for driverObj in self.driverArr: driverObj.deleteLater() self.start = None self.driverArr = [RmsDriver(num) for num in range(1, 9)] self.clearCU() if hasattr(self, 'mainLayout'): while True: widgetToRemove = self.mainLayout.takeAt(0) if widgetToRemove == None: break widgetToRemove.widget().deleteLater() racemode = self.vLayout.takeAt(3) mainItem = self.vLayout.takeAt(2) self.vLayout.removeItem(racemode) self.vLayout.removeItem(mainItem) mainItem.deleteLater() self.vLayout.addLayout(self.buildGrid()) self.vLayout.addWidget(self.racemode) def clearCU(self): # discard remaining timer messages status = self.cu.request() while not isinstance(status, ControlUnit.Status): status = self.cu.request() self.status = status # reset cu timer self.cu.reset() def pressCode(self): print('press Code') self.cu.request(b'T8') def setFuel(self): print('set fuel') self.cu.request(b'T7') def setPace(self): print('pace car') self.cu.request(b'T1') def setSpeed(self): print('set speed') self.cu.request(b'T5') def setBrake(self): print('set brake') self.cu.request(b'T6') def changeDriver(self, driverButton, driverObj): self.driverChangeText = QInputDialog.getText( self, 'Change driver name', 'Driver Name', 0, driverButton.text().split('\n')[0]) if self.driverChangeText[1] == True: driverButton.setText(self.driverChangeText[0] + '\n' + 'Ctrl: ' + str(driverObj.CtrlNum)) driverObj.name = self.driverChangeText[0] def updateDisplay(self, binMode): if binMode != None: if binMode[2] == '1': self.fuelmode.setText('Real') elif binMode[3] == '1': self.fuelmode.setText('On') elif binMode[3] == '0': self.fuelmode.setText('Off') if binMode[1] == '1': self.pitLaneStatus.setText('Exists') else: self.pitLaneStatus.setText('Missing') if binMode[0] == '1': self.lapCounter.setText('Exists') else: self.lapCounter.setText('Missing') driversInPlay = [driver for driver in self.driverArr if driver.time] if len(driversInPlay) + 1 > self.mainLayout.rowCount(): self.addDriver() for pos, driver in enumerate(sorted(driversInPlay, key=posgetter), start=1): if pos == 1: if hasattr(self, 'leader') and self.leader != driver: print('pos change') # self.animation.start() self.leader = driver t = formattime(driver.time - self.start, True) elif driver.lapcount == self.leader.lapcount: t = '+%ss' % formattime(driver.time - self.leader.time) else: gap = self.leader.lapcount - driver.lapcount t = '+%d Lap%s' % (gap, 's' if gap != 1 else '') self.driverBtn[pos].setText(driver.name + '\n' + 'Ctrl: ' + str(driver.CtrlNum)) self.totalTime[pos].setText(t) self.lapcount[pos].display(driver.lapcount) self.laptime[pos].display(formattime(driver.lapTime)) self.bestlaptime[pos].display(formattime(driver.bestLapTime)) self.fuelbar[pos].setValue(driver.fuellevel) if driver.fuellevel > 0: self.fuelbar[pos].setStyleSheet( "QProgressBar{ color: white; background-color: black; border: 5px solid black; border-radius: 10px; text-align: center}\ QProgressBar::chunk { background: qlineargradient(x1: 1, y1: 0.5, x2: 0, y2: 0.5, stop: 0 #00AA00, stop: " + str(0.92 - (1 / (driver.fuellevel))) + " #22FF22, stop: " + str(0.921 - (1 / (driver.fuellevel))) + " #22FF22, stop: " + str(1.001 - (1 / (driver.fuellevel))) + " red, stop: 1 #550000); }") self.pits[pos].display(driver.pitcount) if hasattr(self, 'leader') and self.session.session != None: if self.session.type != None: self.racemode.setText(self.session.session + ' ' + str(self.session.amount) + ' ' + self.session.type) if self.session.type == 'Laps': if self.leader.lapcount > self.session.amount: self.racestart() self.session.saveSessionData(driversInPlay) self.clearCU() self.session.sessionOver() elif self.session.type == 'Timed': if self.leader.time - self.start > self.session.amount * 60000: self.racestart() self.session.saveSessionData(driversInPlay) self.clearCU() self.session.sessionOver() elif self.session.type == None: self.session.session = None self.showLeaderboard() def showLeaderboard(self): self.leaderBoard = LBDialog(self.session.leaderboard) self.leaderBoard.show()
class StartTuto(QDialog): def __init__(self): super(StartTuto, self).__init__() QDialog.__init__(self) self.Next = 0 self.setWindowFlags(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowTitle("لنتعلم معا") self.font = QFont('abdo salem') self.font.setPointSize(20) self.font.setBold(True) self.ex = QPushButton(self) self.ex.setFont(self.font) self.ex.setGeometry(400 + 80, 450, 150, 50) self.ex.setText('خروج') self.ex.setStyleSheet( "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n" "") self.ex.clicked.connect(self.Exit) self.hm = QPushButton(self) self.hm.setFont(self.font) self.hm.setGeometry(200 + 80, 450, 150, 50) self.hm.setText('الرئيسية') self.hm.setStyleSheet( "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n" "") self.hm.clicked.connect(self.home) self.resize(925, 500) self.Ind = [ 'data', 'if', 'for', 'while', 'def', 'class', 'oop', 'exp', 'prj2', 'prj3', 'st' ] self.names = { 'home': [ 'المتغير و\n أنواع البيانات', 'الجملة الشرطية\nIF', 'حلقة التقسيم\nFOR', 'حلقة مادام\nWHILE', 'الدالة\nDEF', 'الفئة\nClass', 'البرمجة كائنية\nالتوجه OOP', 'العبارات', 'المشروع الاول\nRANGE', 'المشروع الثاني\nStr', 'ابدء' ], 'data': [ 'المتغير', 'الأحرف ', 'الأرقام ', 'القائمة', 'القاموس', 'الخطأ\nالصحيح', 'دوال \nانواع البيانات', 'الأمثلة' ], 'if': [ 'الجملة الشرطية\nIF', 'ادوات المقارنة', 'استعمالات\n ELIF و ELSE' ], 'for': ['فكرة \nFOR', 'استعمالات \nFOR', 'امثلة'], 'while': ['فكرة \nWHILE', 'استعمالات \nWHILE', 'امثلة'], 'def': [ 'دالة بسيطة', 'arg\nدالة مع', '*arg\nدالة مع', 'دالة مع\n**kwargs' ], 'class': ['فئة بسيطة\n مع متغير', 'فئة بسيطة\n مع دالة'], 'oop': ['البناء\n__init__', 'خاصية الاراثة', 'دالة\nsuper()'], 'exp': ['عبارة\nreturn', 'عبارة\nassert', 'عبارة\nyield'], 'prj2': ['المشروع'], 'prj3': ['محاكات\nCount', 'محاكات\nFind', 'تطوير\nFind'], 'st': 'exit' } self.Home() def Home(self): self.items = [] for i in range(len(self.names['home'])): item = QPushButton(self) item.setText(self.names['home'][i]) item.setGeometry(395, 350, 120, 80) item.setStyleSheet( "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n" "") self.font.setPointSize(15) item.setFont(self.font) self.items.append(item) exec("""item.clicked.connect(partial(self.IND,i=%i))""" % (i)) self.rootState = QState() self.tiledState = QState(self.rootState) self.centeredState = QState(self.rootState) for i, item in enumerate(self.items): self.tiledState.assignProperty( item, 'pos', QPointF(((i % 6) * 5.3) * 30, ((i // 6) * 5.3) * 30)) self.centeredState.assignProperty(item, 'pos', QPointF()) self.states = QStateMachine() self.states.addState(self.rootState) self.states.setInitialState(self.rootState) self.rootState.setInitialState(self.centeredState) self.group = QParallelAnimationGroup() for i, item in enumerate(self.items): anim = QPropertyAnimation(item, b'pos') anim.setStartValue(QPoint(400, 300)) anim.setDuration(750 + i * 25) anim.setEasingCurve(QEasingCurve.InOutBack) self.group.addAnimation(anim) for u in self.items: trans = self.rootState.addTransition(u.clicked, self.tiledState) trans.addAnimation(self.group) self.states.start() def Exit(self): open('Files/choice', 'w').write('exit') self.close() def home(self): open('Files/choice', 'w').write('home') self.close() def IND(self, i): open('Files/choice', 'a').write(str(i)) if self.Next != 2: self.Next += 1 if self.names[self.Ind[i]] != 'exit': a = self.names[self.Ind[i]] k = 0 for i in self.items[0:len(a)]: i.setText(a[k]) k += 1 for i in self.items[len(a):]: i.hide() else: self.items[-1].hide() else: self.close()
def setupUi(self, Form): screen = QApplication.primaryScreen() size = screen.size() self.w = size.width() self.h = size.height() Form.setObjectName("Form") Form.resize(self.w * 0.682284, self.h * 0.838541) Form.setWindowFlags(Qt.FramelessWindowHint) self.setWindowIcon(QIcon('icons/icon.png')) self.tabWidget_2 = QTabWidget(self) self.tabWidget_2.setGeometry( QRect(0, 0, self.w * 0.674231, self.h * 0.183593)) self.tabWidget_2.setObjectName("tabWidget_2") self.tabWidget = QTabWidget(Form) self.tabWidget.setGeometry( QRect(0, 40, self.w * 0.674231, self.h * 0.769531)) self.ind, self.indi, self.fileo = 0, 0, 1 self.setStyleSheet( "QWidget{background-color: rgb(65, 65, 65);}\nQTabWidget::tab-bar {\n" " background-color: #fff;\n" " icon-position: relative;\n" "}\n" " QTabBar::tab {\n" " background-color:#323232;\n" " border-color: rgb(50, 50, 50);\n" " font: bold 12px \'Arial\';\n" " color: white;\n" " height:40px;\n" " width:170px;\n" "\n" " } \n" "QTabBar::tab:!selected {\n" " background-color:rgb(50, 50, 50);\n" " color: white;\n" " icon-position: center;\n" " }\n" "\n" "QTabBar::tab:hover {\n" " background-color: rgb(60, 60, 60);\n" " color: white;\n" " icon-position: left;\n" " }\n" "\n" "\n" " QTabWidget::pane { \n" " position: absolute;\n" " }\n" "\n" "QTabBar::tab:selected {\n" " background-color:rgb(35, 35, 35);\n" " color: white;\n" "}\n" "QTabBar::close-button {\n" " image: url(icons/close.png)\n" " }") self.tabWidget.setTabsClosable(True) self.tabWidget.setMovable(True) self.tabWidget.setObjectName("tabWidget") self.tab_2 = QWidget() self.tab_2.setObjectName("tab_2") self.tabWidget_2 = QTabWidget(self) self.tabWidget_2.setGeometry( QRect(0, 490, self.w * 0.674231, self.w * 5.446808)) self.tabWidget_2.setObjectName("tabWidget_2") self.tabWidget_2.setTabsClosable(True) self.tabWidget_2.setMovable(True) self.tab = QWidget() self.tab.setObjectName("tab") self.groupBox = QGroupBox(Form) self.groupBox.setGeometry( QRect(0, 0, self.w * 0.688872, self.h * 0.053385)) self.groupBox.setStyleSheet( "QGroupBox {\n" " background-color: rgb(50, 50, 50);\n" " border: 0.5px rgb(50, 50, 50);\n" " font: bold 12px \'Arial\';\n" " color: white;\n" " } \n" "QPushButton:hover{color:black;background-color: black;border:5px solid rgb(35, 35, 35);}\n" "QPushButton{color:white;background-color: rgb(55, 55, 55);border:0.3px solid rgb(50, 50, 50);}QPushButton:pressed{color:black;background-color: rgb(79, 79, 79);;border: rgb(50, 50, 50);}\n" "\n" "") self.groupBox.setObjectName("groupBox") self.clrq = QColor(0, 0, 0) self.shadow = QGraphicsDropShadowEffect(blurRadius=100, xOffset=5, yOffset=5) self.shadow.setColor(self.clrq) self.groupBox.setGraphicsEffect(self.shadow) self.btn = [] self.pushButton = QPushButton(self.groupBox) self.btn.append(self.pushButton) self.pushButton.setGeometry(QRect(900, 7, 28, 28)) font = QFont() font.setPointSize(12) font.setBold(True) font.setWeight(75) self.pushButton.setFont(font) self.pushButton.setStyleSheet( "QPushButton:hover{background-color:rgb(132, 0, 0);border:5px solid rgb(132, 0, 0);}\n" "QPushButton{background-color: rgb(50, 50, 50);border:0.3px solid rgb(50, 50, 50);}QPushButton:pressed{background-color:rgb(170, 0, 0);border: rgb(50, 50, 50);}\n" "") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QPushButton(self.groupBox) self.btn.append(self.pushButton_2) self.pushButton_2.setGeometry(QRect(870, 7, 28, 28)) font = QFont() font.setPointSize(20) font.setBold(True) font.setWeight(75) self.pushButton_2.setFont(font) self.pushButton_2.setStyleSheet( "QPushButton:hover{background-color:rgb(0, 118, 0);border:5px solid rgb(0, 118, 0);}\n" "QPushButton{background-color: rgb(50, 50, 50);border:0.3px solid rgb(50, 50, 50);}QPushButton:pressed{background-color:rgb(0, 255, 0);border: rgb(50, 50, 50);}\n" "") self.pushButton_2.setObjectName("pushButton_2") self.lbl = QLabel(self.groupBox) self.lbl.setText('النسخة : ') font = QFont('abdo salem') font.setPointSize(25) font.setBold(True) self.lbl.setGeometry(750, 8, 90, 22) self.lbl.setFont(font) self.lbl.setStyleSheet('background-color: rgb(50, 50, 50);') self.doubleSpinBox = QDoubleSpinBox(self.groupBox) self.doubleSpinBox.setGeometry(690, 9, 56, 22) self.doubleSpinBox.setFont(font) self.doubleSpinBox.setStyleSheet("background-color: rgb(70, 70, 70);\n" "font: 75 16pt \"Audiowide\";\n" "") self.doubleSpinBox.setWrapping(False) self.doubleSpinBox.setAlignment(Qt.AlignCenter) self.doubleSpinBox.setDecimals(1) self.doubleSpinBox.setSingleStep(0.1) self.doubleSpinBox.setProperty("value", 3.7) self.doubleSpinBox.setValue(3.7) self.open = QPushButton(self.groupBox) self.btn.append(self.open) self.open.setGeometry(QRect(50, 8, 28, 28)) icon = QIcon() icon.addPixmap(QPixmap("icons/save.png"), QIcon.Normal, QIcon.Off) self.open.setIcon(icon) self.open.setIconSize(QSize(24, 24)) self.open.setObjectName("open") self.new = QPushButton(self.groupBox) self.btn.append(self.new) self.new.setGeometry(QRect(90, 8, 28, 28)) self.new.setText("") icon1 = QIcon() icon1.addPixmap(QPixmap("icons/NEW.png"), QIcon.Normal, QIcon.Off) self.new.setIcon(icon1) self.new.setIconSize(QSize(24, 24)) self.new.setObjectName("new") self.run = QPushButton(self.groupBox) self.btn.append(self.run) self.run.setGeometry(QRect(130, 9, 28, 28)) icon2 = QIcon() icon2.addPixmap(QPixmap("icons/start-icosn.png"), QIcon.Normal, QIcon.Off) self.run.setIcon(icon2) self.run.setIconSize(QSize(24, 24)) self.run.setObjectName("run") self.start = QPushButton(self.groupBox) self.start.setGeometry(QRect(360, 0, 250, 45)) self.start.setText('لنتعلم معا') # self.setAttribute(Qt.WA_TranslucentBackground,True) self.start.setStyleSheet( "QPushButton:hover{background-color:rgb(30, 30, 30);border:5px solid rgb(30, 30, 30);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:0.3px solid rgb(50, 50, 50);}QPushButton:pressed{background-color:rgb(80, 80, 80);border: rgb(80, 80, 80);}\n" "") self.start.setFont(font) self.start.setGraphicsEffect(self.shadow) self.slider = QSlider(Qt.Horizontal, self.groupBox) self.slider.setGeometry(QRect(180, 14, 100, 15)) self.slider.setValue(100) self.slider.setStyleSheet("QSlider::groove:horizontal {\n" " background-color:rgb(50, 50, 50);\n" " border: 1px solid;\n" " height: 10px;\n" " margin: 0px;\n" " }\n" "QSlider::handle:horizontal {\n" " background-color:rgb(65, 65, 65);\n" " border: 1px solid;\n" " height: 40px;\n" " width: 40px;\n" " margin: -15px 0px;\n" " }") self.open_2 = QPushButton(self.groupBox) self.btn.append(self.open_2) self.open_2.setGeometry(QRect(10, 8, 28, 28)) icon3 = QIcon() icon3.addPixmap(QPixmap("icons/open.png"), QIcon.Normal, QIcon.Off) self.open_2.setIcon(icon3) self.open_2.setIconSize(QSize(24, 24)) self.open_2.setObjectName("open_2") self.tabWidget.setCurrentIndex(0) self.tabWidget_2.setCurrentIndex(0) Form.setWindowTitle("McPython") self.tabWidget.setTabText(0, "Form") self.pushButton.setText("X") self.pushButton_2.setText("-") self.run.setEnabled(False) self.open.setEnabled(False)
def __init__(self, show_automatic_box=True): super().__init__(show_automatic_box=show_automatic_box) button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Refresh Script", callback=self.refresh_script) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(150) gui.separator(self.controlArea) gen_box = oasysgui.widgetBox(self.controlArea, "COMSYL Beamline Propagation", addSpace=False, orientation="vertical", height=530, width=self.CONTROL_AREA_WIDTH - 5) figure_box0 = oasysgui.widgetBox(gen_box, "", addSpace=True, orientation="horizontal") self.id_comsyl_af_file = oasysgui.lineEdit(figure_box0, self, "COMSYL_AF_FILE", "Comsyl File with Modes:", labelWidth=90, valueType=str, orientation="horizontal") gui.button(figure_box0, self, "...", callback=self.select_comsyl_af_file) figure_box = oasysgui.widgetBox(gen_box, "", addSpace=True, orientation="horizontal") self.id_bl_pickle_file = oasysgui.lineEdit(figure_box, self, "BL_PICKLE_FILE", "BL Pickle File:", labelWidth=90, valueType=str, orientation="horizontal") gui.button(figure_box, self, "...", callback=self.select_bl_pickle_file) oasysgui.lineEdit(gen_box, self, "MODE_INDEX", label="Maximum Mode index", addSpace=False, valueType=int, validator=QIntValidator(), orientation="horizontal", labelWidth=150) oasysgui.lineEdit(gen_box, self, "DIRECTORY_NAME", "Temporal Directory", labelWidth=160, valueType=str, orientation="horizontal") oasysgui.lineEdit(gen_box, self, "PYTHON_INTERPRETER", "Python interpreter", labelWidth=160, valueType=str, orientation="horizontal") tabs_setting = oasysgui.tabWidget(self.mainArea) tabs_setting.setFixedHeight(self.IMAGE_HEIGHT) tabs_setting.setFixedWidth(self.IMAGE_WIDTH) tab_scr = oasysgui.createTabPage(tabs_setting, "Python Script") tab_out = oasysgui.createTabPage(tabs_setting, "System Output") self.pythonScript = oasysgui.textArea(readOnly=False) self.pythonScript.setStyleSheet( "background-color: white; font-family: Courier, monospace;") self.pythonScript.setMaximumHeight(self.IMAGE_HEIGHT - 250) script_box = oasysgui.widgetBox(tab_scr, "", addSpace=False, orientation="vertical", height=self.IMAGE_HEIGHT - 10, width=self.IMAGE_WIDTH - 10) script_box.layout().addWidget(self.pythonScript) console_box = oasysgui.widgetBox(script_box, "", addSpace=True, orientation="vertical", height=150, width=self.IMAGE_WIDTH - 10) self.console = PythonConsole(self.__dict__, self) console_box.layout().addWidget(self.console) self.shadow_output = oasysgui.textArea() out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=self.IMAGE_WIDTH - 45) out_box.layout().addWidget(self.shadow_output) button_box = oasysgui.widgetBox(tab_scr, "", addSpace=True, orientation="horizontal") gui.button(button_box, self, "Run Script", callback=self.execute_script, height=40) gui.button(button_box, self, "Save Script to File", callback=self.save_script, height=40)
class MainWindow(QtWidgets.QMainWindow): """ creates a window and spawns some widgets to be able to test the tile layout """ def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.font = QFont('Latin', 15) self.font.setBold(True) row_number = 6 column_number = 4 vertical_span = 100 horizontal_span = 150 spacing = 5 static_layout = True # create the tile layout self.tile_layout = QTileLayout( rowNumber=row_number, columnNumber=column_number, verticalSpan=vertical_span, horizontalSpan=horizontal_span, verticalSpacing=spacing, horizontalSpacing=spacing, ) # allow the user to drag and drop tiles or not self.tile_layout.acceptDragAndDrop(True) # allow the user to resize tiles or not self.tile_layout.acceptResizing(True) # set the default cursor shape on the tiles self.tile_layout.setCursorIdle(QtCore.Qt.ArrowCursor) # set the cursor shape when the user can grab the tile self.tile_layout.setCursorGrab(QtCore.Qt.OpenHandCursor) # set the cursor shape when the user can resize the tile horizontally self.tile_layout.setCursorResizeHorizontal(QtCore.Qt.SizeHorCursor) # set the cursor shape when the user can resize the tile vertically self.tile_layout.setCursorResizeVertical(QtCore.Qt.SizeVerCursor) # set default tile color self.tile_layout.setColorIdle((240, 240, 240)) # set tile color during resize self.tile_layout.setColorResize((211, 211, 211)) # set tile color during drag and drop self.tile_layout.setColorDragAndDrop((211, 211, 211)) # add widgets in the tile layout for i_row in range(row_number - 2): for i_column in range(column_number): self.tile_layout.addWidget( widget=self.__spawnWidget(), fromRow=i_row, fromColumn=i_column, ) self.tile_layout.addWidget(widget=self.__spawnWidget(), fromRow=row_number - 2, fromColumn=1, rowSpan=2, columnSpan=2) # remove a widget from the tile layout last_widget = self.__spawnWidget() self.tile_layout.addWidget(widget=last_widget, fromRow=row_number - 1, fromColumn=0, rowSpan=1, columnSpan=1) self.tile_layout.removeWidget(last_widget) # return the number of rows print(f'Row number: {self.tile_layout.rowCount()}') # return the number of columns print(f'Column number: {self.tile_layout.columnCount()}') # return the geometry of a specific tile print( f'One tile geometry: {self.tile_layout.tileRect(row_number - 1, 1)}' ) # return the tile height print(f'Tile height: {self.tile_layout.rowsMinimumHeight()}') # return the tile width print(f'Tile width: {self.tile_layout.columnsMinimumWidth()}') # return the vertical spacing between two tiles print(f'Layout vertical spacing: {self.tile_layout.verticalSpacing()}') # return the horizontal spacing between two tiles print( f'Layout horizontal spacing: {self.tile_layout.horizontalSpacing()}' ) # return the widgets currently in the layout print(f'Number of widget: {len(self.tile_layout.widgetList())}') # set the vertical spacing between two tiles self.tile_layout.setVerticalSpacing(5) # set the horizontal spacing between two tiles self.tile_layout.setHorizontalSpacing(5) # set the minimum tiles height self.tile_layout.setRowsMinimumHeight(100) # set the minimum tiles width self.tile_layout.setColumnsMinimumWidth(150) # set the tiles height self.tile_layout.setRowsHeight(100) # set the tiles width self.tile_layout.setColumnsWidth(150) # actions to do when a tile is resized self.tile_layout.tileResized.connect(self.__tileHasBeenResized) # actions to do when a tile is moved self.tile_layout.tileMoved.connect(self.__tileHasBeenMoved) # adds rows at the bottom of the layout self.tile_layout.addRows(1) # adds columns at the right of the layout self.tile_layout.addColumns(1) # removes rows from the layout bottom self.tile_layout.removeRows(1) # removes columns from the layout right self.tile_layout.removeColumns(1) # insert the layout in the window self.central_widget = QtWidgets.QWidget() self.central_widget.setContentsMargins(0, 0, 0, 0) self.central_widget.setLayout(self.tile_layout) if static_layout: self.setCentralWidget(self.central_widget) else: self.scroll = QtWidgets.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setContentsMargins(0, 0, 0, 0) self.scroll.setWidget(self.central_widget) self.setCentralWidget(self.scroll) self.scroll.resizeEvent = self.__centralWidgetResize # if you are not in static layout mode, think to change the scrollArea minimum height and width if you # change tiles minimum height or width vertical_margins = self.tile_layout.contentsMargins().top( ) + self.tile_layout.contentsMargins().bottom() horizontal_margins = self.tile_layout.contentsMargins().left( ) + self.tile_layout.contentsMargins().right() self.scroll.setMinimumHeight(row_number * vertical_span + (row_number - 1) * spacing + vertical_margins + 2) self.scroll.setMinimumWidth(column_number * horizontal_span + (column_number - 1) * spacing + horizontal_margins + 2) def __spawnWidget(self): """spawns a little colored widget with text""" label = QtWidgets.QLabel(self) label.setText(random.choice(possible_text)) label.setFont(self.font) label.setAlignment(QtCore.Qt.AlignCenter) label.setAutoFillBackground(True) label.setPalette(self.__spawnColor()) return label @staticmethod def __spawnColor(): """spawns a random color""" palette = QPalette() palette.setColor(QPalette.Background, QtGui.QColor(*random.choice(possible_colors))) return palette @staticmethod def __tileHasBeenResized(widget, from_row, from_column, row_span, column_span): print( f'{widget} has been resized and is now at the position ({from_row}, {from_column}) ' f'with a span of ({row_span}, {column_span})') @staticmethod def __tileHasBeenMoved(widget, from_row, from_column, to_row, to_column): print( f'{widget} has been moved from position ({from_row}, {from_column}) to ({to_row}, {to_column})' ) def __centralWidgetResize(self, a0): self.tile_layout.updateGlobalSize(a0)
def paint(self, painter, option, index): """ Public method to paint the specified list item. @param painter painter object to paint to (QPainter) @param option style option used for painting (QStyleOptionViewItem) @param index model index of the item (QModelIndex) """ opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = opt.widget style = widget.style() if widget is not None else QApplication.style() height = opt.rect.height() center = height // 2 + opt.rect.top() # Prepare title font titleFont = QFont(opt.font) titleFont.setBold(True) titleFont.setPointSize(titleFont.pointSize() + 1) titleMetrics = QFontMetrics(titleFont) if Globals.isWindowsPlatform(): colorRole = QPalette.Text else: colorRole = ( QPalette.HighlightedText if opt.state & QStyle.State_Selected else QPalette.Text ) leftPos = self.__padding rightPos = ( opt.rect.right() - self.__padding - GreaseMonkeyConfigurationListDelegate.RemoveIconSize ) # Draw background style.drawPrimitive(QStyle.PE_PanelItemViewItem, opt, painter, widget) # Draw checkbox checkBoxYPos = ( center - GreaseMonkeyConfigurationListDelegate.CheckBoxSize // 2 ) opt2 = QStyleOptionViewItem(opt) if opt2.checkState == Qt.Checked: opt2.state |= QStyle.State_On else: opt2.state |= QStyle.State_Off styleCheckBoxRect = style.subElementRect( QStyle.SE_ViewItemCheckIndicator, opt2, widget) opt2.rect = QRect( leftPos, checkBoxYPos, styleCheckBoxRect.width(), styleCheckBoxRect.height()) style.drawPrimitive(QStyle.PE_IndicatorViewItemCheck, opt2, painter, widget) leftPos = opt2.rect.right() + self.__padding # Draw icon iconYPos = center - GreaseMonkeyConfigurationListDelegate.IconSize // 2 iconRect = QRect(leftPos, iconYPos, GreaseMonkeyConfigurationListDelegate.IconSize, GreaseMonkeyConfigurationListDelegate.IconSize) pixmap = index.data(Qt.DecorationRole).pixmap( GreaseMonkeyConfigurationListDelegate.IconSize) painter.drawPixmap(iconRect, pixmap) leftPos = iconRect.right() + self.__padding # Draw script name name = index.data(Qt.DisplayRole) leftTitleEdge = leftPos + 2 rightTitleEdge = rightPos - self.__padding try: leftPosForVersion = ( titleMetrics.horizontalAdvance(name) + self.__padding ) except AttributeError: leftPosForVersion = titleMetrics.width(name) + self.__padding nameRect = QRect(leftTitleEdge, opt.rect.top() + self.__padding, rightTitleEdge - leftTitleEdge, titleMetrics.height()) painter.setFont(titleFont) style.drawItemText(painter, nameRect, Qt.AlignLeft, opt.palette, True, name, colorRole) # Draw version version = index.data(Qt.UserRole) versionRect = QRect( nameRect.x() + leftPosForVersion, nameRect.y(), rightTitleEdge - leftTitleEdge, titleMetrics.height()) versionFont = titleFont painter.setFont(versionFont) style.drawItemText(painter, versionRect, Qt.AlignLeft, opt.palette, True, version, colorRole) # Draw description infoYPos = nameRect.bottom() + opt.fontMetrics.leading() infoRect = QRect( nameRect.x(), infoYPos, nameRect.width(), opt.fontMetrics.height()) info = opt.fontMetrics.elidedText( index.data(Qt.UserRole + 1), Qt.ElideRight, infoRect.width()) painter.setFont(opt.font) style.drawItemText(painter, infoRect, Qt.AlignLeft | Qt.TextSingleLine, opt.palette, True, info, colorRole) # Draw remove button removeIconYPos = ( center - GreaseMonkeyConfigurationListDelegate.RemoveIconSize // 2 ) removeIconRect = QRect( rightPos, removeIconYPos, GreaseMonkeyConfigurationListDelegate.RemoveIconSize, GreaseMonkeyConfigurationListDelegate.RemoveIconSize) painter.drawPixmap(removeIconRect, self.__removePixmap)
def setupUi(self, MainWindow): if MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(1000, 500) MainWindow.setMinimumSize(QSize(1000, 500)) MainWindow.setStyleSheet(u"background-color: rgb(45, 45, 45);") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName(u"verticalLayout") self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.Top_Bar = QFrame(self.centralwidget) self.Top_Bar.setObjectName(u"Top_Bar") self.Top_Bar.setMaximumSize(QSize(16777215, 40)) self.Top_Bar.setStyleSheet(u"background-color: rgb(35, 35, 35);") self.Top_Bar.setFrameShape(QFrame.NoFrame) self.Top_Bar.setFrameShadow(QFrame.Raised) self.horizontalLayout = QHBoxLayout(self.Top_Bar) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName(u"horizontalLayout") self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.frame_toggle = QFrame(self.Top_Bar) self.frame_toggle.setObjectName(u"frame_toggle") self.frame_toggle.setMaximumSize(QSize(70, 40)) self.frame_toggle.setStyleSheet( u"background-color: rgb(85, 170, 255);") self.frame_toggle.setFrameShape(QFrame.StyledPanel) self.frame_toggle.setFrameShadow(QFrame.Raised) self.verticalLayout_2 = QVBoxLayout(self.frame_toggle) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setObjectName(u"verticalLayout_2") self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.Btn_Toggle = QPushButton(self.frame_toggle) self.Btn_Toggle.setObjectName(u"Btn_Toggle") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.Btn_Toggle.sizePolicy().hasHeightForWidth()) self.Btn_Toggle.setSizePolicy(sizePolicy) font = QFont() font.setFamily(u"MS Reference Sans Serif") self.Btn_Toggle.setFont(font) self.Btn_Toggle.setStyleSheet(u"color: rgb(255, 255, 255);\n" "border: 0px solid;") self.verticalLayout_2.addWidget(self.Btn_Toggle) self.horizontalLayout.addWidget(self.frame_toggle) self.frame_top = QFrame(self.Top_Bar) self.frame_top.setObjectName(u"frame_top") self.frame_top.setFrameShape(QFrame.StyledPanel) self.frame_top.setFrameShadow(QFrame.Raised) self.horizontalLayout.addWidget(self.frame_top) self.verticalLayout.addWidget(self.Top_Bar) self.Content = QFrame(self.centralwidget) self.Content.setObjectName(u"Content") self.Content.setFrameShape(QFrame.NoFrame) self.Content.setFrameShadow(QFrame.Raised) self.horizontalLayout_2 = QHBoxLayout(self.Content) self.horizontalLayout_2.setSpacing(0) self.horizontalLayout_2.setObjectName(u"horizontalLayout_2") self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) self.frame_left_menu = QFrame(self.Content) self.frame_left_menu.setObjectName(u"frame_left_menu") self.frame_left_menu.setMinimumSize(QSize(70, 0)) self.frame_left_menu.setMaximumSize(QSize(70, 16777215)) self.frame_left_menu.setStyleSheet( u"background-color: rgb(35, 35, 35);") self.frame_left_menu.setFrameShape(QFrame.StyledPanel) self.frame_left_menu.setFrameShadow(QFrame.Raised) self.verticalLayout_3 = QVBoxLayout(self.frame_left_menu) self.verticalLayout_3.setObjectName(u"verticalLayout_3") self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.frame_top_menus = QFrame(self.frame_left_menu) self.frame_top_menus.setObjectName(u"frame_top_menus") self.frame_top_menus.setFrameShape(QFrame.NoFrame) self.frame_top_menus.setFrameShadow(QFrame.Raised) self.verticalLayout_4 = QVBoxLayout(self.frame_top_menus) self.verticalLayout_4.setSpacing(0) self.verticalLayout_4.setObjectName(u"verticalLayout_4") self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.Patient = QPushButton(self.frame_top_menus) self.Patient.setObjectName(u"Patient") self.Patient.setMinimumSize(QSize(0, 40)) self.Patient.setFont(font) self.Patient.setStyleSheet(u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 0px solid;\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.Patient.setAutoDefault(True) self.verticalLayout_4.addWidget(self.Patient) self.Platform = QPushButton(self.frame_top_menus) self.Platform.setObjectName(u"Platform") self.Platform.setMinimumSize(QSize(0, 40)) self.Platform.setFont(font) self.Platform.setStyleSheet(u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 0px solid;\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.Platform.setAutoDefault(True) self.verticalLayout_4.addWidget(self.Platform) self.verticalLayout_3.addWidget(self.frame_top_menus, 0, Qt.AlignTop) self.horizontalLayout_2.addWidget(self.frame_left_menu) self.frame_pages = QFrame(self.Content) self.frame_pages.setObjectName(u"frame_pages") self.frame_pages.setFrameShape(QFrame.StyledPanel) self.frame_pages.setFrameShadow(QFrame.Raised) self.verticalLayout_5 = QVBoxLayout(self.frame_pages) self.verticalLayout_5.setObjectName(u"verticalLayout_5") self.stackedWidget = QStackedWidget(self.frame_pages) self.stackedWidget.setObjectName(u"stackedWidget") self.Patient_Information = QWidget() self.Patient_Information.setObjectName(u"Patient_Information") self.Add_Patient = QPushButton(self.Patient_Information) self.Add_Patient.setObjectName(u"Add_Patient") self.Add_Patient.setGeometry(QRect(0, 0, 251, 71)) font1 = QFont() font1.setFamily(u"MS Reference Sans Serif") font1.setPointSize(12) font1.setBold(False) font1.setItalic(False) font1.setWeight(50) self.Add_Patient.setFont(font1) self.Add_Patient.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.listWidget = QListWidget(self.Patient_Information) QListWidgetItem(self.listWidget) self.listWidget.setObjectName(u"listWidget") self.listWidget.setGeometry(QRect(0, 70, 251, 361)) self.listWidget.setFont(font1) self.listWidget.setMouseTracking(True) self.listWidget.setTabletTracking(True) self.listWidget.setStyleSheet(u"QListWidget {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayoutWidget = QWidget(self.Patient_Information) self.formLayoutWidget.setObjectName(u"formLayoutWidget") self.formLayoutWidget.setGeometry(QRect(260, 0, 641, 392)) self.formLayout = QFormLayout(self.formLayoutWidget) self.formLayout.setObjectName(u"formLayout") self.formLayout.setVerticalSpacing(28) self.formLayout.setContentsMargins(0, 0, 0, 0) self.genderLabel = QLabel(self.formLayoutWidget) self.genderLabel.setObjectName(u"genderLabel") self.genderLabel.setFont(font1) self.genderLabel.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(0, QFormLayout.LabelRole, self.genderLabel) self.genderLineEdit = QLineEdit(self.formLayoutWidget) self.genderLineEdit.setObjectName(u"genderLineEdit") self.genderLineEdit.setMinimumSize(QSize(0, 19)) self.genderLineEdit.setFont(font1) self.genderLineEdit.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(0, QFormLayout.FieldRole, self.genderLineEdit) self.heightLabel = QLabel(self.formLayoutWidget) self.heightLabel.setObjectName(u"heightLabel") self.heightLabel.setFont(font1) self.heightLabel.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(1, QFormLayout.LabelRole, self.heightLabel) self.heightLineEdit = QLineEdit(self.formLayoutWidget) self.heightLineEdit.setObjectName(u"heightLineEdit") self.heightLineEdit.setFont(font1) self.heightLineEdit.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(1, QFormLayout.FieldRole, self.heightLineEdit) self.ageLabel = QLabel(self.formLayoutWidget) self.ageLabel.setObjectName(u"ageLabel") self.ageLabel.setFont(font1) self.ageLabel.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(2, QFormLayout.LabelRole, self.ageLabel) self.ageLineEdit = QLineEdit(self.formLayoutWidget) self.ageLineEdit.setObjectName(u"ageLineEdit") self.ageLineEdit.setFont(font1) self.ageLineEdit.setStyleSheet(u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(2, QFormLayout.FieldRole, self.ageLineEdit) self.shoeSizeLabel = QLabel(self.formLayoutWidget) self.shoeSizeLabel.setObjectName(u"shoeSizeLabel") self.shoeSizeLabel.setFont(font1) self.shoeSizeLabel.setStyleSheet( u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(3, QFormLayout.LabelRole, self.shoeSizeLabel) self.shoeSizeLineEdit = QLineEdit(self.formLayoutWidget) self.shoeSizeLineEdit.setObjectName(u"shoeSizeLineEdit") self.shoeSizeLineEdit.setFont(font1) self.shoeSizeLineEdit.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(3, QFormLayout.FieldRole, self.shoeSizeLineEdit) self.weightLabel = QLabel(self.formLayoutWidget) self.weightLabel.setObjectName(u"weightLabel") self.weightLabel.setFont(font1) self.weightLabel.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(4, QFormLayout.LabelRole, self.weightLabel) self.weightLineEdit = QLineEdit(self.formLayoutWidget) self.weightLineEdit.setObjectName(u"weightLineEdit") self.weightLineEdit.setFont(font1) self.weightLineEdit.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout.setWidget(4, QFormLayout.FieldRole, self.weightLineEdit) self.label = QLabel(self.formLayoutWidget) self.label.setObjectName(u"label") self.formLayout.setWidget(5, QFormLayout.LabelRole, self.label) self.Save_Patient_Info = QPushButton(self.Patient_Information) self.Save_Patient_Info.setObjectName(u"Save_Patient_Info") self.Save_Patient_Info.setGeometry(QRect(260, 290, 321, 141)) self.Save_Patient_Info.setFont(font1) self.Save_Patient_Info.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.Delete_Patient_Info = QPushButton(self.Patient_Information) self.Delete_Patient_Info.setObjectName(u"Delete_Patient_Info") self.Delete_Patient_Info.setGeometry(QRect(590, 290, 311, 141)) self.Delete_Patient_Info.setFont(font1) self.Delete_Patient_Info.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.stackedWidget.addWidget(self.Patient_Information) self.Platform_Running = QWidget() self.Platform_Running.setObjectName(u"Platform_Running") self.Run_Simulation = QPushButton(self.Platform_Running) self.Run_Simulation.setObjectName(u"Run_Simulation") self.Run_Simulation.setGeometry(QRect(660, 0, 241, 431)) font2 = QFont() font2.setFamily(u"MS Reference Sans Serif") font2.setPointSize(16) font2.setBold(False) font2.setWeight(50) self.Run_Simulation.setFont(font2) self.Run_Simulation.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.simulationlist = QListWidget(self.Platform_Running) self.simulationlist.setObjectName(u"simulationlist") self.simulationlist.setGeometry(QRect(0, 70, 251, 361)) self.simulationlist.setFont(font1) self.simulationlist.setStyleSheet( u"QListWidget {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.Add_Simulation = QPushButton(self.Platform_Running) self.Add_Simulation.setObjectName(u"Add_Simulation") self.Add_Simulation.setGeometry(QRect(0, 0, 251, 71)) self.Add_Simulation.setFont(font1) self.Add_Simulation.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.Save_Simulation = QPushButton(self.Platform_Running) self.Save_Simulation.setObjectName(u"Save_Simulation") self.Save_Simulation.setGeometry(QRect(250, 290, 201, 141)) self.Save_Simulation.setFont(font1) self.Save_Simulation.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.formLayoutWidget_2 = QWidget(self.Platform_Running) self.formLayoutWidget_2.setObjectName(u"formLayoutWidget_2") self.formLayoutWidget_2.setGeometry(QRect(260, 0, 391, 201)) self.formLayout_2 = QFormLayout(self.formLayoutWidget_2) self.formLayout_2.setObjectName(u"formLayout_2") self.formLayout_2.setVerticalSpacing(50) self.formLayout_2.setContentsMargins(0, 0, 0, 0) self.distanceLabel = QLabel(self.formLayoutWidget_2) self.distanceLabel.setObjectName(u"distanceLabel") self.distanceLabel.setFont(font1) self.distanceLabel.setStyleSheet( u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout_2.setWidget(0, QFormLayout.LabelRole, self.distanceLabel) self.distanceLineEdit_2 = QLineEdit(self.formLayoutWidget_2) self.distanceLineEdit_2.setObjectName(u"distanceLineEdit_2") self.distanceLineEdit_2.setMinimumSize(QSize(0, 19)) self.distanceLineEdit_2.setFont(font1) self.distanceLineEdit_2.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout_2.setWidget(0, QFormLayout.FieldRole, self.distanceLineEdit_2) self.speedLabel_2 = QLabel(self.formLayoutWidget_2) self.speedLabel_2.setObjectName(u"speedLabel_2") self.speedLabel_2.setFont(font1) self.speedLabel_2.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout_2.setWidget(1, QFormLayout.LabelRole, self.speedLabel_2) self.speedLineEdit_2 = QLineEdit(self.formLayoutWidget_2) self.speedLineEdit_2.setObjectName(u"speedLineEdit_2") self.speedLineEdit_2.setMinimumSize(QSize(0, 19)) self.speedLineEdit_2.setFont(font1) self.speedLineEdit_2.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout_2.setWidget(1, QFormLayout.FieldRole, self.speedLineEdit_2) self.directionLabel_2 = QLabel(self.formLayoutWidget_2) self.directionLabel_2.setObjectName(u"directionLabel_2") self.directionLabel_2.setFont(font1) self.directionLabel_2.setStyleSheet( u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout_2.setWidget(2, QFormLayout.LabelRole, self.directionLabel_2) self.directionLineEdit_2 = QLineEdit(self.formLayoutWidget_2) self.directionLineEdit_2.setObjectName(u"directionLineEdit_2") self.directionLineEdit_2.setMinimumSize(QSize(0, 19)) self.directionLineEdit_2.setFont(font1) self.directionLineEdit_2.setStyleSheet( u"QLineEdit {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}") self.formLayout_2.setWidget(2, QFormLayout.FieldRole, self.directionLineEdit_2) self.label_2 = QLabel(self.Platform_Running) self.label_2.setObjectName(u"label_2") self.label_2.setGeometry(QRect(260, 200, 391, 41)) font3 = QFont() font3.setFamily(u"MS Reference Sans Serif") font3.setPointSize(10) font3.setBold(False) font3.setItalic(False) font3.setWeight(50) self.label_2.setFont(font3) self.label_2.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 10pt\n" "}") self.Delete_Simulation = QPushButton(self.Platform_Running) self.Delete_Simulation.setObjectName(u"Delete_Simulation") self.Delete_Simulation.setGeometry(QRect(450, 290, 211, 141)) self.Delete_Simulation.setFont(font1) self.Delete_Simulation.setStyleSheet( u"QPushButton {\n" " color: rgb(255, 255, 255);\n" " background-color: rgb(35, 35, 35);\n" " border: 2px solid;\n" " border-color: rgb(255, 255, 255);\n" " font: 12pt\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(85, 170, 255);\n" "}") self.stackedWidget.addWidget(self.Platform_Running) self.verticalLayout_5.addWidget(self.stackedWidget) self.horizontalLayout_2.addWidget(self.frame_pages) self.verticalLayout.addWidget(self.Content) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
class RmsDriver(QObject): def __init__(self, driverNum): super().__init__() self.CtrlNum = driverNum self.name = 'Driver ' + str(driverNum) self.lapcount = 0 self.bestLapTime = None self.lapTime = None self.time = None self.fuellevel = 15 self.pitcount = 0 self.pit = False self.buildDriver() def buildDriver(self): self.nameFont = QFont() self.nameFont.setPointSize(20) self.nameFont.setBold(True) self.nameBtn = QPushButton(self.name + '\n' + 'Ctrl: ' + str(self.CtrlNum)) self.nameBtn.setToolTip('Click to change driver name') self.nameBtn.setFont(self.nameFont) self.nameBtn.setStyleSheet( "QPushButton { border: 5px solid black; border-radius: 10px; background-color: white}" ) self.lapCountLCD = QLCDNumber(3) self.lapCountLCD.setStyleSheet( "QLCDNumber{ border-radius: 10px; background-color: black}") lcdPalette = self.lapCountLCD.palette() lcdPalette.setColor(lcdPalette.WindowText, QColor(255, 255, 0)) self.lapCountLCD.setPalette(lcdPalette) self.lapCountLCD.display(self.lapcount) self.bestLapLCD = QLCDNumber() self.bestLapLCD.setStyleSheet( "QLCDNumber{ border-radius: 10px; background-color: black}") lcdPalette = self.bestLapLCD.palette() lcdPalette.setColor(lcdPalette.WindowText, QColor(255, 255, 0)) self.bestLapLCD.setPalette(lcdPalette) self.bestLapLCD.display(self.bestLapTime) self.lapLCD = QLCDNumber() self.lapLCD.setStyleSheet( "QLCDNumber{ border-radius: 10px; background-color: black}") lcdPalette = self.lapLCD.palette() lcdPalette.setColor(lcdPalette.WindowText, QColor(255, 255, 0)) self.lapLCD.setPalette(lcdPalette) self.lapLCD.display(self.lapTime) self.fuelbar = QProgressBar() self.fuelbar.setOrientation(Qt.Horizontal) self.fuelbar.setStyleSheet( "QProgressBar{ color: white; background-color: black; border: 5px solid black; border-radius: 10px; text-align: center}\ QProgressBar::chunk { background: qlineargradient(x1: 1, y1: 0.5, x2: 0, y2: 0.5, stop: 0 #00AA00, stop: " + str(0.92 - (1 / (self.fuellevel))) + " #22FF22, stop: " + str(0.921 - (1 / (self.fuellevel))) + " #22FF22, stop: " + str(1.001 - (1 / (self.fuellevel))) + " red, stop: 1 #550000); }") self.fuelbar.setMinimum(0) self.fuelbar.setMaximum(15) self.fuelbar.setValue(self.fuellevel) self.pitCountLCD = QLCDNumber(2) self.pitCountLCD.setStyleSheet( "QLCDNumber{ border-radius: 10px; background-color: black}") lcdPalette = self.pitCountLCD.palette() lcdPalette.setColor(lcdPalette.WindowText, QColor(255, 0, 0)) self.pitCountLCD.setPalette(lcdPalette) self.pitCountLCD.display(self.pitcount) def getName(self): return self.name def getNameBtn(self): return self.nameBtn def getLapCountLCD(self): return self.lapCountLCD def getBestLapLCD(self): return self.bestLapLCD def getLapLCD(self): return self.lapLCD def getFuelBar(self): return self.fuelbar def setCtrlNum(self, num): self.CtrlNum = num self.nameBtn.setText(self.name + '\n' + 'Ctrl: ' + str(self.CtrlNum)) def getPits(self): return self.pitCountLCD def newlap(self, timer): if self.time is not None: self.lapTime = timer.timestamp - self.time if self.bestLapTime is None or self.lapTime < self.bestLapTime: self.bestLapTime = self.lapTime self.lapcount += 1 self.time = timer.timestamp
else: QMessageBox.warning(self, "警告", "用户名或密码错误!", QMessageBox.Yes) self.usrLineEdit.setFocus() def reject(self): QMessageBox.warning(self, "警告", "确定退出?", QMessageBox.Yes) sys.exit() if __name__ == "__main__": app = QApplication(sys.argv) splash = QSplashScreen(QPixmap(":/pic/src/img/1.jpg")) splash.show() font = QFont() font.setPointSize(16) font.setBold(True) font.setWeight(75) splash.setFont(font) splash.showMessage("正在加载。。。", Qt.AlignHCenter, Qt.red) time.sleep(1) splash.showMessage("请耐心等待,不要反复点击。。。", Qt.AlignHCenter, Qt.red) time.sleep(1) # 设置进程,启动加载页面时可以进行其他操作而不会卡死 app.processEvents() win = LoginDlg() main = MainForm() win.show() splash.finish(win) sys.exit(app.exec_())
def __init__(self, show_automatic_box=False): super().__init__(show_automatic_box=show_automatic_box, show_view_box=False) self.general_options_box.setVisible(False) button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Calculate Spectrum", callback=self.calculateRadiation) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(150) gui.separator(self.controlArea) self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH) # FLUX ------------------------------------------- spe_box = oasysgui.widgetBox(self.controlArea, "Wavefront Parameters", addSpace=False, orientation="vertical", width=self.CONTROL_AREA_WIDTH - 5) oasysgui.lineEdit(spe_box, self, "spe_photon_energy_min", "Photon Energy Min [eV]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_photon_energy_max", "Photon Energy Max [eV]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_photon_energy_points", "Photon Energy Points", labelWidth=260, valueType=int, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_h_slit_gap", "H Slit Gap [m]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_v_slit_gap", "V Slit Gap [m]", labelWidth=260, valueType=float, orientation="horizontal") self.box_points = oasysgui.widgetBox(spe_box, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.box_points, self, "spe_h_slit_points", "H Slit Points", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(self.box_points, self, "spe_v_slit_points", "V Slit Points", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_distance", "Propagation Distance [m]", labelWidth=260, valueType=float, orientation="horizontal") gui.comboBox(spe_box, self, "spe_polarization_component_to_be_extracted", label="Polarization Component", items=PolarizationComponent.tuple(), labelWidth=150, sendSelectedValue=False, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_on_axis_x", "H On-Axis Position [m]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(spe_box, self, "spe_on_axis_y", "V On-Axis Position [m]", labelWidth=260, valueType=float, orientation="horizontal") pre_box = oasysgui.widgetBox(self.controlArea, "Precision Parameters", addSpace=False, orientation="vertical", width=self.CONTROL_AREA_WIDTH - 5) self.tabs_precision = oasysgui.tabWidget(pre_box) tab_prop = oasysgui.createTabPage(self.tabs_precision, "Propagation") gui.comboBox(tab_prop, self, "spe_sr_method", label="Calculation Method", items=["Manual", "Auto"], labelWidth=260, sendSelectedValue=False, orientation="horizontal") oasysgui.lineEdit(tab_prop, self, "spe_relative_precision", "Relative Precision", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(tab_prop, self, "spe_start_integration_longitudinal_position", "Longitudinal pos. to start integration [m]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(tab_prop, self, "spe_end_integration_longitudinal_position", "Longitudinal pos. to finish integration [m]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(tab_prop, self, "spe_number_of_points_for_trajectory_calculation", "Number of points for trajectory calculation", labelWidth=260, valueType=int, orientation="horizontal") gui.comboBox(tab_prop, self, "spe_use_terminating_terms", label="Use \"terminating terms\"or not", items=["No", "Yes"], labelWidth=260, sendSelectedValue=False, orientation="horizontal") oasysgui.lineEdit(tab_prop, self, "spe_sampling_factor_for_adjusting_nx_ny", "Sampling factor for adjusting nx/ny", labelWidth=260, valueType=int, orientation="horizontal") # FLUX ------------------------------------------- gui.rubber(self.controlArea)
class BookmarksPanel(QWidget): def __init__(self, parent=None): # pylint: disable=too-many-statements super(BookmarksPanel, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('BookmarksPanel created before Dwarf exists') return self._bookmarks_list = DwarfListView() self._bookmarks_list.doubleClicked.connect(self._on_dblclicked) self._bookmarks_list.setContextMenuPolicy(Qt.CustomContextMenu) self._bookmarks_list.customContextMenuRequested.connect( self._on_contextmenu) self._bookmarks_model = QStandardItemModel(0, 2) self._bookmarks_model.setHeaderData(0, Qt.Horizontal, 'Address') self._bookmarks_model.setHeaderData(1, Qt.Horizontal, 'Notes') self._bookmarks_list.setModel(self._bookmarks_model) self._bookmarks_list.header().setStretchLastSection(False) self._bookmarks_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents | QHeaderView.Interactive) self._bookmarks_list.header().setSectionResizeMode( 1, QHeaderView.Stretch | QHeaderView.Interactive) v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) v_box.addWidget(self._bookmarks_list) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) self.btn1 = QPushButton( QIcon(utils.resource_path('assets/icons/plus.svg')), '') self.btn1.setFixedSize(20, 20) self.btn1.clicked.connect(lambda: self._create_bookmark(-1)) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(self.btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) self.setLayout(v_box) self._bold_font = QFont(self._bookmarks_list.font()) self._bold_font.setBold(True) shortcut_addnative = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_A), self._app_window, self._create_bookmark) shortcut_addnative.setAutoRepeat(False) # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def delete_items(self): """ Delete selected Items """ index = self._bookmarks_list.selectionModel().currentIndex().row() if index != -1: self._on_delete_bookmark(index) self._bookmarks_model.removeRow(index) def clear_list(self): """ Clear the List """ # go through all items and tell it gets removed for item in range(self._bookmarks_model.rowCount()): if item: self._on_delete_bookmark(item) if self._bookmarks_model.rowCount() > 0: # something was wrong it should be empty self._bookmarks_model.removeRows(0, self._bookmarks_model.rowCount()) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _on_dblclicked(self, index): self._app_window.jump_to_address( self._bookmarks_model.item(index, 0).text()) def _on_contextmenu(self, pos): context_menu = QMenu(self) index = self._bookmarks_list.indexAt(pos).row() if index != -1: context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self._bookmarks_model.item(index, 0).text())) context_menu.addAction( 'Jump to address', lambda: self._app_window.jump_to_address( self._bookmarks_model.item(index, 0).text())) # todo: add hook address menu context_menu.addSeparator() context_menu.addAction('Edit', lambda: self._create_bookmark(index=index)) context_menu.addAction('Delete', lambda: self._on_delete_bookmark(index)) context_menu.addSeparator() context_menu.addAction('New', lambda: self._create_bookmark()) global_pt = self._bookmarks_list.mapToGlobal(pos) context_menu.exec(global_pt) # + button def _create_bookmark(self, index=-1, ptr=''): note = '' if ptr == '': if isinstance(index, int) and index >= 0: ptr = self._bookmarks_model.item(index, 0).text() note = self._bookmarks_model.item(index, 1).text() ptr, input_ = InputDialog.input_pointer(parent=self._app_window, input_content=ptr) else: try: ptr = int(ptr, 16) except: ptr = 0 if ptr > 0: index = self._bookmarks_model.findItems(hex(ptr), Qt.MatchExactly) if len(index) > 0: index = index[0].row() note = self._bookmarks_model.item(index, 1).text() else: index = -1 accept, note = InputDialog.input(hint='Insert notes for %s' % hex(ptr), input_content=note) if accept: if index < 0: self._bookmarks_model.appendRow( [QStandardItem(hex(ptr)), QStandardItem(note)]) else: item = self._bookmarks_model.item(index, 0) item.setText(hex(ptr)) item = self._bookmarks_model.item(index, 1) item.setText(note) # shortcuts/menu def _on_delete_bookmark(self, index): self._bookmarks_model.removeRow(index)
def _setup_ui(self): self.setContentsMargins(0, 0, 0, 0) top_font = QFont() top_font.setBold(True) top_font.setPixelSize(19) # main wrapper main_wrapper = QVBoxLayout() main_wrapper.setContentsMargins(1, 1, 1, 1) # wrapwdgt wrap_wdgt = QWidget() self._top_class_name = QLabel(wrap_wdgt) self._top_class_name.setContentsMargins(10, 10, 10, 10) self._top_class_name.setAttribute(Qt.WA_TranslucentBackground, True) # keep this self._top_class_name.setFont(top_font) self._top_class_name.setStyleSheet('color: #ef5350;') wrap_wdgt.setMaximumHeight(self._top_class_name.height() + 20) main_wrapper.addWidget(wrap_wdgt) # left list left_wrap_wdgt = QWidget() left_v_box = QVBoxLayout(left_wrap_wdgt) left_v_box.setContentsMargins(0, 0, 0, 0) methods_label = QLabel('METHODS') font = methods_label.font() font.setBold(True) methods_label.setFont(font) methods_label.setContentsMargins(10, 0, 10, 2) methods_label.setAttribute(Qt.WA_TranslucentBackground, True) # keep this left_v_box.addWidget(methods_label) self._methods_list = DwarfListView() left_v_box.addWidget(self._methods_list) # center list center_wrap_wdgt = QWidget() center_v_box = QVBoxLayout(center_wrap_wdgt) center_v_box.setContentsMargins(0, 0, 0, 0) methods_label = QLabel('NATIVE FIELDS') methods_label.setFont(font) methods_label.setContentsMargins(10, 0, 10, 2) methods_label.setAttribute(Qt.WA_TranslucentBackground, True) # keep this center_v_box.addWidget(methods_label) self._native_fields_list = DwarfListView() self._native_fields_list.doubleClicked.connect( self._on_native_field_dblclicked) center_v_box.addWidget(self._native_fields_list) # right list right_wrap_wdgt = QWidget() right_v_box = QVBoxLayout(right_wrap_wdgt) right_v_box.setContentsMargins(0, 0, 0, 0) methods_label = QLabel('FIELDS') methods_label.setFont(font) methods_label.setContentsMargins(10, 0, 10, 2) methods_label.setAttribute(Qt.WA_TranslucentBackground, True) # keep this right_v_box.addWidget(methods_label) self._fields_list = DwarfListView() self._fields_list.doubleClicked.connect(self._on_field_dblclicked) right_v_box.addWidget(self._fields_list) # main splitter main_splitter = QSplitter(Qt.Horizontal) main_splitter.setContentsMargins(0, 0, 0, 0) main_splitter.addWidget(left_wrap_wdgt) main_splitter.addWidget(center_wrap_wdgt) main_splitter.addWidget(right_wrap_wdgt) main_splitter.setSizes([250, 100, 100]) main_wrapper.addWidget(main_splitter) main_wrapper.setSpacing(0) self.setLayout(main_wrapper)
def load(self, path: str, is_first_call: bool = True) -> None: if path == self._path: return theme_full_path = os.path.join(path, "theme.json") Logger.log( "d", "Loading theme file: {theme_full_path}".format( theme_full_path=theme_full_path)) try: with open(theme_full_path, encoding="utf-8") as f: data = json.load(f) except EnvironmentError as e: Logger.error( "Unable to load theme file at {theme_full_path}: {err}".format( theme_full_path=theme_full_path, err=e)) return except UnicodeDecodeError: Logger.error( "Theme file at {theme_full_path} is corrupt (invalid UTF-8 bytes)." .format(theme_full_path=theme_full_path)) return # Iteratively load inherited themes try: theme_id = data["metadata"]["inherits"] self.load(Resources.getPath(Resources.Themes, theme_id), is_first_call=False) except FileNotFoundError: Logger.log("e", "Could not find inherited theme %s", theme_id) except KeyError: pass # No metadata or no inherits keyword in the theme.json file if "colors" in data: for name, color in data["colors"].items(): try: c = QColor(color[0], color[1], color[2], color[3]) except IndexError: # Color doesn't have enough components. Logger.log( "w", "Colour {name} doesn't have enough components. Need to have 4, but had {num_components}." .format(name=name, num_components=len(color))) continue # Skip this one then. self._colors[name] = c fonts_dir = os.path.join(path, "fonts") if os.path.isdir(fonts_dir): for root, dirnames, filenames in os.walk(fonts_dir): for filename in filenames: if filename.lower().endswith(".ttf"): QFontDatabase.addApplicationFont( os.path.join(root, filename)) if "fonts" in data: system_font_size = QCoreApplication.instance().font().pointSize() for name, font in data["fonts"].items(): q_font = QFont() q_font.setFamily( font.get("family", QCoreApplication.instance().font().family())) if font.get("bold"): q_font.setBold(font.get("bold", False)) else: q_font.setWeight(font.get("weight", 50)) q_font.setLetterSpacing(QFont.AbsoluteSpacing, font.get("letterSpacing", 0)) q_font.setItalic(font.get("italic", False)) q_font.setPointSize(int( font.get("size", 1) * system_font_size)) q_font.setCapitalization(QFont.AllUppercase if font.get( "capitalize", False) else QFont.MixedCase) self._fonts[name] = q_font if "sizes" in data: for name, size in data["sizes"].items(): s = QSizeF() s.setWidth(round(size[0] * self._em_width)) s.setHeight(round(size[1] * self._em_height)) self._sizes[name] = s iconsdir = os.path.join(path, "icons") if os.path.isdir(iconsdir): for icon in os.listdir(iconsdir): name = os.path.splitext(icon)[0] self._icons[name] = QUrl.fromLocalFile( os.path.join(iconsdir, icon)) imagesdir = os.path.join(path, "images") if os.path.isdir(imagesdir): for image in os.listdir(imagesdir): name = os.path.splitext(image)[0] self._images[name] = QUrl.fromLocalFile( os.path.join(imagesdir, image)) styles = os.path.join(path, "styles.qml") if os.path.isfile(styles): c = QQmlComponent(self._engine, styles) context = QQmlContext(self._engine, self._engine) context.setContextProperty("Theme", self) self._styles = c.create(context) if c.isError(): for error in c.errors(): Logger.log("e", error.toString()) Logger.log("d", "Loaded theme %s", path) self._path = path # only emit the theme loaded signal once after all the themes in the inheritance chain have been loaded if is_first_call: self.themeLoaded.emit()
class EntityWidget: def __init__(self): super().__init__() self.label_font = QFont() self.label_font.setBold(False) self.label_font.setWeight(LABEL_FONT_WEIGHT) self.fieldStyle = 'QLabel { color: black; font: "Segoe UI"; font-size: 14px }' self.fieldErrorStyle = 'QLabel { color: red; font: bold "Segoe UI"; font-size: 14px }' self.fieldMatchStyle = 'QLabel { color: green; font: bold "Segoe UI"; font-size: 14px }' self.fields: list[QLabel] = [] self.labels = [] self.is_prompt = False @abc.abstractmethod def set_fields(self, mi): pass @abc.abstractmethod def set_default_icon(self): pass @abc.abstractmethod def set_inactive_icon(self): pass @abc.abstractmethod def set_bad_icon(self): pass @abc.abstractmethod def mark_mismatch_error(self, kind: str): pass @abc.abstractmethod def reset_state(self): pass def mark_field_unknown(self, field): field.setStyleSheet(self.fieldErrorStyle) field.setText("???") def mark_not_parsable(self): self.set_bad_icon() for f in self.fields: f.setText("???") f.setStyleSheet(self.fieldErrorStyle) # Intentional def make_prompt_preset(self, opacity=DEFAULT_PROMPT_OPACITY): self.is_prompt = True op = QGraphicsOpacityEffect(self) op.setOpacity(opacity) self.setGraphicsEffect(op) self.setAutoFillBackground(False) self.setContextMenuPolicy(Qt.PreventContextMenu) self.set_inactive_icon() for f in self.fields: f.setText(". . . . . .")
def zesDisplay(self): """ Returns a widget which holds information about the average similar home in the area. Similarity is measured through Zillow's api, zillowAPI calculates a weighted average based off scores and values :return widget: Widget with grid layout and labels describing similar avg home zestimates, upper_val, lower_val, and change """ widget = QGroupBox() gridLayout = QGridLayout() simZes = QLabel() myFont = QFont() myFont.setBold(True) simZes.setFont(myFont) simZes.setText("Home's Zestimate Value") # Similar to title, bold gridLayout.addWidget(simZes, 0, 0) # add to 0,0 # Initialize column titles typ = QLabel('Type') amount = QLabel('Amount in Dollars') dif = QLabel('Difference') gridLayout.addWidget(typ, 1, 0) # first col gridLayout.addWidget(amount, 1, 1) # second col gridLayout.addWidget(dif, 1, 2) # third col row2Lab = QLabel("Zestimate:") # Row title as label zillowZestimate = QLabel() # Row value at col 1 zillowZestimate.setText( str(self.propertyObj.zillowAnalysis.comp_mean_weighted_sim)) d2lab = QLabel() # convert diff to string and round to 2 dec places if self.propertyObj.zillowAnalysis.price is not None and self.propertyObj.zillowAnalysis.comp_mean_weighted_sim is not None: d2 = self.propertyObj.zillowAnalysis.price - self.propertyObj.zillowAnalysis.comp_mean_weighted_sim # difference between avg and actual home d2lab.setText(locale.currency(d2, grouping=True)) else: d2 = "None" d2lab.setText(d2) if d2 == "None": print("Diff is none.") elif d2 > 0: d2lab.setStyleSheet( "color: green;") # green if your home is more expensive else: d2lab.setStyleSheet( "color: red;") # red if your house is less expensive gridLayout.addWidget(row2Lab, 2, 0) gridLayout.addWidget(zillowZestimate, 2, 1) gridLayout.addWidget(d2lab, 2, 2) # Repeat above for every row row3Lab = QLabel("Upper Valuation:") zillowUpper = QLabel() zillowUpper.setText( str(self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_high)) d3lab = QLabel() if self.propertyObj.zillowAnalysis.upper_val is not None and self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_high is not None: d3 = self.propertyObj.zillowAnalysis.upper_val - self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_high d3lab.setText(locale.currency(d3, grouping=True)) else: d3 = "None" d3lab.setText(d3) if d3 == "None": print("Diff is none.") elif d3 > 0: d3lab.setStyleSheet("color: green;") else: d3lab.setStyleSheet("color: red;") gridLayout.addWidget(row3Lab, 3, 0) gridLayout.addWidget(zillowUpper, 3, 1) gridLayout.addWidget(d3lab, 3, 2) row4Lab = QLabel("Lower Valuation: ") zillowLower = QLabel() zillowLower.setText( str(self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_low)) d4lab = QLabel() if self.propertyObj.zillowAnalysis.lower_val is not None and self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_low is not None: d4 = self.propertyObj.zillowAnalysis.lower_val - self.propertyObj.zillowAnalysis.comp_mean_weighted_sim_low d4lab.setText(locale.currency(d4, grouping=True)) else: d4 = "None" d4lab.setText(d4) if d4 == "None": print("Diff is none.") elif d4 > 0: d4lab.setStyleSheet("color: green;") # green for pos else: d4lab.setStyleSheet("color: red;") gridLayout.addWidget(row4Lab, 4, 0) gridLayout.addWidget(zillowLower, 4, 1) gridLayout.addWidget(d4lab, 4, 2) row5Lab = QLabel("30 Day Change: ") zillowChange = QLabel() zillowChange.setText( str(self.propertyObj.zillowAnalysis.comp_change_mean_weighted_sim)) d5lab = QLabel() if self.propertyObj.zillowAnalysis.change_30_days is not None and self.propertyObj.zillowAnalysis.comp_change_mean_weighted_sim is not None: d5 = self.propertyObj.zillowAnalysis.change_30_days - self.propertyObj.zillowAnalysis.comp_change_mean_weighted_sim d5lab.setText(locale.currency(d5, grouping=True)) else: d5 = "None" d5lab.setText(d5) if d5 == "None": print("Diff is none.") elif d5 > 0: d5lab.setStyleSheet("color: green;") else: d5lab.setStyleSheet("color: red;") gridLayout.addWidget(row5Lab, 5, 0) gridLayout.addWidget(zillowChange, 5, 1) gridLayout.addWidget(d5lab, 5, 2) widget.setLayout(gridLayout) # add grid to widget return widget
def __init__(self): super().__init__(show_automatic_box=True) main_box = gui.widgetBox(self.controlArea, "Fitter Setting", orientation="vertical", width=self.CONTROL_AREA_WIDTH) button_box = gui.widgetBox(main_box, "", orientation="vertical", width=self.CONTROL_AREA_WIDTH-15, height=70) button_box_1 = gui.widgetBox(button_box, "", orientation="horizontal") self.fit_button = gui.button(button_box_1, self, "Fit", height=40, callback=self.do_fit) self.fit_button.setStyleSheet("color: #252468") font = QFont(self.fit_button.font()) font.setBold(True) font.setPixelSize(18) self.fit_button.setFont(font) self.stop_fit_button = gui.button(button_box_1, self, "STOP", height=40, callback=self.stop_fit) self.stop_fit_button.setStyleSheet("color: red") font = QFont(self.stop_fit_button.font()) font.setBold(True) font.setItalic(True) self.stop_fit_button.setFont(font) button_box_2 = gui.widgetBox(button_box, "", orientation="horizontal") gui.button(button_box_2, self, "Send Current Fit", height=40, callback=self.send_current_fit) gui.button(button_box_2, self, "Save Data", height=40, callback=self.save_data) orangegui.separator(main_box) self.cb_fitter = orangegui.comboBox(main_box, self, "fitter_name", label="Fit algorithm", items=FitterName.tuple(), orientation="horizontal") iteration_box = gui.widgetBox(main_box, "", orientation="horizontal", width=250) gui.lineEdit(iteration_box, self, "n_iterations", "Nr. Iterations", labelWidth=80, valueType=int, validator=QIntValidator()) orangegui.checkBox(iteration_box, self, "is_incremental", "Incremental") iteration_box = gui.widgetBox(main_box, "", orientation="vertical", width=250) self.le_current_iteration = gui.lineEdit(iteration_box, self, "current_iteration", "Current Iteration", labelWidth=120, valueType=int, orientation="horizontal") self.le_current_iteration.setReadOnly(True) self.le_current_iteration.setStyleSheet("background-color: #FAFAB0; color: #252468") font = QFont(self.le_current_iteration.font()) font.setBold(True) self.le_current_iteration.setFont(font) orangegui.separator(main_box) self.plot_box = gui.widgetBox(main_box, "Plotting Options", orientation="vertical", width=self.CONTROL_AREA_WIDTH-20) self.cb_interactive = orangegui.checkBox(self.plot_box, self, "is_interactive", "Refresh Plots while fitting", callback=self.set_interactive) orangegui.separator(self.plot_box, height=8) self.cb_show_wss_gof = orangegui.checkBox(self.plot_box, self, "show_wss_gof", "Refresh W.S.S. and G.o.F. plots" ) orangegui.separator(self.plot_box) self.cb_show_ipf = orangegui.checkBox(self.plot_box, self, "show_ipf", "Refresh Instrumental Profile plots") orangegui.separator(self.plot_box) self.cb_show_shift = orangegui.checkBox(self.plot_box, self, "show_shift", "Refresh Calibration Shift plots") orangegui.separator(self.plot_box) self.cb_show_size = orangegui.checkBox(self.plot_box, self, "show_size", "Refresh Size Distribution plot") orangegui.separator(self.plot_box) self.cb_show_warren = orangegui.checkBox(self.plot_box, self, "show_warren", "Refresh Warren's plot") self.set_interactive() tab_free_out = gui.widgetBox(main_box, "Free Output Parameters", orientation="vertical") self.scrollarea_free_out = QScrollArea(tab_free_out) self.scrollarea_free_out.setMinimumWidth(self.CONTROL_AREA_WIDTH-55) self.scrollarea_free_out.setMaximumHeight(170) def write_text(): self.free_output_parameters_text = self.text_area_free_out.toPlainText() self.text_area_free_out = gui.textArea(height=1000, width=1000, readOnly=False) self.text_area_free_out.setText(self.free_output_parameters_text) self.text_area_free_out.textChanged.connect(write_text) self.scrollarea_free_out.setWidget(self.text_area_free_out) self.scrollarea_free_out.setWidgetResizable(1) tab_free_out.layout().addWidget(self.scrollarea_free_out, alignment=Qt.AlignHCenter) self.tabs = gui.tabWidget(self.mainArea) self.tab_fit_in = gui.createTabPage(self.tabs, "Fit Input Parameters") self.tab_plot = gui.createTabPage(self.tabs, "Plots") self.tab_fit_out = gui.createTabPage(self.tabs, "Fit Output Parameters") self.tabs_plot = gui.tabWidget(self.tab_plot) self.tab_plot_fit_data = gui.createTabPage(self.tabs_plot, "Fit") self.tab_plot_fit_wss = gui.createTabPage(self.tabs_plot, "W.S.S.") self.tab_plot_fit_gof = gui.createTabPage(self.tabs_plot, "G.o.F.") self.tab_plot_ipf = gui.createTabPage(self.tabs_plot, "Instrumental Profile") self.tab_plot_size = gui.createTabPage(self.tabs_plot, "Size Distribution") self.tab_plot_strain = gui.createTabPage(self.tabs_plot, "Warren's Plot") self.std_output = gui.textArea(height=100, width=800) self.std_output.setStyleSheet("font-family: Courier, monospace;") out_box = gui.widgetBox(self.mainArea, "System Output", addSpace=False, orientation="horizontal") out_box.layout().addWidget(self.std_output) self.tabs_plot_fit_data = gui.tabWidget(self.tab_plot_fit_data) self.tabs_plot_ipf = gui.tabWidget(self.tab_plot_ipf) self.tab_plot_fwhm = gui.createTabPage(self.tabs_plot_ipf, "Caglioti's FWHM") self.tab_plot_eta = gui.createTabPage(self.tabs_plot_ipf, "Caglioti's \u03b7") self.tab_plot_lab6 = gui.createTabPage(self.tabs_plot_ipf, "LaB6 Tan Correction") self.build_plot_fit() self.plot_fit_wss = PlotWindow() self.plot_fit_wss.setDefaultPlotLines(True) self.plot_fit_wss.setActiveCurveColor(color="#00008B") self.plot_fit_wss.setGraphXLabel("Iteration") self.plot_fit_wss.setGraphYLabel("WSS") self.tab_plot_fit_wss.layout().addWidget(self.plot_fit_wss) self.plot_fit_gof = PlotWindow() self.plot_fit_gof.setDefaultPlotLines(True) self.plot_fit_gof.setActiveCurveColor(color="#00008B") self.plot_fit_gof.setGraphXLabel("Iteration") self.plot_fit_gof.setGraphYLabel("GOF") self.tab_plot_fit_gof.layout().addWidget(self.plot_fit_gof) self.plot_size = PlotWindow() self.plot_size.setDefaultPlotLines(True) self.plot_size.setActiveCurveColor(color="#00008B") self.plot_size.setGraphTitle("Crystalline Domains Size Distribution") self.plot_size.setGraphXLabel(r"D [nm]") self.plot_size.setGraphYLabel("Frequency") self.tab_plot_size.layout().addWidget(self.plot_size) self.plot_strain = PlotWindow(control=True) legendsDockWidget = LegendsDockWidget(plot=self.plot_strain) self.plot_strain._legendsDockWidget = legendsDockWidget self.plot_strain._dockWidgets.append(legendsDockWidget) self.plot_strain.addDockWidget(qt.Qt.RightDockWidgetArea, legendsDockWidget) self.plot_strain._legendsDockWidget.setFixedWidth(120) self.plot_strain.getLegendsDockWidget().show() self.plot_strain.setDefaultPlotLines(True) self.plot_strain.setActiveCurveColor(color="#00008B") self.plot_strain.setGraphTitle("Warren's plot") self.plot_strain.setGraphXLabel(r"L [nm]") self.plot_strain.setGraphYLabel("$\sqrt{<{\Delta}L^{2}>}$ [nm]") self.tab_plot_strain.layout().addWidget(self.plot_strain) box = gui.widgetBox(self.tab_plot_fwhm, "", orientation="horizontal") boxl = gui.widgetBox(box, "", orientation="vertical") boxr = gui.widgetBox(box, "", orientation="vertical", width=150) def set_fwhm_autoscale(): self.le_fwhm_xmin.setEnabled(self.fwhm_autoscale==0) self.le_fwhm_xmax.setEnabled(self.fwhm_autoscale==0) self.le_fwhm_ymin.setEnabled(self.fwhm_autoscale==0) self.le_fwhm_ymax.setEnabled(self.fwhm_autoscale==0) orangegui.checkBox(boxr, self, "fwhm_autoscale", "Autoscale", callback=set_fwhm_autoscale) self.le_fwhm_xmin = gui.lineEdit(boxr, self, "fwhm_xmin", "2\u03b8 min", labelWidth=70, valueType=float) self.le_fwhm_xmax = gui.lineEdit(boxr, self, "fwhm_xmax", "2\u03b8 max", labelWidth=70, valueType=float) self.le_fwhm_ymin = gui.lineEdit(boxr, self, "fwhm_ymin", "FWHM min", labelWidth=70, valueType=float) self.le_fwhm_ymax = gui.lineEdit(boxr, self, "fwhm_ymax", "FWHM max", labelWidth=70, valueType=float) gui.button(boxr, self, "Refresh", height=40, callback=self.refresh_caglioti_fwhm) set_fwhm_autoscale() self.plot_ipf_fwhm = PlotWindow() self.plot_ipf_fwhm.setDefaultPlotLines(True) self.plot_ipf_fwhm.setActiveCurveColor(color="#00008B") self.plot_ipf_fwhm.setGraphXLabel("2\u03b8 (deg)") self.plot_ipf_fwhm.setGraphYLabel("FWHM (deg)") boxl.layout().addWidget(self.plot_ipf_fwhm) box = gui.widgetBox(self.tab_plot_eta, "", orientation="horizontal") boxl = gui.widgetBox(box, "", orientation="vertical") boxr = gui.widgetBox(box, "", orientation="vertical", width=150) def set_eta_autoscale(): self.le_eta_xmin.setEnabled(self.eta_autoscale==0) self.le_eta_xmax.setEnabled(self.eta_autoscale==0) self.le_eta_ymin.setEnabled(self.eta_autoscale==0) self.le_eta_ymax.setEnabled(self.eta_autoscale==0) orangegui.checkBox(boxr, self, "eta_autoscale", "Autoscale", callback=set_eta_autoscale) self.le_eta_xmin = gui.lineEdit(boxr, self, "eta_xmin", "2\u03b8 min", labelWidth=70, valueType=float) self.le_eta_xmax = gui.lineEdit(boxr, self, "eta_xmax", "2\u03b8 max", labelWidth=70, valueType=float) self.le_eta_ymin = gui.lineEdit(boxr, self, "eta_ymin", "\u03b7 min", labelWidth=70, valueType=float) self.le_eta_ymax = gui.lineEdit(boxr, self, "eta_ymax", "\u03b7 max", labelWidth=70, valueType=float) gui.button(boxr, self, "Refresh", height=40, callback=self.refresh_caglioti_eta) set_eta_autoscale() self.plot_ipf_eta = PlotWindow() self.plot_ipf_eta.setDefaultPlotLines(True) self.plot_ipf_eta.setActiveCurveColor(color="#00008B") self.plot_ipf_eta.setGraphXLabel("2\u03b8 (deg)") self.plot_ipf_eta.setGraphYLabel("\u03b7") boxl.layout().addWidget(self.plot_ipf_eta) box = gui.widgetBox(self.tab_plot_lab6, "", orientation="horizontal") boxl = gui.widgetBox(box, "", orientation="vertical") boxr = gui.widgetBox(box, "", orientation="vertical", width=150) def set_lab6_autoscale(): self.le_lab6_xmin.setEnabled(self.lab6_autoscale==0) self.le_lab6_xmax.setEnabled(self.lab6_autoscale==0) self.le_lab6_ymin.setEnabled(self.lab6_autoscale==0) self.le_lab6_ymax.setEnabled(self.lab6_autoscale==0) orangegui.checkBox(boxr, self, "lab6_autoscale", "Autoscale", callback=set_lab6_autoscale) self.le_lab6_xmin = gui.lineEdit(boxr, self, "lab6_xmin", "2\u03b8 min", labelWidth=70, valueType=float) self.le_lab6_xmax = gui.lineEdit(boxr, self, "lab6_xmax", "2\u03b8 max", labelWidth=70, valueType=float) self.le_lab6_ymin = gui.lineEdit(boxr, self, "lab6_ymin", "\u0394(2\u03b8) min", labelWidth=70, valueType=float) self.le_lab6_ymax = gui.lineEdit(boxr, self, "lab6_ymax", "\u0394(2\u03b8) max", labelWidth=70, valueType=float) gui.button(boxr, self, "Refresh", height=40, callback=self.refresh_lab6) set_lab6_autoscale() self.plot_ipf_lab6 = PlotWindow() self.plot_ipf_lab6.setDefaultPlotLines(True) self.plot_ipf_lab6.setActiveCurveColor(color="#00008B") self.plot_ipf_lab6.setGraphXLabel("2\u03b8 (deg)") self.plot_ipf_lab6.setGraphYLabel("\u0394(2\u03b8) (deg)") boxl.layout().addWidget(self.plot_ipf_lab6) # ------------------- self.table_fit_in = self.create_table_widget(is_output=False) self.tab_fit_in.layout().addWidget(self.table_fit_in, alignment=Qt.AlignHCenter) # ------------------- self.table_fit_out = self.create_table_widget() self.tab_fit_out.layout().addWidget(self.table_fit_out, alignment=Qt.AlignHCenter)
def setupUi(self, MainWindow): QDesktopWidget.screenGeometry(self, ) MainWindow.resize(1200, 800) #메인 화면 색상py self.setStyleSheet("color: black;" "background-color: white;") font = QFont() font.setFamily("NanumGothic") MainWindow.setFont(font) self.centralwidget = QWidget(MainWindow) self.label = QLabel(self.centralwidget) self.label.setGeometry(QRect(20, 20, 101, 31)) font = QFont() font.setFamily("NanumGothic") font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.button_add = QPushButton(self.centralwidget) self.button_add.setGeometry(QRect(60, 730, 131, 34)) #버튼 스타일 변경 self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_add.setFont(staticValues.buttonFont) self.button_modi = QPushButton(self.centralwidget) self.button_modi.setGeometry(QRect(260, 730, 131, 34)) self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_modi.setFont(staticValues.buttonFont) self.button_del = QPushButton(self.centralwidget) self.button_del.setGeometry(QRect(460, 730, 131, 34)) self.button_del.setStyleSheet(staticValues.redButtonStyleSheet) self.button_del.setFont(staticValues.buttonFont) self.button_upload = QPushButton(self.centralwidget) self.button_upload.setGeometry(QRect(790, 730, 131, 34)) self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_upload.setFont(staticValues.buttonFont) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QRect(40, 70, 1121, 621)) self.tab = QWidget() self.tab.layout = QVBoxLayout() self.tabWidget.addTab(self.tab, "회원 목록") self.tableWidget = QTableWidget(self.tab) self.tableWidget.setGeometry(QRect(0, 0, 1111, 591)) self.tableWidget.setObjectName("회원 목록") self.tableWidget.setColumnCount(13) self.tableWidget.setRowCount(0) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels([ "회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근", "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소" ]) # self.tableView = QTableWidget() # self.tableView.setColumnCount(5) # self.tableView.setRowCount(3) # self.tab.layout.addWidget(self.tableView) # self.tab.setLayout(self.tab.layout) # self.tab_2 = QWidget() # self.tabWidget.addTab(self.tab_2, "") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
def init_ui(self): vbl_0 = QVBoxLayout(self) self.label_title = QLabel(self) font = QFont() font.setPointSize(18) font.setBold(True) self.label_title.setFont(font) self.label_title.setContentsMargins(2, 5, 5, 7) self.label_title.setStyleSheet(Style.h2()) lbl_color = QLabel(" ", self) lbl_color.setStyleSheet(Style.configure_title()) hbox1 = QHBoxLayout() hbox1.addWidget(lbl_color) hbox1.addWidget(self.label_title, 1) self.btn_help = QPushButton(_("Help..."), self) self.btn_help.clicked.connect(self.on_button_help_clicked) hbox1.addWidget(self.btn_help) hbox1.setContentsMargins(0, 0, 0, 5) vbl_0.addLayout(hbox1) vbl_0.insertSpacing(2, 25) grid = QGridLayout() grid.setContentsMargins(0, 0, 0, 0) # left, top, right, bottom grid.setVerticalSpacing(5) self.para_widgets = { "resource_dir": ParaLine(self, "resource_dir", ParaWidget.str_conv(), grid, 3, True), "metadata_dir": ParaLine(self, "metadata_dir", ParaWidget.str_conv(), grid, 5, False), "description_dir": ParaLine(self, "description_dir", ParaWidget.str_conv(), grid, 7, True), "plugin_dir": ParaLine(self, "plugin_dir", ParaWidget.str_conv(), grid, 9, True), "url_prefix": ParaLine(self, "url_prefix", ParaWidget.str_conv(), grid, 11, False), "strategy": ParaStrategyDrop(self, "strategy", grid, 15), "max_items_in_list": ParaLine(self, "max_items_in_list", ParaWidget.int_conv(), grid, 17, False, width=100), "zero_fill_filename": ParaLine(self, "zero_fill_filename", ParaWidget.int_conv(), grid, 19, False, width=100), "is_saving_pretty_xml": ParaCheck(self, "is_saving_pretty_xml", grid, 21), "is_saving_sitemaps": ParaCheck(self, "is_saving_sitemaps", grid, 22), "has_wellknown_at_root": ParaCheck(self, "has_wellknown_at_root", grid, 23) } self.button_reset = QPushButton(_("Reset"), self) self.button_reset.clicked.connect(self.on_button_reset_clicked) grid.addWidget(self.button_reset, 24, 3) vbl_0.addLayout(grid) vbl_0.addStretch(1) self.setLayout(vbl_0)
def __init__(self, show_automatic_box=True): super().__init__(show_automatic_box=show_automatic_box) self.runaction = widget.OWAction("Run Shadow/Trace", self) self.runaction.triggered.connect(self.traceOpticalElement) self.addAction(self.runaction) ################################# # FIX A WEIRD BEHAVIOUR AFTER DISPLAY # THE WIDGET: PROBABLY ON SIGNAL MANAGER self.dumpSettings() self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH) button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") self.button_trace = gui.button(button_box, self, "Run Shadow/Trace", callback=self.traceOpticalElement) font = QFont(self.button_trace.font()) font.setBold(True) self.button_trace.setFont(font) palette = QPalette( self.button_trace.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) self.button_trace.setPalette(palette) # assign new palette self.button_trace.setFixedHeight(45) self.button_reset = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings) font = QFont(self.button_reset.font()) font.setItalic(True) self.button_reset.setFont(font) palette = QPalette( self.button_reset.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) self.button_reset.setPalette(palette) # assign new palette self.button_reset.setFixedHeight(45) self.button_reset.setFixedWidth(150) gui.separator(self.controlArea) self.tabs_setting = oasysgui.tabWidget(self.controlArea) self.tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT - 5) self.tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5) self.tab_bas = oasysgui.createTabPage(self.tabs_setting, "Basic Setting") self.tab_adv = oasysgui.createTabPage(self.tabs_setting, "Advanced Setting") adv_other_box = oasysgui.widgetBox(self.tab_adv, "Optional file output", addSpace=False, orientation="vertical") gui.comboBox(adv_other_box, self, "file_to_write_out", label="Files to write out", labelWidth=150, items=[ "All", "Mirror", "Image", "None", "Debug (All + start.xx/end.xx)" ], sendSelectedValue=False, orientation="horizontal")
def __init__(self, parent=None): super(Main_MUESTRA, self).__init__(parent) self.setWindowTitle("EXADATA") self.setFixedSize(900, 600) self.centralwidget = QtWidgets.QWidget(self) self.centralwidget.setObjectName("centralwidget") # FRAME paleta = QPalette() paleta.setColor(QPalette.Background, QColor(51, 0, 102)) frame = QFrame(self) frame.setFrameShape(QFrame.NoFrame) frame.setFrameShadow(QFrame.Sunken) frame.setAutoFillBackground(True) frame.setPalette(paleta) frame.setFixedWidth(950) frame.setFixedHeight(100) frame.move(0, 0) labelIcono = QLabel(frame) labelIcono.setFixedWidth(65) labelIcono.setFixedHeight(65) labelIcono.setPixmap(QPixmap("icono.jpg").scaled(65, 65, Qt.KeepAspectRatio, Qt.SmoothTransformation)) labelIcono.move(10, 28) fuenteTitulo = QFont() fuenteTitulo.setPointSize(25) fuenteTitulo.setBold(True) labelTitulo = QLabel("<font color='white'>EXADATA</font>", frame) labelTitulo.setFont(fuenteTitulo) labelTitulo.move(85, 30) fuenteSubtitulo = QFont() fuenteSubtitulo.setPointSize(13) labelSubtitulo = QLabel("<font color='white'>Análisis de Tweets " , frame) labelSubtitulo.setFont(fuenteSubtitulo) labelSubtitulo.move(85, 68) # BARRA self.progressBar = QtWidgets.QProgressBar(self.centralwidget) self.progressBar.setGeometry(QtCore.QRect(10, 480, 510, 23)) self.progressBar.setProperty("value", 24) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") #inicio tabla self.tabla = QtWidgets.QTableWidget(self.centralwidget) # formato tabla posx,posy,tamx,tamy self.tabla.setGeometry(QtCore.QRect(10, 120, 510, 400)) self.tabla.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.tabla.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents) self.tabla.setColumnCount(4) self.tabla.setObjectName("tabla") self.tabla.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(2, item) item = QtWidgets.QTableWidgetItem() self.tabla.setHorizontalHeaderItem(3, item) self.tabla.horizontalHeader().setDefaultSectionSize(120) self.tabla.horizontalHeader().setStretchLastSection(True) self.tabla.verticalHeader().setStretchLastSection(False) self.tabla.cellClicked.connect(self.ConsultarFecha) #fin tabla # BOTONES # boton exportar_bd self.bt_exportar_bd = QtWidgets.QPushButton(self.centralwidget) self.bt_exportar_bd.setGeometry(QtCore.QRect(550, 400, 100, 20)) self.bt_exportar_bd.setObjectName("bt_exportar_bd") self.bt_exportar_bd.clicked.connect(self.Exportar_Fecha) # boton exportar_bd2 self.bt_exportar_bd2 = QtWidgets.QPushButton(self.centralwidget) self.bt_exportar_bd2.setGeometry(QtCore.QRect(635, 460, 100, 20)) self.bt_exportar_bd2.setObjectName("bt_exportar_bd2") self.bt_exportar_bd2.clicked.connect(self.Exportar_Cantidad) # CUADRO TEXTO self.muestra_cantidad = QtWidgets.QLineEdit(self.centralwidget) self.muestra_cantidad.setGeometry(QtCore.QRect(550, 460, 50, 20)) self.muestra_cantidad.setObjectName("muestra_cantidad") #================================================================================= self.setCentralWidget(self.centralwidget) #CALENDARIO # formato tabla posx,posy,tamx,tamy self.calendario = QtWidgets.QCalendarWidget(self.centralwidget) self.calendario.setGeometry(QtCore.QRect(550, 120, 312, 183)) self.calendario.setStyleSheet("") self.calendario.setStyleSheet("alternate-background-color: rgb(118, 148, 255);") self.calendario.setObjectName("calendario") #LABEL MUESTRA POR FECHA self.label_muestraFecha = QtWidgets.QLabel(self.centralwidget) self.label_muestraFecha.setGeometry(QtCore.QRect(550, 330, 121, 16)) self.label_muestraFecha.setObjectName("label_muestraFecha") #LABEL MUESTRA DE TODA LA BASE self.label_muestraToda = QtWidgets.QLabel(self.centralwidget) self.label_muestraToda.setGeometry(QtCore.QRect(550, 440, 200, 16)) self.label_muestraToda.setObjectName("label_muestraToda") self.fechaInicio = QtWidgets.QDateEdit(self.centralwidget) self.fechaInicio.setGeometry(QtCore.QRect(550, 370, 110, 22)) self.fechaInicio.setObjectName("fechaInicio") self.fechaInicio.setCalendarPopup(True) self.fechaTermino = QtWidgets.QDateEdit(self.centralwidget) self.fechaTermino.setGeometry(QtCore.QRect(720, 370, 110, 22)) self.fechaTermino.setObjectName("fechaTermino") self.fechaTermino.setCalendarPopup(True) self.fechaInicio.setDate(QtCore.QDate.currentDate()) self.fechaTermino.setDate(QtCore.QDate.currentDate()) self.incioLetra = QtWidgets.QLabel(self.centralwidget) self.incioLetra.setGeometry(QtCore.QRect(550, 350, 111, 16)) self.incioLetra.setObjectName("incioLetra") self.terminoLetra = QtWidgets.QLabel(self.centralwidget) self.terminoLetra.setGeometry(QtCore.QRect(720, 350, 111, 16)) self.terminoLetra.setObjectName("terminoLetra") #BARRA MENU self.menubar = QtWidgets.QMenuBar(self) self.menubar.setGeometry(QtCore.QRect(0, 0, 1000, 21)) self.menubar.setObjectName("menubar") self.Programas = QtWidgets.QMenu(self.menubar) self.BaseDeDatos = QtWidgets.QAction(self) self.menubar.addAction(self.Programas.menuAction()) self.Programas.addAction(self.BaseDeDatos) self.BaseDeDatos.triggered.connect(self.close) self.Ayuda = QtWidgets.QMenu(self.menubar) self.SobreQue = QtWidgets.QAction(self) self.menubar.addAction(self.Ayuda.menuAction()) self.Ayuda.addAction(self.SobreQue) self.SobreQue.triggered.connect(self.AYUDA) # boton recarga_bd self.bt_recarga_bd = QtWidgets.QPushButton(self.centralwidget) self.bt_recarga_bd.setGeometry(QtCore.QRect(10, 530, 510, 20)) self.bt_recarga_bd.setObjectName("bt_recarga_bd") self.bt_recarga_bd.clicked.connect(self.CargarTabla) self.retranslateUi(self) QtCore.QMetaObject.connectSlotsByName(self) #new table self.tabla_master() self.CargarTabla() self.progressBar.hide()
def setupUi(self): self.win.setWindowTitle(f"Tassomai Automation v{__version__}") self.win.setWindowIcon(QIcon(path('images', 'logo.png'))) self.win.resize(665, 580) self.centralwidget = QWidget(self.win) self.formLayout = QFormLayout(self.centralwidget) self.formLayout.setContentsMargins(5, 0, 5, -1) self.topFrame = QFrame(self.centralwidget) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.topFrame.sizePolicy().hasHeightForWidth()) self.topFrame.setSizePolicy(sizePolicy) self.topFrame.setAutoFillBackground(True) self.topFrame.setFrameShape(QFrame.StyledPanel) self.topFrame.setFrameShadow(QFrame.Raised) self.gridLayout = QGridLayout(self.topFrame) self.tassomaiImage = QLabel(self.topFrame) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tassomaiImage.sizePolicy().hasHeightForWidth()) self.tassomaiImage.setSizePolicy(sizePolicy) self.tassomaiImage.setPixmap(QPixmap(path('images', 'banner.png'))) self.gridLayout.addWidget(self.tassomaiImage, 0, 0, 1, 1) self.formLayout.setWidget(0, QFormLayout.SpanningRole, self.topFrame) self.tab = QTabWidget(self.centralwidget) self.main_tab = QWidget() self.automation_tab = QWidget() self.gridLayout_4 = QGridLayout(self.main_tab) self.gridLayout_4.setContentsMargins(0, 0, 0, 0) self.main_frame = QFrame(self.main_tab) self.main_frame.setAutoFillBackground(True) self.main_frame.setFrameShape(QFrame.StyledPanel) self.main_frame.setFrameShadow(QFrame.Raised) self.gridLayout_2 = QGridLayout(self.main_frame) self.gridLayout_2.setContentsMargins(5, 6, 2, -1) self.gridLayout_2.setVerticalSpacing(10) self.gridLayout_5 = QGridLayout(self.automation_tab) self.gridLayout_5.setContentsMargins(0, 0, 0, 0) self.automation_frame = QFrame(self.automation_tab) self.automation_frame.setAutoFillBackground(True) self.automation_frame.setFrameShape(QFrame.StyledPanel) self.automation_frame.setFrameShadow(QFrame.Raised) self.delayLayout = QHBoxLayout() self.delayLayout.setContentsMargins(0, 0, 0, 0) self.delayLayout.setSpacing(3) self.delay = QCheckBox(self.main_frame) font = QFont() font.setPointSize(10) self.delay.setFont(font) self.delayLayout.addWidget(self.delay) self.amountOfDelay = QDoubleSpinBox(self.main_frame) self.amountOfDelay.setMinimumWidth(70) self.amountOfDelay.setMaximum(25.00) self.delayLayout.addWidget(self.amountOfDelay) self.label03 = QLabel(self.main_frame) self.label03.setSizePolicy(sizePolicy) self.label03.setFont(font) self.delayLayout.addWidget(self.label03) self.amountOfDelay2 = QDoubleSpinBox(self.main_frame) self.amountOfDelay2.setMinimumWidth(70) self.amountOfDelay2.setMaximum(25.00) self.delayLayout.addWidget(self.amountOfDelay2) self.label3 = QLabel(self.main_frame) self.label3.setSizePolicy(sizePolicy) self.label3.setFont(font) self.delayLayout.addWidget(self.label3) self.whenDelay = QComboBox(self.main_frame) self.whenDelay.addItem("question") self.whenDelay.addItem("quiz") self.whenDelay.setMaximumWidth(100) self.delayLayout.addWidget(self.whenDelay) self.verticalSpacer1 = QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding) self.delayLayout.addItem(self.verticalSpacer1) self.gridLayout_2.addLayout(self.delayLayout, 2, 0, 1, 1) self.randomnessLayout = QHBoxLayout() self.randomnessLayout.setContentsMargins(0, 0, 0, 0) self.randomnessLayout.setSpacing(3) self.randomness = QCheckBox(self.main_frame) self.randomness.setFont(font) self.randomness.setMaximumWidth(338) self.randomnessLayout.addWidget(self.randomness) self.randomnessAmount = QSpinBox(self.main_frame) self.randomnessAmount.setMinimumWidth(70) self.randomnessAmount.setMaximum(600) self.randomnessLayout.addWidget(self.randomnessAmount) self.label4 = QLabel(self.main_frame) self.label4.setSizePolicy(sizePolicy) self.label4.setFont(font) self.randomnessLayout.addWidget(self.label4) self.gridLayout_2.addLayout(self.randomnessLayout, 3, 0, 1, 1) self.dailyGoal = QCheckBox(self.main_frame) font = QFont() font.setPointSize(10) self.dailyGoal.setFont(font) self.gridLayout_2.addWidget(self.dailyGoal, 4, 0, 1, 1) self.bonusGoal = QCheckBox(self.main_frame) self.bonusGoal.setFont(font) self.gridLayout_2.addWidget(self.bonusGoal, 5, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.label1 = QLabel(self.main_frame) sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label1.sizePolicy().hasHeightForWidth()) self.label1.setSizePolicy(sizePolicy) font = QFont() font.setPointSize(10) self.label1.setFont(font) self.horizontalLayout.addWidget(self.label1) self.maxQuizes = QSpinBox(self.main_frame) self.maxQuizes.setMinimum(1) self.maxQuizes.setMaximum(1000000) self.maxQuizes.setProperty("value", 1000) self.horizontalLayout.addWidget(self.maxQuizes) self.label2 = QLabel(self.main_frame) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label2.sizePolicy().hasHeightForWidth()) self.label2.setSizePolicy(sizePolicy) font = QFont() font.setPointSize(10) self.label2.setFont(font) self.horizontalLayout.addWidget(self.label2) self.gridLayout_2.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.userBox = QGroupBox(self.main_frame) font = QFont() font.setPointSize(9) font.setBold(False) font.setWeight(50) self.userBox.setFont(font) self.gridLayout_3 = QGridLayout(self.userBox) self.emailTassomaiLabel = QLabel(self.userBox) self.gridLayout_3.addWidget(self.emailTassomaiLabel, 0, 0, 1, 1) self.emailTassomai = QLineEdit(self.userBox) self.gridLayout_3.addWidget(self.emailTassomai, 0, 1, 1, 1) self.passwordTassomaiLabel = QLabel(self.userBox) self.gridLayout_3.addWidget(self.passwordTassomaiLabel, 1, 0, 1, 1) self.passwordTassomai = QLineEdit(self.userBox) self.passwordTassomai.setEchoMode(QLineEdit.Password) self.gridLayout_3.addWidget(self.passwordTassomai, 1, 1, 1, 1) self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout_3.addItem(self.verticalSpacer, 2, 0, 1, 1) self.gridLayout_4.addWidget(self.main_frame, 0, 0, 1, 1) self.gridLayout_5.addWidget(self.automation_frame, 0, 0, 1, 1) self.tab.addTab(self.main_tab, "") self.tab.addTab(self.automation_tab, "") self.formLayout.setWidget(1, QFormLayout.SpanningRole, self.tab) self.gridLayout_2.addWidget(self.userBox, 0, 0, 1, 1) self.buttonsLayout = QHBoxLayout() self.bottom_frame = QFrame(self.centralwidget) self.bottom_frame.setFrameShape(QFrame.StyledPanel) self.bottom_frame.setFrameShadow(QFrame.Raised) self.gridLayout_7 = QGridLayout(self.bottom_frame) self.gridLayout_7.setContentsMargins(0, 0, 0, 0) self.startButton = QPushButton(self.bottom_frame) self.buttonsLayout.addWidget(self.startButton) self.stopButton = QPushButton(self.bottom_frame) self.buttonsLayout.addWidget(self.stopButton) self.gridLayout_7.addLayout(self.buttonsLayout, 0, 0, 1, 1) self.output = QTextEdit(self.bottom_frame) self.gridLayout_7.addWidget(self.output, 1, 0, 1, 1) self.formLayout.setWidget(2, QFormLayout.SpanningRole, self.bottom_frame) self.win.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(self.win) self.menubar.setGeometry(QRect(0, 0, 665, 21)) self.tools_menu = QMenu(self.menubar) self.uninstall_option = QAction() self.tools_menu.addAction(self.uninstall_option) self.menubar.addAction(self.tools_menu.menuAction()) self.win.setMenuBar(self.menubar) self.createTable() self.retranslateUi() self.tab.setCurrentIndex(0) self.tab.currentChanged['int'].connect(lambda k: self.bottom_frame.hide() if k != 0 else self.bottom_frame.show()) QMetaObject.connectSlotsByName(self.win)
top.setGeometry(15, 70, 570, 175) top.setStyleSheet('color: black; background: darkgray;border-style: solid; border-width: 1px; border-radius: 5px; border-color: black; }"') top.lower() # Create path textbox file_path_textbox = QLineEdit(win) file_path_textbox.move(120, 150) file_path_textbox.resize(450, 30) file_path_textbox.setStyleSheet( 'background: lightblue;border-style: solid; border-width: 1px; border-radius: 5px; border-color: black; }"') # create performance display performance_display = QPushButton(win) performance_display.setText("") myFont=QFont() myFont.setBold(True) performance_display.setFont(myFont) performance_display.setGeometry(50, 200, 500, 30) performance_display.setStyleSheet("QPushButton { color: yellow;background-color: darkgray; border-style: solid }" "QPushButton:pressed { background-color: darkgray }" ) # define button for collection collect_Button = QPushButton('Find and Scan', win) collect_Button.setGeometry(240, 200,115,30) collect_Button.setStyleSheet("QPushButton { background-color: lightgray; border-style: outset; border-width: 2px; border-radius: 5px; border-color: lightgray; padding: 4px; }" "QPushButton:pressed { background-color: darkblue }" ) # define button for 'blacklist' blacklist_Button = QPushButton('', win) blacklist_Button.setGeometry(175, 400,115,30) blacklist_Button.setStyleSheet("QPushButton { color: black; background-color: pink; border-style: outset; border-width: 2px; border-radius: 15px; border-color: lightgray; padding: 4px; }"