def refresh(self): """Refreshes the list of assignments for the current or newly selected course. Also changes the course name at the top of the page if the course has changed. """ self.tablewidget_assignments.clear() if self.app.planner.is_empty() or self.app.planner.get_current_course() is None: self._enable_course_page(False) else: self._enable_course_page(True) self.tablewidget_assignments.disconnect() current_course = self.app.planner.get_current_course() assignments = self.app.planner.get_assignments(current_course[0], self.app.settings.show_completed()) n_items = len(assignments) self.tablewidget_assignments.setRowCount(n_items) for i in range(n_items): _id, _name, _course, _completed, _due_date = assignments[i] # Completed Column completed = QTableWidgetItem() completed.setCheckState(2 if _completed else 0) self.tablewidget_assignments.setItem(i, 0, completed) # Name Column name = DataLabel(_name) name.setObjectName("AssignmentLabel") name.set_data(_id) name.setFont(QApplication.font()) self.tablewidget_assignments.setCellWidget(i, 1, name) # Due Date Column y, m, d = _due_date.split("-") due_date = QLabel(f"{m}/{d}") due_date.setObjectName("AssignmentLabel") due_date.setFont(QApplication.font()) self.tablewidget_assignments.setCellWidget(i, 2, due_date) # Edit Column edit = QPushButton("•••") edit.setObjectName("AssignmentEdit") edit.setCursor(Qt.PointingHandCursor) edit.clicked.connect(lambda clicked, id=_id: self.update_assignment(id)) self.tablewidget_assignments.setCellWidget(i, 3, edit) # Delete Column delete = QPushButton("X") delete.setObjectName("AssignmentDelete") delete.setCursor(Qt.PointingHandCursor) delete.clicked.connect(lambda clicked, id=_id: self.delete_assignment(id)) self.tablewidget_assignments.setCellWidget(i, 4, delete) self.tablewidget_assignments.itemChanged.connect(self.item_changed)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.font = QApplication.font() self.font_bold = QApplication.font() self.font.setPixelSize(options.font_size) self.font_bold.setPixelSize(options.font_size) self.font_bold.setBold(True) self.fm = QFontMetrics(self.font) self.fm_bold = QFontMetrics(self.font_bold) # This should be set by the view. Indicates whether we should draw wide or narrow items. self.wide_items = False OptionEventChannel.subscribe('font_size', self.update_font)
def __init__(self, index, label=None): super().__init__(-RADIUS, -RADIUS, 2 * RADIUS, 2 * RADIUS) self._edges = set() self._pie = [] self._font = QApplication.font() self._text_color = QColor() self._pixmap = QPixmap() self._stock_polygon = NodePolygon.Circle self._node_polygon = QPolygonF() self._overlay_brush: QBrush = QBrush() self.id = index if label is None: self.setLabel(str(index + 1)) else: self.setLabel(label) self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemSendsScenePositionChanges) self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.setBrush(Qt.lightGray) self.setPen(QPen(Qt.black, 1)) self.setZValue(10)
def _setup_text_editor(self): self.styleComboBox = QComboBox(self.fontToolBar) self.styleComboBox.addItem("Standard") self.styleComboBox.addItem("Bullet List (Disc)") self.styleComboBox.addItem("Bullet List (Circle)") self.styleComboBox.addItem("Bullet List (Square)") self.styleComboBox.addItem("Ordered List (Decimal)") self.styleComboBox.addItem("Ordered List (Alpha lower)") self.styleComboBox.addItem("Ordered List (Alpha upper)") self.styleComboBox.addItem("Ordered List (Roman lower)") self.styleComboBox.addItem("Ordered List (Roman upper)") self.styleComboBox.addItem("Heading 1") self.styleComboBox.addItem("Heading 2") self.styleComboBox.addItem("Heading 3") self.styleComboBox.addItem("Heading 4") self.styleComboBox.addItem("Heading 5") self.styleComboBox.addItem("Heading 6") self.fontToolBar.addWidget(self.styleComboBox) self.fontComboBox = QFontComboBox(self.fontToolBar) # TODO connect self.fontToolBar.addWidget(self.fontComboBox) self.sizeComboBox = QComboBox(self.fontToolBar) # TODO connect sizes = QFontDatabase.standardSizes() [self.sizeComboBox.addItem(str(size)) for size in sizes] self.sizeComboBox.setCurrentIndex( sizes.index(QApplication.font().pointSize())) self.fontToolBar.addWidget(self.sizeComboBox)
def reset(self): locale = QLocale.system() self.recentDocuments = [] dateFormat = str(locale.dateFormat(QLocale.ShortFormat)) dateFormat = clean_format(dateFormat) self.dateFormat = dateFormat self.tableFontSize = QApplication.font().pointSize()
def reset(self): self.filter_hardness = 95 self.mix_file_kind = True self.use_regexp = False self.ignore_hardlink_matches = False self.remove_empty_folders = False self.debug_mode = False self.destination_type = 1 self.custom_command = '' self.language = trans.installed_lang if trans.installed_lang else '' self.tableFontSize = QApplication.font().pointSize() self.resultWindowIsMaximized = False self.resultWindowRect = None self.directoriesWindowRect = None self.recentResults = [] self.recentFolders = [] self.word_weighting = True self.match_similar = False self.ignore_small_files = True self.small_file_threshold = 10 # KB self.scan_tag_track = False self.scan_tag_artist = True self.scan_tag_album = True self.scan_tag_title = True self.scan_tag_genre = False self.scan_tag_year = False self.match_scaled = False
def main(config_file=None): """ parse args """ # argument parsing with argparse here for access to functions later # update to more formal implementation if config_file is None: # check for config file from command line args = sys.argv[1:] if len(args) > 0: file = args[0] if os.path.isfile(file): config_file = file if config_file is None: # load the default config file from safas module config_file = os.path.join(safas.__path__[0], 'config.yml') app = QApplication([]) f = app.font() f.setFamily("Monaco") f.setPointSize(9) app.setFont(f) window = MainPanel(config_file) logging.basicConfig(stream=sys.stdout, level=logging.INFO) # global, once for the app app.exec_()
def __init__(self, parent=None): super().__init__(parent=parent) self.displayed_email_label = None font = QFont(QApplication.font()) font.setPixelSize(14) self.label_title = QLabel('') self.label_title.setFont(font) mlayout = QVBoxLayout() mlayout.setContentsMargins(0, 0, 0, 0) mlayout.addWidget(self.label_title) self.setLayout(mlayout) generic = EmailLabel() sent = SentEmailLabel() trash = TrashEmailLabel() self.email_label_map = { EmailLabel: generic, SentEmailLabel: sent, TrashEmailLabel: trash } # Any label id that is not in the special_label_map should use generic EmailLabel self.special_label_map = { GMAIL_LABEL_SENT: SentEmailLabel, GMAIL_LABEL_TRASH: TrashEmailLabel } self.labels = {} EmailEventChannel.subscribe('show_label', self.show_label) EmailEventChannel.subscribe('labels_sync', self.process_labels)
def data(self, index, role=Qt.DisplayRole): terrain = self.terrainAt(index) if terrain: x = role if x == Qt.DisplayRole or x == Qt.EditRole: return terrain.name() elif x == Qt.DecorationRole: imageTile = terrain.imageTile() if imageTile: return imageTile.image() elif x == TerrainModel.UserRoles.TerrainRole: return QVariant(terrain) else: tileset = self.tilesetAt(index) if tileset: x = role if x == Qt.DisplayRole: return tileset.name() elif x == Qt.SizeHintRole: return QSize(1, 32) elif x == Qt.FontRole: font = QApplication.font() font.setBold(True) return font elif x == Qt.BackgroundRole: bg = QApplication.palette().alternateBase().color() return bg #.darker(103) return QVariant()
def sizeHint(self, option: 'QStyleOptionViewItem', index: QModelIndex) -> QSize: if not index.isValid(): return QSize() playlist = index.model().at(index.row()) font = QApplication.font() title_fm = QFontMetrics(font) playlist_rec = title_fm.boundingRect(0, 0, option.rect.width() - PlaylistDelegate.icon_diameter, 0, Qt.AlignLeft | Qt.AlignTop | Qt.TextWordWrap, playlist.name) title_rect = title_fm.boundingRect(option.rect.left() + PlaylistDelegate.pad_horizontal, playlist_rec.bottom() + PlaylistDelegate.pad_vertical, playlist_rec.width(), 0, Qt.AlignHCenter | Qt.AlignTop | Qt.TextWordWrap, playlist.name) playlist_size = QSize(PlaylistDelegate.icon_diameter, playlist_rec.height() + PlaylistDelegate.pad_vertical + title_rect.height()) if playlist_size.height() < PlaylistDelegate.icon_diameter: playlist_size.setHeight(PlaylistDelegate.icon_diameter) return playlist_size
def __init__(self, parent=None, name=None, modal=False, fl=Qt.Widget): QDialog.__init__(self, parent, fl) Ui_B_CraftWindow.setupUi(self, self) if name: self.setObjectName(name) if modal: self.setModal(modal) self.gems = [] self.GemName = [] self.GemCost = [] self.GemMakes = [] for i in range(0, 4): idx = i + 1 self.GemName.append(getattr(self, 'Gem%dName' % idx)) self.GemCost.append(getattr(self, 'Gem%dCost' % idx)) self.GemMakes.append(getattr(self, 'Gem%dMakes' % idx)) self.GemMakes[i].setSpecialValueText(" ") self.GemMakes[i].valueChanged[int].connect(self.RemakeChanged) self.Close.clicked.connect(self.CloseWindow) self.parent = parent testfont = QFontMetrics(QApplication.font()) width = testfont.size(Qt.TextSingleLine, " 199g 00s 00c").width() self.gridlayout.setColumnMinimumWidth(2, width)
def sizeHint(self, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> QtCore.QSize: if not index.isValid(): return QSize() context = index.model().chat_message_contexts()[index.row()] msg_text = index.data(Qt.DisplayRole) msg_font = QApplication.font() msg_fm = QFontMetrics(msg_font) msg_rect = msg_fm.boundingRect( 0, 0, option.rect.width() - MessageItemDelegate.total_pfp_width + MessageItemDelegate.profile_padding, 0, Qt.AlignLeft | Qt.AlignTop | Qt.TextWordWrap, msg_text) msg_size = QSize( option.rect.width(), msg_rect.height() + MessageItemDelegate.padding + MessageItemDelegate.profile_padding) if msg_size.height() < MessageItemDelegate.icon_radius: msg_size.setHeight(MessageItemDelegate.icon_radius) return msg_size
def __init__(self, settings): super(QWidget, self).__init__() self._layout = QBoxLayout(QBoxLayout.TopToBottom) self.setLayout(self._layout) self.settings = settings # eq directory widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Everquest Directory: ") layout.addWidget(label) text = QLineEdit() text.setText(self.settings.get_value("general", "eq_directory")) text.setToolTip(self.settings.get_value("general", "eq_directory")) text.setDisabled(True) self._text_eq_directory = text layout.addWidget(text, 1) button = QPushButton("Browse...") button.clicked.connect(self._get_eq_directory) layout.addWidget(button) self._layout.addWidget(widget, 0, Qt.AlignTop) # eq directory info frame = QFrame() frame.setFrameShadow(QFrame.Sunken) frame.setFrameShape(QFrame.Box) frame_layout = QBoxLayout(QBoxLayout.LeftToRight) frame.setLayout(frame_layout) widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) self._label_eq_directory = QLabel() layout.addWidget(self._label_eq_directory, 1) frame_layout.addWidget(widget, 1, Qt.AlignCenter) self._layout.addWidget(frame, 1) # parse interval widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Seconds between parse checks: ") layout.addWidget(label, 0, Qt.AlignLeft) text = QLineEdit() text.setText(str(self.settings.get_value("general", "parse_interval"))) text.editingFinished.connect(self._parse_interval_editing_finished) text.setMaxLength(3) self._text_parse_interval = text metrics = QFontMetrics(QApplication.font()) text.setFixedWidth(metrics.width("888888")) layout.addWidget(text, 0, Qt.AlignLeft) self._layout.addWidget(widget, 0, Qt.AlignTop | Qt.AlignLeft) # spacing at bottom of window widget = QWidget() self._layout.addWidget(widget, 1) # setup if settings.get_value("general", "eq_directory") is not None: self._check_directory_stats()
def reset(self): self.filter_hardness = 95 self.mix_file_kind = True self.use_regexp = False self.ignore_hardlink_matches = False self.remove_empty_folders = False self.debug_mode = False self.destination_type = 1 self.custom_command = "" self.language = trans.installed_lang if trans.installed_lang else "" self.tableFontSize = QApplication.font().pointSize() self.reference_bold_font = True self.resultWindowIsMaximized = False self.resultWindowRect = None self.directoriesWindowRect = None self.recentResults = [] self.recentFolders = [] self.word_weighting = True self.match_similar = False self.ignore_small_files = True self.small_file_threshold = 10 # KB self.scan_tag_track = False self.scan_tag_artist = True self.scan_tag_album = True self.scan_tag_title = True self.scan_tag_genre = False self.scan_tag_year = False self.match_scaled = False self.picture_cache_type = "sqlite"
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 __init__(self, parent): super(WindowFilterSettingsDialog, self).__init__(parent) self.setupUi(self) m = QFontMetrics(QApplication.font()) self.triggerRegexLineEdit.setMinimumWidth( m.width("windowclass.WindowClass")) self.target_item = None self.grabber = None # type: iomediator.WindowGrabber
def fontForID(self, fontId): result = QFont(QApplication.font()) if fontId == FontID.Title: result.setPointSize(self.TITLE_FONT_SIZE) result.setBold(True) elif fontId == FontID.AxisLabel: result.setPointSize(self.LABEL_FONT_SIZE) return result
def __init__(self, threadlink, test_utility, report): self.system_font = QApplication.font().family() self.label_font = QFont(self.system_font, 12) super().__init__() self.threadlink = threadlink self.tu = test_utility self.report = report
def __init__(self): super().__init__() self.sm = serial_manager.SerialManager() self.serial_thread = QThread() self.sm.moveToThread(self.serial_thread) self.serial_thread.start() self.test_version_signal.connect(self.sm.check_version) self.read_cables_signal.connect(self.sm.read_cables) self.sm.version_check_signal.connect(self.version_check) self.sm.port_unavailable_signal.connect(self.port_unavailable) self.sm.serial_error_signal.connect(self.serial_error) self.sm.cable_values_signal.connect(self.display_cables) self.sm.no_sensors_signal.connect(self.no_sensors) self.port_name = None self.system_font = QApplication.font().family() self.label_font = QFont(self.system_font, 14) self.sensor_font = QFont(self.system_font, 12) self.quit = QAction("Quit/退出;結束", self) self.quit.setShortcut("Ctrl+Q") self.quit.setStatusTip("Exit Program/退出;結束") self.quit.triggered.connect(self.close) self.about_tu = QAction("About Test Utility", self) self.about_tu.setShortcut("Ctrl+U") self.about_tu.setStatusTip("About Program") self.about_tu.triggered.connect(self.about_program) self.aboutqt = QAction("About Qt", self) self.aboutqt.setShortcut("Ctrl+I") self.aboutqt.setStatusTip("About Qt") self.aboutqt.triggered.connect(self.about_qt) # Create menubar self.menubar = self.menuBar() self.file_menu = self.menubar.addMenu("&File/文件") self.file_menu.addAction(self.quit) self.serial_menu = self.menubar.addMenu("&Serial/串行端口") self.serial_menu.installEventFilter(self) self.ports_menu = QMenu("&Ports/串行端口", self) self.serial_menu.addMenu(self.ports_menu) self.ports_menu.aboutToShow.connect(self.populate_ports) self.ports_group = QActionGroup(self) self.ports_group.triggered.connect(self.connect_port) self.help_menu = self.menubar.addMenu("&Help/帮助") self.help_menu.addAction(self.about_tu) self.help_menu.addAction(self.aboutqt) self.center() self.initUI()
def CreateTitle(self, title, parentWidget): titlelabel = QLabel(parentWidget) titlelabel.setText(title) titlelabel.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) titlelabel.setSizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum) titlefont = QApplication.font() titlefont.setBold(True) titlelabel.setFont(titlefont) return titlelabel
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 main(): from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QFont import widgets.main_widget as mw app = QApplication(sys.argv) app.setStyleSheet( "QSplitter::handle { background-color: rgb(192, 192, 192)}") # set the application font size globally font = QFont(app.font().family(), font_size, app.font().weight(), app.font().italic()) app.setFont(font) app.setStyle('QtCurve') # ['Breeze', 'Oxygen', 'QtCurve', 'Windows', 'Fusion'] windowsvista window = mw.MainWindow() window.showMaximized() app.aboutToQuit.connect(window.shutdown_kernel) sys.exit(app.exec_())
def initUI(self): # Look and feel antiAliasedFont = QApplication.font() antiAliasedFont.setStyleStrategy(QFont.PreferAntialias) QApplication.setFont(antiAliasedFont) self.setWindowTitle('Open Chess') path = constants.RESOURCES_PATH + '/icon.png' self.setWindowIcon(QIcon(path)) # Geometry """This will make the window the correct aspect ratio""" screenGeo = QDesktopWidget().availableGeometry() idealWidth = constants.IDEAL_RESOLUTION['width'] idealHeight = constants.IDEAL_RESOLUTION['height'] # TODO: maybe there is a good way to get this value? guessedFrame = 2 titlebarHeight = QApplication.style().pixelMetric( QStyle.PM_TitleBarHeight) + guessedFrame widthDisparity = screenGeo.width() - idealWidth heightDisparity = screenGeo.height() - idealHeight if widthDisparity < 0 and widthDisparity < heightDisparity: width = idealWidth + widthDisparity ratio = float(idealHeight) / idealWidth height = int(ratio * (idealWidth + widthDisparity)) self.setGeometry(0, 0, width - guessedFrame * 2, height - titlebarHeight) elif heightDisparity < 0 and heightDisparity < widthDisparity: ratio = float(idealWidth) / idealHeight width = int(ratio * (idealHeight + heightDisparity)) height = idealHeight + heightDisparity self.setGeometry(0, 0, width - guessedFrame * 2, height - titlebarHeight) else: self.setGeometry(0, 0, idealWidth, idealHeight) print("window geometry is", self.geometry()) # Widget self.centralWidget = CentralWidget(self) self.setCentralWidget(self.centralWidget) self.createActions() self.createMenus() # Center the window on the desktop # TODO: Add option for setting startup xy and saving layout in general # qr = self.frameGeometry() # cp = QDesktopWidget().geometry().center() # qr.moveCenter(cp) frameGeo = self.geometry() frameGeo.setHeight(frameGeo.height() + titlebarHeight + guessedFrame) frameGeo.setWidth(frameGeo.width() + guessedFrame * 2) self.move(QDesktopWidget().screenGeometry().center() - frameGeo.center())
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 __init__(self, di, prefix, sortcus, sortdies): QAbstractItemModel.__init__(self) self.prefix = prefix self.top_dies = [ decorate_die(CU.get_top_DIE(), i) for (i, CU) in enumerate(di._CUs) ] self.highlight_condition = None fi = QFontInfo(QApplication.font()) self.bold_font = QFont(fi.family(), fi.pointSize(), QFont.Bold) self.blue_brush = QBrush(Qt.GlobalColor.blue) self.sortcus = sortcus self.sortdies = sortdies
def on_player_song_changed(self, song): source_name_map = { p.identifier: p.name for p in self._app.library.list() } font_metrics = QFontMetrics(QApplication.font()) text = '{} - {}'.format(song.title, song.artists_name) elided_text = font_metrics.elidedText( text, Qt.ElideRight, self.progress_slider.width() - 100) self.song_source_label.setText(source_name_map[song.source]) self.song_title_label.setText(elided_text)
def main(): """ App entry point. """ from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) QApplication.setStyle(QStyleFactory.create('Fusion')) app = QApplication(sys.argv) rect = QDesktopWidget().screenGeometry(-1) width = 1400 height = 1000 if rect.width() > 1920 and rect.height() > 1080: app.font().setPointSize(16) app.setFont(app.font()) width, height = (1650, 1080) window = MainWindow(width, height) window.show() sys.exit(app.exec_())
def font(self, widget=None): """Return the font of the default text format. This font can then be used for a text editing widget. If widget is specified, resolves the application's default font for the widget with the properties from the theme. """ font = QApplication.font(widget) f = self.baseformat() if f: font = f.font().resolve(font) return font
def on_player_song_changed(self, song): if song is None: self.song_source_label.setText('歌曲来源') self.song_title_label.setText('No song is playing.') return source_name_map = {p.identifier: p.name for p in self._app.library.list()} font_metrics = QFontMetrics(QApplication.font()) text = '{} - {}'.format(song.title, song.artists_name) elided_text = font_metrics.elidedText( text, Qt.ElideRight, self.progress_slider.width() - 100) self.song_source_label.setText(source_name_map[song.source]) self.song_title_label.setText(elided_text)
def reset(self): self.filter_hardness = 95 self.mix_file_kind = True self.use_regexp = False self.ignore_hardlink_matches = False self.remove_empty_folders = False self.debug_mode = False self.destination_type = 1 self.custom_command = "" self.language = trans.installed_lang if trans.installed_lang else "" self.use_native_dialogs = True self.tableFontSize = QApplication.font().pointSize() self.reference_bold_font = True self.details_dialog_titlebar_enabled = True self.details_dialog_vertical_titlebar = True self.details_table_delta_foreground_color = QColor(250, 20, 20) # red # By default use internal icons on platforms other than Linux for now self.details_dialog_override_theme_icons = False if not ISLINUX else True self.details_dialog_viewers_show_scrollbars = True self.result_table_ref_foreground_color = QColor(Qt.blue) self.result_table_ref_background_color = QColor(Qt.lightGray) self.result_table_delta_foreground_color = QColor(255, 142, 40) # orange self.resultWindowIsMaximized = False self.resultWindowRect = None self.directoriesWindowRect = None self.mainWindowRect = None self.mainWindowIsMaximized = False self.recentResults = [] self.recentFolders = [] self.tabs_default_pos = True self.word_weighting = True self.match_similar = False self.ignore_small_files = True self.small_file_threshold = 10 # KB self.ignore_large_files = False self.large_file_threshold = 1000 # MB self.big_file_partial_hashes = False self.big_file_size_threshold = 100 # MB self.scan_tag_track = False self.scan_tag_artist = True self.scan_tag_album = True self.scan_tag_title = True self.scan_tag_genre = False self.scan_tag_year = False self.match_scaled = False self.picture_cache_type = "sqlite"
def __init__(self, app): super().__init__(text=self.default_text, parent=None) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self._app = app # TODO: we can create a label class that roll the text when # the text is longer than the label width self._timer = QTimer() self._txt = self._raw_text = self.default_text self._font_metrics = QFontMetrics(QApplication.font()) self._text_rect = self._font_metrics.boundingRect(self._raw_text) # text's position, keep changing to make text roll self._pos = 0 self._timer.timeout.connect(self.change_text_position)
def __init__(self, app): super().__init__(text=self.default_text, parent=None) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self._app = app self._timer = QTimer() self._txt = self._raw_text = self.default_text self._font_metrics = QFontMetrics(QApplication.font()) self._text_rect = self._font_metrics.boundingRect(self._raw_text) # text's position, keep changing to make text roll self._pos = 0 self._timer.timeout.connect(self.change_text_position) self._fetching_artists = False
def __init__(self, text, pixmap=None, parent=None): super().__init__(parent) rgb_value = 255 if options.theme == 'dark' else 0 self.theme = options.theme # You are supposed to set size policy like this, and not to override sizePolicy() # If vertical policy was preferred, then you would have to implement minimumSizeHint and # maximumSize to limit how much the item can shrink and grow. self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.text = text self.pixmap = pixmap self._prepare_pixmap(QColor(rgb_value, rgb_value, rgb_value, 200)) self.spacing = 12 self.font = QApplication.font() self.font.setBold(True) self.fm = QFontMetrics(self.font) self.mouse_over = False self.checked = False self.active = False self.setMouseTracking(True) self.background_color = QColor(rgb_value, rgb_value, rgb_value, 0) self.background_animation = QPropertyAnimation(self, b'opacity') self.background_animation.setStartValue(0) self.background_animation.setEndValue(40) self.background_animation.setDuration(300) self.indicator_pos = 5 self.indicator_position_anim = QPropertyAnimation( self, b'indicator_position') self.indicator_position_anim.setStartValue(5) self.indicator_position_anim.setEndValue(-5) self.indicator_position_anim.setDuration(300) self.indicator_background = QColor(rgb_value, rgb_value, rgb_value, 0) self.indicator_opacity_anim = QPropertyAnimation( self, b'indicator_opacity') self.indicator_opacity_anim.setStartValue(0) self.indicator_opacity_anim.setEndValue(140) self.indicator_opacity_anim.setDuration(300) self.all_animations = QParallelAnimationGroup() self.all_animations.addAnimation(self.background_animation) self.all_animations.addAnimation(self.indicator_position_anim) self.all_animations.addAnimation(self.indicator_opacity_anim) OptionEventChannel.subscribe('theme', self.handle_theme_change)
def paintEvent(self, event): painter = QPainter(self) painter.setFont(QApplication.font()) painter.setPen(self._app.palette().color(self._app.palette().Text)) if self._timer.isActive(): self._txt = self._raw_text else: self._txt = self._font_metrics.elidedText( self._raw_text, Qt.ElideRight, self.width()) painter.drawText( QRect(self._pos, 0, self.width()-self._pos, self.height()), Qt.AlignLeft | Qt.AlignVCenter, self._txt )
def paint(self, painter: QPainter, option: 'QStyleOptionViewItem', index: QModelIndex) -> None: """ Paint the playlist on the screen :param painter: Controls actual painting :param option: Options for painting :param index: Index of item """ playlist = index.model().at(index.row()) if not index.isValid(): return painter.save() # Save current state, before altering for custom painting painter.setRenderHints(QPainter.Antialiasing, True) painter.setRenderHints(QPainter.HighQualityAntialiasing, True) painter.setRenderHints(QPainter.SmoothPixmapTransform, True) playlist_pix: QPixmap = index.data(Qt.DecorationRole) # Tiled pixmap title_font = QApplication.font() title_font.setPixelSize(15) title_fm = QFontMetrics(title_font) icon_rect = QRect(option.rect.left() + PlaylistDelegate.pad_horizontal, option.rect.top(), PlaylistDelegate.icon_diameter, PlaylistDelegate.icon_diameter) title_rect = title_fm.boundingRect(option.rect.left() + PlaylistDelegate.pad_horizontal, icon_rect.bottom() + PlaylistDelegate.pad_vertical, icon_rect.width(), 0, Qt.AlignHCenter | Qt.AlignTop | Qt.TextWordWrap, playlist.name) # Draw icon painter.drawPixmap(icon_rect, playlist_pix) # Draw title painter.setFont(title_font) painter.setPen(Qt.white) painter.drawText(title_rect, Qt.AlignHCenter | Qt.AlignTop | Qt.TextWordWrap, playlist.name) painter.restore()
def on_player_song_changed(self, song): if song is None: self.song_source_label.setText('歌曲来源') self.song_title_label.setText('No song is playing.') return source_name_map = {p.identifier: p.name for p in self._app.library.list()} font_metrics = QFontMetrics(QApplication.font()) text = '{} - {}'.format(song.title_display, song.artists_name_display) # width -> three button + source label + text <= progress slider # three button: 63, source label: 150 elided_text = font_metrics.elidedText( text, Qt.ElideRight, self.progress_slider.width() - 200) self.song_source_label.setText(source_name_map[song.source]) self.song_title_label.setText(elided_text) loop = asyncio.get_event_loop() loop.create_task(self.update_mv_btn_status(song))
def main(): # Create and parse the command-line arguments parser = argparse.ArgumentParser(description='Linux Show Player') parser.add_argument('-f', '--file', default='', help="Session file path") parser.add_argument('-l', '--log', choices=['debug', 'info', 'warning'], default='warning', help='Log level') args = parser.parse_args() # Set the logging level if args.log == 'debug': log = logging.DEBUG elif args.log == 'info': log = logging.INFO else: log = logging.WARNING logging.basicConfig(format='%(levelname)s:: %(message)s', level=log) # Create the QApplication app = QApplication(sys.argv) app.setApplicationName('Linux Show Player') app.setQuitOnLastWindowClosed(True) # Force light font, for environment with "bad" QT support. appFont = app.font() appFont.setWeight(QFont.Light) app.setFont(appFont) # Set icons and theme from the application configuration QIcon.setThemeSearchPaths(styles.IconsThemePaths) QIcon.setThemeName(config['Theme']['icons']) styles.apply_style(config['Theme']['theme']) # Create the application LiSP_app = Application() # Load modules and plugins modules.load_modules() plugins.load_plugins() # Start the application LiSP_app.start(session_file=args.file) # Start the application sys.exit(_exec(app, LiSP_app))
def reset(self): self.filter_hardness = 95 self.mix_file_kind = True self.use_regexp = False self.ignore_hardlink_matches = False self.remove_empty_folders = False self.debug_mode = False self.destination_type = 1 self.custom_command = '' self.language = trans.installed_lang if trans.installed_lang else '' self.tableFontSize = QApplication.font().pointSize() self.resultWindowIsMaximized = False self.resultWindowRect = None self.directoriesWindowRect = None self.recentResults = [] self.recentFolders = [] self._reset_specific()
def __init__(self, settings): super(QWidget, self).__init__() self._layout = QBoxLayout(QBoxLayout.TopToBottom) self.setLayout(self._layout) self.settings = settings self.metrics = QFontMetrics(QApplication.font()) self.characters = self.settings.get_value('characters', None) if self.characters is None: self.characters = {} # select or add new character widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Select Character To Edit:") layout.addWidget(label, 0) combo = QComboBox() self._combo_character = combo self._combo_character.currentIndexChanged.connect(self._combo_changed) layout.addWidget(combo, 1) label = QLabel(" or ") layout.addWidget(label, 0) button = QPushButton("Add New") button.clicked.connect(self._new_character_mode_on) self._add_button = button layout.addWidget(button, 0) self._layout.addWidget(widget, 1) # start of frame frame = QFrame() frame.setFrameShadow(QFrame.Sunken) frame.setFrameStyle(QFrame.Box) frame_layout = QBoxLayout(QBoxLayout.TopToBottom) frame.setLayout(frame_layout) # name and level widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Name:") layout.addWidget(label, 0) text = QLineEdit() text.setMaxLength(20) text.setMinimumWidth(self.metrics.width("8888888888888888888888")) self._name = text self._name.textChanged.connect(self._name_changed) layout.addWidget(text, 1) label = QLabel("Level:") layout.addWidget(label, 0) text = QLineEdit() text.setMaxLength(3) text.setMinimumWidth(self.metrics.width("88888")) self._level = text self._level.editingFinished.connect(self._level_editing_finished) layout.addWidget(text, 1) frame_layout.addWidget(widget, 1) # logfile widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) label = QLabel("Log File:") layout.addWidget(label, 0) text = QLineEdit() text.setEnabled(False) self._log_file = text layout.addWidget(text, 1) button = QPushButton("Browse...") self._button_browse = button self._button_browse.clicked.connect(self._get_log_file) layout.addWidget(button, 0) frame_layout.addWidget(widget, 1) # delete or save buttons widget = QWidget() layout = QBoxLayout(QBoxLayout.LeftToRight) widget.setLayout(layout) button = QPushButton("Save") button.clicked.connect(self._save_new) layout.addWidget(button, 0, Qt.AlignRight) button = QPushButton("Delete") self._button_delete = button self._button_delete.clicked.connect(self._button_delete_clicked) layout.addWidget(button, 0, Qt.AlignRight) frame_layout.addWidget(widget, 0, Qt.AlignRight) # end of frame self._layout.addWidget(frame, 1) # spacing at bottom of window widget = QWidget() self._layout.addWidget(widget, 1) # setup self._new_character_mode_off() self._update_combo_character() if self.settings.get_value('general', 'eq_directory') is not None: log_directory = os.path.join(self.settings.get_value('general', 'eq_directory'), 'logs/') self._log_directory = log_directory if os.path.exists(log_directory): self._log_files = [log.lower() for log in os.listdir(log_directory) if 'eqlog' in log[:5]]
def setupTextActions(self): tb = QToolBar(self) tb.setWindowTitle("Format Actions") self.addToolBar(tb) menu = QMenu("F&ormat", self) self.menuBar().addMenu(menu) self.actionTextBold = QAction( QIcon.fromTheme('format-text-bold', QIcon(rsrcPath + '/textbold.png')), "&Bold", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_B, triggered=self.textBold, checkable=True) bold = QFont() bold.setBold(True) self.actionTextBold.setFont(bold) tb.addAction(self.actionTextBold) menu.addAction(self.actionTextBold) self.actionTextItalic = QAction( QIcon.fromTheme('format-text-italic', QIcon(rsrcPath + '/textitalic.png')), "&Italic", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_I, triggered=self.textItalic, checkable=True) italic = QFont() italic.setItalic(True) self.actionTextItalic.setFont(italic) tb.addAction(self.actionTextItalic) menu.addAction(self.actionTextItalic) self.actionTextUnderline = QAction( QIcon.fromTheme('format-text-underline', QIcon(rsrcPath + '/textunder.png')), "&Underline", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_U, triggered=self.textUnderline, checkable=True) underline = QFont() underline.setUnderline(True) self.actionTextUnderline.setFont(underline) tb.addAction(self.actionTextUnderline) menu.addAction(self.actionTextUnderline) menu.addSeparator() grp = QActionGroup(self, triggered=self.textAlign) # Make sure the alignLeft is always left of the alignRight. if QApplication.isLeftToRight(): self.actionAlignLeft = QAction( QIcon.fromTheme('format-justify-left', QIcon(rsrcPath + '/textleft.png')), "&Left", grp) self.actionAlignCenter = QAction( QIcon.fromTheme('format-justify-center', QIcon(rsrcPath + '/textcenter.png')), "C&enter", grp) self.actionAlignRight = QAction( QIcon.fromTheme('format-justify-right', QIcon(rsrcPath + '/textright.png')), "&Right", grp) else: self.actionAlignRight = QAction( QIcon.fromTheme('format-justify-right', QIcon(rsrcPath + '/textright.png')), "&Right", grp) self.actionAlignCenter = QAction( QIcon.fromTheme('format-justify-center', QIcon(rsrcPath + '/textcenter.png')), "C&enter", grp) self.actionAlignLeft = QAction( QIcon.fromTheme('format-justify-left', QIcon(rsrcPath + '/textleft.png')), "&Left", grp) self.actionAlignJustify = QAction( QIcon.fromTheme('format-justify-fill', QIcon(rsrcPath + '/textjustify.png')), "&Justify", grp) self.actionAlignLeft.setShortcut(Qt.CTRL + Qt.Key_L) self.actionAlignLeft.setCheckable(True) self.actionAlignLeft.setPriority(QAction.LowPriority) self.actionAlignCenter.setShortcut(Qt.CTRL + Qt.Key_E) self.actionAlignCenter.setCheckable(True) self.actionAlignCenter.setPriority(QAction.LowPriority) self.actionAlignRight.setShortcut(Qt.CTRL + Qt.Key_R) self.actionAlignRight.setCheckable(True) self.actionAlignRight.setPriority(QAction.LowPriority) self.actionAlignJustify.setShortcut(Qt.CTRL + Qt.Key_J) self.actionAlignJustify.setCheckable(True) self.actionAlignJustify.setPriority(QAction.LowPriority) tb.addActions(grp.actions()) menu.addActions(grp.actions()) menu.addSeparator() pix = QPixmap(16, 16) pix.fill(Qt.black) self.actionTextColor = QAction(QIcon(pix), "&Color...", self, triggered=self.textColor) tb.addAction(self.actionTextColor) menu.addAction(self.actionTextColor) tb = QToolBar(self) tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea) tb.setWindowTitle("Format Actions") self.addToolBarBreak(Qt.TopToolBarArea) self.addToolBar(tb) comboStyle = QComboBox(tb) tb.addWidget(comboStyle) comboStyle.addItem("Standard") comboStyle.addItem("Bullet List (Disc)") comboStyle.addItem("Bullet List (Circle)") comboStyle.addItem("Bullet List (Square)") comboStyle.addItem("Ordered List (Decimal)") comboStyle.addItem("Ordered List (Alpha lower)") comboStyle.addItem("Ordered List (Alpha upper)") comboStyle.addItem("Ordered List (Roman lower)") comboStyle.addItem("Ordered List (Roman upper)") comboStyle.activated.connect(self.textStyle) self.comboFont = QFontComboBox(tb) tb.addWidget(self.comboFont) self.comboFont.activated[str].connect(self.textFamily) self.comboSize = QComboBox(tb) self.comboSize.setObjectName("comboSize") tb.addWidget(self.comboSize) self.comboSize.setEditable(True) db = QFontDatabase() for size in db.standardSizes(): self.comboSize.addItem("%s" % (size)) self.comboSize.activated[str].connect(self.textSize) self.comboSize.setCurrentIndex( self.comboSize.findText( "%s" % (QApplication.font().pointSize())))
def main(): fix_windows_stdout_stderr() if sys.version_info < (3, 4): print("You need at least Python 3.4 for this application!") sys.exit(1) urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0] urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..", "..") prefix = os.path.abspath(os.path.normpath(urh_dir)) src_dir = os.path.join(prefix, "src") if os.path.exists(src_dir) and not prefix.startswith("/usr") and not re.match(r"(?i)c:\\program", prefix): # Started locally, not installed -> add directory to path sys.path.insert(0, src_dir) if len(sys.argv) > 1 and sys.argv[1] == "--version": import urh.version print(urh.version.VERSION) sys.exit(0) if GENERATE_UI and not hasattr(sys, 'frozen'): try: sys.path.insert(0, os.path.join(prefix)) from data import generate_ui generate_ui.gen() except (ImportError, FileNotFoundError): # The generate UI script cannot be found so we are most likely in release mode, no problem here. pass from urh.util import util util.set_shared_library_path() try: import urh.cythonext.signal_functions import urh.cythonext.path_creator import urh.cythonext.util except ImportError: if hasattr(sys, "frozen"): print("C++ Extensions not found. Exiting...") sys.exit(1) print("Could not find C++ extensions, trying to build them.") old_dir = os.path.realpath(os.curdir) os.chdir(os.path.join(src_dir, "urh", "cythonext")) from urh.cythonext import build build.main() os.chdir(old_dir) from urh.controller.MainController import MainController from urh import constants if constants.SETTINGS.value("theme_index", 0, int) > 0: os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion' app = QApplication(["URH"] + sys.argv[1:]) app.setWindowIcon(QIcon(":/icons/icons/appicon.png")) util.set_icon_theme() font_size = constants.SETTINGS.value("font_size", 0, int) if font_size > 0: font = app.font() font.setPointSize(font_size) app.setFont(font) constants.SETTINGS.setValue("default_theme", app.style().objectName()) if constants.SETTINGS.value("theme_index", 0, int) > 0: app.setStyle(QStyleFactory.create("Fusion")) if constants.SETTINGS.value("theme_index", 0, int) == 2: palette = QPalette() background_color = QColor(56, 60, 74) text_color = QColor(211, 218, 227).lighter() palette.setColor(QPalette.Window, background_color) palette.setColor(QPalette.WindowText, text_color) palette.setColor(QPalette.Base, background_color) palette.setColor(QPalette.AlternateBase, background_color) palette.setColor(QPalette.ToolTipBase, background_color) palette.setColor(QPalette.ToolTipText, text_color) palette.setColor(QPalette.Text, text_color) palette.setColor(QPalette.Button, background_color) palette.setColor(QPalette.ButtonText, text_color) palette.setColor(QPalette.BrightText, Qt.red) palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray) palette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.darkGray) palette.setColor(QPalette.Highlight, QColor(200, 50, 0)) palette.setColor(QPalette.HighlightedText, text_color) app.setPalette(palette) # use system colors for painting widget = QWidget() bg_color = widget.palette().color(QPalette.Background) fg_color = widget.palette().color(QPalette.Foreground) selection_color = widget.palette().color(QPalette.Highlight) constants.BGCOLOR = bg_color constants.LINECOLOR = fg_color constants.SELECTION_COLOR = selection_color constants.SEND_INDICATOR_COLOR = selection_color main_window = MainController() # allow usage of prange (OpenMP) in Processes multiprocessing.set_start_method("spawn") if sys.platform == "darwin": menu_bar = main_window.menuBar() menu_bar.setNativeMenuBar(False) elif sys.platform == "win32": # Ensure we get the app icon in windows taskbar import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("jopohl.urh") main_window.showMaximized() # main_window.setFixedSize(1920, 1080 - 30) # Youtube if "autoclose" in sys.argv[1:]: # Autoclose after 1 second, this is useful for automated testing timer = QTimer() timer.timeout.connect(app.quit) timer.start(1000) return_code = app.exec_() app.closeAllWindows() os._exit(return_code) # sys.exit() is not enough on Windows and will result in crash on exit
def __init__(self, mainwindow): QWidget.__init__(self, mainwindow) self._currentView = None self._positions = [] self._positionsDirty = True self._replace = False # are we in replace mode? self._going = False # are we moving the text cursor? mainwindow.currentViewChanged.connect(self.viewChanged) mainwindow.actionCollection.edit_find_next.triggered.connect(self.findNext) mainwindow.actionCollection.edit_find_previous.triggered.connect(self.findPrevious) # don't inherit looks from view self.setFont(QApplication.font()) self.setPalette(QApplication.palette()) grid = QGridLayout(spacing=2) grid.setContentsMargins(4, 0, 4, 0) grid.setVerticalSpacing(0) self.setLayout(grid) self.searchEntry = QLineEdit(textChanged=self.slotSearchChanged) self.searchLabel = QLabel() self.prevButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findPrevious) self.prevButton.setIcon(icons.get('go-previous')) self.nextButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findNext) self.nextButton.setIcon(icons.get('go-next')) self.caseCheck = QCheckBox(checked=True, focusPolicy=Qt.NoFocus) self.regexCheck = QCheckBox(focusPolicy=Qt.NoFocus) self.countLabel = QLabel(alignment=Qt.AlignRight | Qt.AlignVCenter) self.countLabel.setMinimumWidth(QApplication.fontMetrics().width("9999")) self.closeButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus) self.hideAction = QAction(self, triggered=self.slotHide) self.hideAction.setShortcut(QKeySequence(Qt.Key_Escape)) self.hideAction.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton)) self.closeButton.setDefaultAction(self.hideAction) grid.addWidget(self.searchLabel, 0, 0) grid.addWidget(self.searchEntry, 0, 1) grid.addWidget(self.prevButton, 0, 2) grid.addWidget(self.nextButton, 0, 3) grid.addWidget(self.caseCheck, 0, 4) grid.addWidget(self.regexCheck, 0, 5) grid.addWidget(self.countLabel, 0, 6) grid.addWidget(self.closeButton, 0, 7) self.caseCheck.toggled.connect(self.slotSearchChanged) self.regexCheck.toggled.connect(self.slotSearchChanged) self.replaceEntry = QLineEdit() self.replaceLabel = QLabel() self.replaceButton = QPushButton(clicked=self.slotReplace) self.replaceAllButton = QPushButton(clicked=self.slotReplaceAll) grid.addWidget(self.replaceLabel, 1, 0) grid.addWidget(self.replaceEntry, 1, 1) grid.addWidget(self.replaceButton, 1, 4) grid.addWidget(self.replaceAllButton, 1, 5) app.settingsChanged.connect(self.readSettings) self.readSettings() app.translateUI(self)
def start(test=False): app_constants.APP_RESTART_CODE = -123456789 if os.name == 'posix': main_path = os.path.dirname(os.path.realpath(__file__)) log_path = os.path.join(main_path, 'happypanda.log') debug_log_path = os.path.join(main_path, 'happypanda_debug.log') else: log_path = 'happypanda.log' debug_log_path = 'happypanda_debug.log' if os.path.exists('cacert.pem'): os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(os.getcwd(), "cacert.pem") parser = argparse.ArgumentParser(prog='Happypanda', description='A manga/doujinshi manager with tagging support') parser.add_argument('-d', '--debug', action='store_true', help='happypanda_debug_log.log will be created in main directory') parser.add_argument('-v', '--version', action='version', version='Happypanda v{}'.format(app_constants.vs)) parser.add_argument('-e', '--exceptions', action='store_true', help='Disable custom excepthook') parser.add_argument('-x', '--dev', action='store_true', help='Development Switch') args = parser.parse_args() log_handlers = [] log_level = logging.INFO if args.dev: log_handlers.append(logging.StreamHandler()) if args.debug: print("happypanda_debug.log created at {}".format(os.getcwd())) # create log try: with open(debug_log_path, 'x') as f: pass except FileExistsError: pass log_handlers.append(logging.FileHandler(debug_log_path, 'w', 'utf-8')) log_level = logging.DEBUG app_constants.DEBUG = True else: try: with open(log_path, 'x') as f: pass except FileExistsError: pass log_handlers.append(logging.handlers.RotatingFileHandler( log_path, maxBytes=1000000*10, encoding='utf-8', backupCount=2)) # Fix for logging not working # clear the handlers first before adding these custom handler # http://stackoverflow.com/a/15167862 logging.getLogger('').handlers = [] logging.basicConfig(level=log_level, format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s', datefmt='%d-%m %H:%M', handlers=tuple(log_handlers)) log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical if not args.exceptions: def uncaught_exceptions(ex_type, ex, tb): log_c(''.join(traceback.format_tb(tb))) log_c('{}: {}'.format(ex_type, ex)) traceback.print_exception(ex_type, ex, tb) sys.excepthook = uncaught_exceptions if app_constants.FORCE_HIGH_DPI_SUPPORT: log_i("Enabling high DPI display support") os.environ.putenv("QT_DEVICE_PIXEL_RATIO", "auto") effects = [Qt.UI_AnimateCombo, Qt.UI_FadeMenu, Qt.UI_AnimateMenu, Qt.UI_AnimateTooltip, Qt.UI_FadeTooltip] for effect in effects: QApplication.setEffectEnabled(effect) application = QApplication(sys.argv) application.setOrganizationName('Pewpews') application.setOrganizationDomain('https://github.com/Pewpews/happypanda') application.setApplicationName('Happypanda') application.setApplicationDisplayName('Happypanda') application.setApplicationVersion('v{}'.format(app_constants.vs)) application.setAttribute(Qt.AA_UseHighDpiPixmaps) application.font().setStyleStrategy(application.font().PreferAntialias) log_i('Starting Happypanda...'.format(app_constants.vs)) if args.debug: log_i('Running in debug mode'.format(app_constants.vs)) import pprint sys.displayhook = pprint.pprint app_constants.load_icons() log_i('Happypanda Version {}'.format(app_constants.vs)) log_i('OS: {} {}\n'.format(platform.system(), platform.release())) conn = None try: conn = db.init_db() log_d('Init DB Conn: OK') log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION)) except: log_c('Invalid database') log.exception('Database connection failed!') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText('Invalid database') msg_box.setInformativeText("Do you want to create a new database?") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: pass else: application.exit() log_d('Normal Exit App: OK') sys.exit() def start_main_window(conn): db.DBBase._DB_CONN = conn #if args.test: # import threading, time # ser_list = [] # for x in range(5000): # s = gallerydb.gallery() # s.profile = app_constants.NO_IMAGE_PATH # s.title = 'Test {}'.format(x) # s.artist = 'Author {}'.format(x) # s.path = app_constants.static_dir # s.type = 'Test' # s.language = 'English' # s.info = 'I am number {}'.format(x) # ser_list.append(s) # done = False # thread_list = [] # i = 0 # while not done: # try: # if threading.active_count() > 5000: # thread_list = [] # done = True # else: # thread_list.append( # threading.Thread(target=gallerydb.galleryDB.add_gallery, # args=(ser_list[i],))) # thread_list[i].start() # i += 1 # print(i) # print('Threads running: {}'.format(threading.activeCount())) # except IndexError: # done = True WINDOW = app.AppWindow(args.exceptions) # styling d_style = app_constants.default_stylesheet_path u_style = app_constants.user_stylesheet_path if len(u_style) is not 0: try: style_file = QFile(u_style) log_i('Select userstyle: OK') except: style_file = QFile(d_style) log_i('Select defaultstyle: OK') else: style_file = QFile(d_style) log_i('Select defaultstyle: OK') style_file.open(QFile.ReadOnly) style = str(style_file.readAll(), 'utf-8') application.setStyleSheet(style) try: os.mkdir(app_constants.temp_dir) except FileExistsError: try: for root, dirs, files in scandir.walk('temp', topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) except: log.exception("Empty temp: FAIL") log_d('Create temp: OK') if test: return application, WINDOW return application.exec_() def db_upgrade(): log_d('Database connection failed') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText('Incompatible database!') msg_box.setInformativeText("Do you want to upgrade to newest version?" + " It shouldn't take more than a second. Don't start a new instance!") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: utils.backup_database() import threading db_p = db_constants.DB_PATH db.add_db_revisions(db_p) conn = db.init_db() return start_main_window(conn) else: application.exit() log_d('Normal Exit App: OK') return 0 if conn: return start_main_window(conn) else: return db_upgrade()
cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) self.setMinimumSize(self.size()) self.setFixedSize(self.size()) # %% if __name__ == '__main__' if __name__ == '__main__': from projet.manager_data import DataManager from projet.reader_projet import ProjetReader app = QApplication(sys.argv) ft = app.font() ft.setFamily('Segoe UI') ft.setPointSize(11) app.setFont(ft) pf = 'C:/Users/jsgosselin/GWHAT/Projects/Example/Example.gwt' pr = ProjetReader(pf) dm = DataManager() dm.set_projet(pr) Hydroprint = HydroprintGUI(dm) Hydroprint.show() Hydroprint.wldset_changed() sys.exit(app.exec_())