class Downloads(QWidget): def __init__(self): super(Downloads, self).__init__() self.history = get_download_history() self.history.reverse() self.layout = QStackedLayout() self.layout.setMargin(0) self.page_widget = QScrollArea() self.page_widget.setWidgetResizable(True) widget = QWidget(self.page_widget) widget.setMinimumWidth(350) self.page_widget.setWidget(widget) self.page_layout = QVBoxLayout(widget, alignment=Qt.AlignTop) self.page_layout.setMargin(0) self.page_layout.setContentsMargins(25, 25, 25, 25) self.layout.addWidget(self.page_widget) self.layout.setCurrentWidget(self.page_widget) if len(self.history) == 0: self.history_empty_label = QLabel('No downloads', alignment=Qt.AlignCenter) self.layout.addWidget(self.history_empty_label) self.layout.setCurrentWidget(self.history_empty_label) for item in self.history: self.page_layout.addWidget(DownloadItem(item=item)) self.setLayout(self.layout)
class ApplicationWindow(QWidget): def __init__(self): super().__init__() self.hm_page = HomePage() self.mn_window = MainWindow() self.widget_layout = QStackedLayout() self.buildLayout() self.connections() #self.setStyleSheet('background-color: white') #self.hm_page.setStyleSheet('background-color: #2e3843') def buildLayout(self): self.widget_layout = QStackedLayout() self.widget_layout.addWidget(self.hm_page) self.widget_layout.addWidget(self.mn_window) self.setLayout(self.widget_layout) def connections(self): self.hm_page.changePage.connect( lambda: self.widget_layout.setCurrentIndex(1)) self.mn_window.changePage.connect( lambda: self.widget_layout.setCurrentIndex(0))
class MainWindowCentralWidget(QWidget): """ Container for all widgets of pages in the application. """ def __init__(self): QWidget.__init__(self) self.__MAIN_MENU_WIDGET_NAME = 'main_menu' self.__SETTINGS_WIDGET_NAME = 'settings' self.__FACE_LOAD_WIDGET_NAME = 'face load' self.__FACE_AUTH_WIDGET_NAME = 'face auth' self.__setup_ui() self.widgets = { self.__MAIN_MENU_WIDGET_NAME: self.main_menu_widget, self.__SETTINGS_WIDGET_NAME: self.settings_widget, self.__FACE_LOAD_WIDGET_NAME: self.face_loading_widget, self.__FACE_AUTH_WIDGET_NAME: self.face_authentication_widget } def __setup_ui(self): self.stacked_layout = QStackedLayout() self.main_menu_widget = MainMenuWidget(self) self.stacked_layout.addWidget(self.main_menu_widget) self.settings_widget = SettingsWidget(self) self.stacked_layout.addWidget(self.settings_widget) self.face_loading_widget = FaceLoadingWidget(self) self.stacked_layout.addWidget(self.face_loading_widget) self.face_authentication_widget = FaceAuthenticationWidget(self) self.stacked_layout.addWidget(self.face_authentication_widget) self.setLayout(self.stacked_layout) def set_current_widget(self, widget_name: str): """ Choose which widget (page) to display :param widget_name: name of the widget to switch """ self.stacked_layout.setCurrentWidget(self.widgets[widget_name]) def set_main_menu(self): self.set_current_widget(self.__MAIN_MENU_WIDGET_NAME) def open_face_load_widget(self): self.set_current_widget(self.__FACE_LOAD_WIDGET_NAME) def open_settings_widget(self): self.set_current_widget(self.__SETTINGS_WIDGET_NAME) def open_face_auth_widget(self): self.set_current_widget(self.__FACE_AUTH_WIDGET_NAME) @Slot() def change_widget(self): self.stacked_layout.setCurrentWidget(self.settings_widget)
class MainWindow(StyleWindow): def __init__(self, parent=None): StyleWindow.__init__(self, parent) self.init_window_attr() self.setObjectName("MainWindow") self._title = Title() self.mouse_drag_enabled = True self._stacked_layout = QStackedLayout() self._init_view() def init_window_attr(self): """ 初始化window falg & window attributes """ self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowMinMaxButtonsHint) def init_title(self, layout: QBoxLayout): self._title.setObjectName("MainTitle") self._title.setFixedHeight(40) self._title.title_text = self.tr("DVideoEditTools") self._title.close.connect(self.close) self._title.show_minimized.connect(self.showMinimized) self._title.show_maximized.connect(self.show_max_normal) layout.addWidget(self._title) def _init_view(self): main_layout = QVBoxLayout() main_layout.setContentsMargins(0, 0, 0, 0) main_layout.setSpacing(0) self.set_layout(main_layout) self.init_title(main_layout) main_layout.addLayout(self._stacked_layout) self._stacked_layout.addWidget(HomePage()) # main_layout.addStretch(0) def move_center(self): screen_rect = QDesktopWidget().availableGeometry() x = (screen_rect.right() - self.width()) / 2 y = (screen_rect.bottom() - self.height()) / 2 center_pos = QPoint(int(x), int(y)) self.move(center_pos) def show_max_normal(self): if self.isMaximized(): self.showNormal() else: self.showMaximized()
def __init__(self): super().__init__() layout = QStackedLayout() layout.addWidget(Color("red")) layout.addWidget(Color("green")) layout.addWidget(Color("blue")) layout.addWidget(Color("yellow")) layout.setCurrentIndex(0) widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget)
def setup_ui(self, proj_path=None): switch = QStackedLayout() get_proj = GetProject() manager_wig = ManagerWidget() switch.addWidget(get_proj) switch.addWidget(manager_wig) @get_proj.submit.connect def submit(proj, path): manager_wig.set_project(proj, path) switch.setCurrentWidget(manager_wig) @manager_wig.back.connect def back(): switch.setCurrentWidget(get_proj) self.setLayout(switch) if proj_path: get_proj.try_open(proj_path)
class DynamicView(Widget): def __init__(self): super().__init__() self.__stacked_layout = QStackedLayout() self._layout.addLayout(self.__stacked_layout) self.__widgets = [] def add_item(self, item: Widget): w = QWidget() w.setLayout(item.get_layout()) self.__stacked_layout.addWidget(w) self.__widgets.append(w) def remove_item(self, idx: int): self.__stacked_layout.takeAt(idx) del self.__widgets[idx] def clear(self): for i in range(len(self.__widgets) - 1): self.remove_item(i) def set_index(self, idx: int): self.__stacked_layout.setCurrentIndex(idx)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("My App") pagelayout = QVBoxLayout() button_layout = QHBoxLayout() self.stacklayout = QStackedLayout() pagelayout.addLayout(button_layout) pagelayout.addLayout(self.stacklayout) btn = QPushButton("red") btn.pressed.connect(self.activate_tab_1) button_layout.addWidget(btn) self.stacklayout.addWidget(Color("red")) btn = QPushButton("green") btn.pressed.connect(self.activate_tab_2) button_layout.addWidget(btn) self.stacklayout.addWidget(Color("green")) btn = QPushButton("yellow") btn.pressed.connect(self.activate_tab_3) button_layout.addWidget(btn) self.stacklayout.addWidget(Color("yellow")) widget = QWidget() widget.setLayout(pagelayout) self.setCentralWidget(widget) def activate_tab_1(self): self.stacklayout.setCurrentIndex(0) def activate_tab_2(self): self.stacklayout.setCurrentIndex(1) def activate_tab_3(self): self.stacklayout.setCurrentIndex(2)
class Form(QWidget): def __init__(self): super(Form, self).__init__() self.setWindowTitle("stacked layout ") self.wgtA = QWidget() self.wgtA_vl = QVBoxLayout() self.btnA = QPushButton("A") self.btnB = QPushButton("B") self.btnC = QPushButton("C") self.wgtA_vl.addWidget(self.btnA) self.wgtA_vl.addWidget(self.btnB) self.wgtA_vl.addWidget(self.btnC) self.wgtA.setLayout(self.wgtA_vl) self.wgt1 = QWidget() self.wgt1_vl = QVBoxLayout() self.btn1 = QPushButton("1") self.btn2 = QPushButton("2") self.btn3 = QPushButton("3") self.wgt1_vl.addWidget(self.btn1) self.wgt1_vl.addWidget(self.btn2) self.wgt1_vl.addWidget(self.btn3) self.wgt1.setLayout(self.wgt1_vl) self.wgtGA = QWidget() self.wgtGA_vl = QVBoxLayout() self.btnGA = QPushButton("가") self.btnNA = QPushButton("나") self.btnDA = QPushButton("다") self.wgtGA_vl.addWidget(self.btnGA) self.wgtGA_vl.addWidget(self.btnNA) self.wgtGA_vl.addWidget(self.btnDA) self.wgtGA.setLayout(self.wgtGA_vl) self.layout = QStackedLayout() self.layout.addWidget(self.wgtA) self.layout.addWidget(self.wgt1) self.layout.addWidget(self.wgtGA) self.setLayout(self.layout) self.btnA.clicked.connect( lambda s=None, i=0: self.set_stack_index(s, i)) self.btnB.clicked.connect( lambda s=None, i=1: self.set_stack_index(s, i)) self.btnC.clicked.connect( lambda s=None, i=2: self.set_stack_index(s, i)) self.btn1.clicked.connect( lambda s=None, i=0: self.set_stack_index(s, i)) self.btn2.clicked.connect( lambda s=None, i=1: self.set_stack_index(s, i)) self.btn3.clicked.connect( lambda s=None, i=2: self.set_stack_index(s, i)) self.btnGA.clicked.connect( lambda s=None, i=0: self.set_stack_index(s, i)) self.btnNA.clicked.connect( lambda s=None, i=1: self.set_stack_index(s, i)) self.btnDA.clicked.connect( lambda s=None, i=2: self.set_stack_index(s, i)) def set_stack_index(self, s, i): self.layout.setCurrentIndex(i)
class MetalGUI(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.parent = parent self.supported_setups = ['TOP-DOWN'] self.stacked_layout = QStackedLayout() self.__setup_widget = None self.__metal_main_widget = None self.__init_main_widget__() self.stacked_layout.setCurrentIndex(0) self.setLayout(self.stacked_layout) def minimumSizeHint(self): return self.stacked_layout.currentWidget().minimumSizeHint() def sizeHint(self): return self.stacked_layout.currentWidget().sizeHint() def __load_settings__(self): base_path = Path(__file__).parent settings_path = str( (base_path / '../resources/PRINTER_SETTINGS.json').resolve()) settings_file = QFile(settings_path) if settings_file.open(QIODevice.ReadOnly | QIODevice.Text): file_data = QJsonDocument.fromJson( settings_file.readAll()).object() if "metal_printer_settings" in file_data: printer_setup = str( file_data["metal_printer_settings"]["printer_setup"]) if printer_setup == self.supported_setups[0]: self.__select_setup__(0) else: return False return True settings_file.close() return False def __init_configuration_selection_widget__(self): self.__setup_widget = QWidget(self) setup_layout = QHBoxLayout() for idx in range(len(self.supported_setups)): button = QPushButton(self.supported_setups[idx], self.__setup_widget) button.setFixedSize(200, 200) button.clicked.connect(self.__select_setup__) setup_layout.addWidget(button) self.__setup_widget.setLayout(setup_layout) self.stacked_layout.addWidget(self.__setup_widget) def __select_setup__(self, idx): self.selected_setup = self.supported_setups[idx] self.__init_main_widget__() self.stacked_layout.setCurrentIndex(1) self.parent.move( self.desktops.screen(0).rect().center() - self.__metal_main_widget.rect().center()) def __init_main_widget__(self): self.__metal_main_widget = QTabWidget(self) self.__metal_main_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.__gcode_sender_widget = GCodeSenderGUI( parent=self.__metal_main_widget) self.__slicer_widget = MetalSlicerGUI(parent=self.__metal_main_widget) self.__slicer_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.__metal_main_widget.addTab(self.__gcode_sender_widget, 'GCode Sender') self.__metal_main_widget.addTab(self.__slicer_widget, 'Slicer') self.stacked_layout.addWidget(self.__metal_main_widget) self.desktops = QDesktopWidget() @Slot() def closeEvent(self, event: QCloseEvent): if self.__setup_widget: self.__setup_widget.close() if self.__metal_main_widget: self.__slicer_widget.close() self.__metal_main_widget.close() event.accept() def get_settings_window(self, parent=None): printer_settings = QGroupBox("Metal Printer Settings:", parent) gcodesender_settings = self.__gcode_sender_widget.get_settings_window( printer_settings) settings_layout = QVBoxLayout(printer_settings) settings_layout.addWidget(gcodesender_settings) return printer_settings
class SandyScreen(QWidget): def __init__(self, root): QWidget.__init__(self) self.root = root # Setting state vars self.app_running = True self.ctrl_down = False self.in_fullscreen = False self.in_menu = False self.on_pause = True # Setting animation vars self.timer_delay = 10 self.phase = 1 self.delta_per_tick = 1 / 30 self.xpmsz = None self.geo = [0, 0, 0, 0] # Creating timer and sandpile self.timer = QTimer(self) self.seed = None self.piletype = None self.sandpile = None self.reroll_pile() # Generating pause icon self.pause_icon = Image.new('RGBA', size=(60, 60)) for i in range(60): for j in range(60): self.pause_icon.putpixel( (j, i), (255, 255, 255, 0 if 20 < j < 40 else 100)) # Initialising UI and running self.init_ui() self.show() def init_ui(self): self.setMinimumSize(600, 400) self.setWindowTitle('Sandy Screen') # Menu widget self.menu = SandyMenu(self) # Sandbox container widget and its background and canvas label stack self.sandbox = QWidget(self) self.sandbox.setGeometry(0, 0, 600, 400) self.sandbox_bg = QLabel(self.sandbox) self.sandbox_bg.setGeometry(0, 0, 600, 400) self.sandbox_bg.setPixmap( QPixmap(['1 1 1 1', '1 c #000000', '1']).scaled(self.sandbox_bg.size())) self.canvases = [QLabel(self.sandbox), QLabel(self.sandbox)] for c in self.canvases: c.setAlignment(Qt.AlignCenter) c.setGeometry(0, 0, 600, 400) self.canvases[1].setPixmap(QPixmap(generate_xpm(self.sandpile)[0])) self.sandpile.topple_step() self.canvases[0].setPixmap(QPixmap(generate_xpm(self.sandpile)[0])) # Opacity effect on the upper frame label self.opeff = QGraphicsOpacityEffect(self.canvases[-1]) self.opeff.setOpacity(1) self.canvases[-1].setGraphicsEffect(self.opeff) # Main stack layout self.layout = QStackedLayout(self) self.layout.addWidget(self.sandbox) self.layout.addWidget(self.menu) # Overlay pause icon label self.pause_label = QLabel(self) self.pause_label.setAlignment(Qt.AlignCenter) self.pause_label.setPixmap(QPixmap(ImageQt.ImageQt(self.pause_icon))) def restart_pile(self): del self.sandpile self.sandpile = self.piletype(copy.deepcopy(self.seed), frozen=True, timed=False, vocal=False) print('restart called') def reroll_pile(self, piletype=None, seed=None): if seed: self.seed = seed else: v = random.randint(8, 33) self.seed = [[v for j in range(_X)] for i in range(_Y)] if piletype: self.piletype = piletype else: v = random.randint(0, 3) self.piletype = [t4f, t6hf, t6vf, t8f][v] self.sandpile = self.piletype(copy.deepcopy(self.seed), frozen=True, timed=False, vocal=False) def run(self): self.root.exec_() def closeEvent(self, event): self.timer.stop() self.app_running = False def keyPressEvent(self, event): k = event.key() if k == 16777236: self.update_sandbox(1) # if k == _CTRL: self.ctrl_down = True if self.ctrl_down: if k == _M: self.toggle_menu() # Menu toggled on Ctrl+M elif k == _R: self.reroll_pile() else: if k == _F11: self.toggle_fullscreen() elif k == _SPACE and not self.in_menu: self.toggle_pause() def keyReleaseEvent(self, event): if event.key() == _CTRL: self.ctrl_down = False def resizeEvent(self, event): self.pause_label.setGeometry(self.rect()) sbg = self.sandbox.geometry() sbs = self.sandbox.size() self.sandbox_bg.setGeometry(sbg) self.sandbox_bg.setPixmap(self.sandbox_bg.pixmap().scaled( self.sandbox_bg.size())) for c in self.canvases: c.setGeometry(sbg) c.setPixmap(c.pixmap().scaled(sbs, Qt.KeepAspectRatio)) ### Fix this. def toggle_fullscreen(self): self.in_fullscreen = not self.in_fullscreen self.showFullScreen() if self.in_fullscreen else self.showNormal() def toggle_menu(self): self.in_menu = not self.in_menu if self.in_menu: self.layout.setCurrentIndex(1) self.pause_label.setVisible(False) self.on_pause = True self.root.restoreOverrideCursor() else: self.layout.setCurrentIndex(0) if self.on_pause: self.pause_label.raise_() self.pause_label.setVisible(True) else: self.root.setOverrideCursor(Qt.BlankCursor) self.resizeEvent(None) def toggle_pause(self): self.on_pause = not self.on_pause if self.on_pause: self.timer.stop() self.pause_label.raise_() self.pause_label.setVisible(True) self.root.restoreOverrideCursor() else: self.pause_label.setVisible(False) self.timer.singleShot(self.timer_delay, lambda: self.update_sandbox(0)) self.root.setOverrideCursor(Qt.BlankCursor) def update_sandbox(self, mode): if not self.in_menu: if mode == self.on_pause: self.phase -= self.delta_per_tick if self.phase <= 0: self.canvases[-1].setPixmap(self.canvases[0].pixmap()) self.phase = 1 self.opeff.setOpacity(self.phase) if not self.sandpile.topple_step() and not self.on_pause: self.toggle_pause() xpm, sz = generate_xpm(self.sandpile) self.canvases[0].setPixmap( QPixmap(xpm).scaled(self.sandbox.size(), Qt.KeepAspectRatio)) else: self.opeff.setOpacity( math.pow(math.sin(math.pi * self.phase / 2), 2)) if mode == 0 and self.app_running: self.timer.singleShot(self.timer_delay, lambda: self.update_sandbox(0))
class HomeFeed(QWidget): def __init__(self): super(HomeFeed, self).__init__() self.run_get_feed_thread() self.feed = [] self.page = 1 self.loading = False self.layout = QStackedLayout() self.layout.setMargin(0) self.loading_label = QLabel('Loading...', alignment=Qt.AlignCenter) self.layout.addWidget(self.loading_label) self.layout.setCurrentWidget(self.loading_label) self.page_widget = QScrollArea() self.page_widget.setWidgetResizable(True) self.page_widget.viewport().installEventFilter(self) widget = QWidget(self.page_widget) widget.setMinimumWidth(350) self.page_widget.setWidget(widget) self.flow_layout = FlowLayout(widget) self.flow_layout.setContentsMargins(25, 25, 25, 25) self.layout.addWidget(self.page_widget) self.setLayout(self.layout) def run_get_feed_thread(self): self.thread = RunThread(self.get_feed, self.on_feed_receive) def eventFilter(self, source, event): if (event.type() == QEvent.Wheel and source is self.page_widget.viewport() and not self.loading): scrollbar = self.page_widget.verticalScrollBar() y = scrollbar.value() bottom = scrollbar.maximum() if y >= bottom: self.page += 1 self.loading = True self.run_get_feed_thread() return super(HomeFeed, self).eventFilter(source, event) def get_feed(self): spider = CoreRadioSpider() self.feed = spider.get_home_feed(page=self.page) return True def on_feed_receive(self): if len(self.feed) > 0: for item in self.feed: preview_widget = SongPreview(artwork=item['artwork'], title=item['title'], url=item['href']) self.flow_layout.addWidget(preview_widget) self.loading = False self.layout.setCurrentWidget(self.page_widget) else: self.loading_label.setText( "Something wen't wrong, please try again")
class QSettingsWindow(QDialog): def __init__(self, game: Game): super(QSettingsWindow, self).__init__() self.game = game self.pluginsPage = None self.pluginsOptionsPage = None self.campaign_management_page = QWidget() self.setModal(True) self.setWindowTitle("Settings") self.setWindowIcon(CONST.ICONS["Settings"]) self.setMinimumSize(600, 250) self.initUi() def initUi(self): self.layout = QGridLayout() self.categoryList = QListView() self.right_layout = QStackedLayout() self.categoryList.setMaximumWidth(175) self.categoryModel = QStandardItemModel(self.categoryList) self.categoryList.setIconSize(QSize(32, 32)) self.initDifficultyLayout() difficulty = QStandardItem("Difficulty") difficulty.setIcon(CONST.ICONS["Missile"]) difficulty.setEditable(False) difficulty.setSelectable(True) self.categoryModel.appendRow(difficulty) self.right_layout.addWidget(self.difficultyPage) self.init_campaign_management_layout() campaign_management = QStandardItem("Campaign Management") campaign_management.setIcon(CONST.ICONS["Money"]) campaign_management.setEditable(False) campaign_management.setSelectable(True) self.categoryModel.appendRow(campaign_management) self.right_layout.addWidget(self.campaign_management_page) self.initGeneratorLayout() generator = QStandardItem("Mission Generator") generator.setIcon(CONST.ICONS["Generator"]) generator.setEditable(False) generator.setSelectable(True) self.categoryModel.appendRow(generator) self.right_layout.addWidget(self.generatorPage) self.initCheatLayout() cheat = QStandardItem("Cheat Menu") cheat.setIcon(CONST.ICONS["Cheat"]) cheat.setEditable(False) cheat.setSelectable(True) self.categoryModel.appendRow(cheat) self.right_layout.addWidget(self.cheatPage) self.pluginsPage = PluginsPage() plugins = QStandardItem("LUA Plugins") plugins.setIcon(CONST.ICONS["Plugins"]) plugins.setEditable(False) plugins.setSelectable(True) self.categoryModel.appendRow(plugins) self.right_layout.addWidget(self.pluginsPage) self.pluginsOptionsPage = PluginOptionsPage() pluginsOptions = QStandardItem("LUA Plugins Options") pluginsOptions.setIcon(CONST.ICONS["PluginsOptions"]) pluginsOptions.setEditable(False) pluginsOptions.setSelectable(True) self.categoryModel.appendRow(pluginsOptions) self.right_layout.addWidget(self.pluginsOptionsPage) self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows) self.categoryList.setModel(self.categoryModel) self.categoryList.selectionModel().setCurrentIndex( self.categoryList.indexAt(QPoint(1, 1)), QItemSelectionModel.Select) self.categoryList.selectionModel().selectionChanged.connect( self.onSelectionChanged) self.layout.addWidget(self.categoryList, 0, 0, 1, 1) self.layout.addLayout(self.right_layout, 0, 1, 5, 1) self.setLayout(self.layout) def init(self): pass def initDifficultyLayout(self): self.difficultyPage = QWidget() self.difficultyLayout = QVBoxLayout() self.difficultyLayout.setAlignment(Qt.AlignTop) self.difficultyPage.setLayout(self.difficultyLayout) # DCS AI difficulty settings self.aiDifficultySettings = QGroupBox("AI Difficulty") self.aiDifficultyLayout = QGridLayout() self.playerCoalitionSkill = QComboBox() self.enemyCoalitionSkill = QComboBox() self.enemyAASkill = QComboBox() for skill in CONST.SKILL_OPTIONS: self.playerCoalitionSkill.addItem(skill) self.enemyCoalitionSkill.addItem(skill) self.enemyAASkill.addItem(skill) self.playerCoalitionSkill.setCurrentIndex( CONST.SKILL_OPTIONS.index(self.game.settings.player_skill)) self.enemyCoalitionSkill.setCurrentIndex( CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill)) self.enemyAASkill.setCurrentIndex( CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill)) self.player_income = TenthsSpinSlider( "Player income multiplier", 0, 50, int(self.game.settings.player_income_multiplier * 10), ) self.player_income.spinner.valueChanged.connect(self.applySettings) self.enemy_income = TenthsSpinSlider( "Enemy income multiplier", 0, 50, int(self.game.settings.enemy_income_multiplier * 10), ) self.enemy_income.spinner.valueChanged.connect(self.applySettings) self.playerCoalitionSkill.currentIndexChanged.connect( self.applySettings) self.enemyCoalitionSkill.currentIndexChanged.connect( self.applySettings) self.enemyAASkill.currentIndexChanged.connect(self.applySettings) # Mission generation settings related to difficulty self.missionSettings = QGroupBox("Mission Difficulty") self.missionLayout = QGridLayout() self.manpads = QCheckBox() self.manpads.setChecked(self.game.settings.manpads) self.manpads.toggled.connect(self.applySettings) self.noNightMission = QCheckBox() self.noNightMission.setChecked(self.game.settings.night_disabled) self.noNightMission.toggled.connect(self.applySettings) # DCS Mission options self.missionRestrictionsSettings = QGroupBox("Mission Restrictions") self.missionRestrictionsLayout = QGridLayout() self.difficultyLabel = QComboBox() [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS] self.difficultyLabel.setCurrentIndex( CONST.LABELS_OPTIONS.index(self.game.settings.labels)) self.difficultyLabel.currentIndexChanged.connect(self.applySettings) self.mapVisibiitySelection = QComboBox() self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All: self.mapVisibiitySelection.setCurrentIndex(0) self.mapVisibiitySelection.addItem("Fog of War", ForcedOptions.Views.Allies) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies: self.mapVisibiitySelection.setCurrentIndex(1) self.mapVisibiitySelection.addItem("Allies Only", ForcedOptions.Views.OnlyAllies) if (self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyAllies): self.mapVisibiitySelection.setCurrentIndex(2) self.mapVisibiitySelection.addItem("Own Aircraft Only", ForcedOptions.Views.MyAircraft) if (self.game.settings.map_coalition_visibility == ForcedOptions.Views.MyAircraft): self.mapVisibiitySelection.setCurrentIndex(3) self.mapVisibiitySelection.addItem("Map Only", ForcedOptions.Views.OnlyMap) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap: self.mapVisibiitySelection.setCurrentIndex(4) self.mapVisibiitySelection.currentIndexChanged.connect( self.applySettings) self.ext_views = QCheckBox() self.ext_views.setChecked(self.game.settings.external_views_allowed) self.ext_views.toggled.connect(self.applySettings) self.aiDifficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0) self.aiDifficultyLayout.addWidget(self.playerCoalitionSkill, 0, 1, Qt.AlignRight) self.aiDifficultyLayout.addWidget(QLabel("Enemy coalition skill"), 1, 0) self.aiDifficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1, Qt.AlignRight) self.aiDifficultyLayout.addWidget( QLabel("Enemy AA and vehicles skill"), 2, 0) self.aiDifficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight) self.aiDifficultyLayout.addLayout(self.player_income, 3, 0) self.aiDifficultyLayout.addLayout(self.enemy_income, 4, 0) self.aiDifficultySettings.setLayout(self.aiDifficultyLayout) self.difficultyLayout.addWidget(self.aiDifficultySettings) self.missionLayout.addWidget(QLabel("Manpads on frontlines"), 0, 0) self.missionLayout.addWidget(self.manpads, 0, 1, Qt.AlignRight) self.missionLayout.addWidget(QLabel("No night missions"), 1, 0) self.missionLayout.addWidget(self.noNightMission, 1, 1, Qt.AlignRight) self.missionSettings.setLayout(self.missionLayout) self.difficultyLayout.addWidget(self.missionSettings) self.missionRestrictionsLayout.addWidget(QLabel("In Game Labels"), 0, 0) self.missionRestrictionsLayout.addWidget(self.difficultyLabel, 0, 1, Qt.AlignRight) self.missionRestrictionsLayout.addWidget( QLabel("Map visibility options"), 1, 0) self.missionRestrictionsLayout.addWidget(self.mapVisibiitySelection, 1, 1, Qt.AlignRight) self.missionRestrictionsLayout.addWidget( QLabel("Allow external views"), 2, 0) self.missionRestrictionsLayout.addWidget(self.ext_views, 2, 1, Qt.AlignRight) self.missionRestrictionsSettings.setLayout( self.missionRestrictionsLayout) self.difficultyLayout.addWidget(self.missionRestrictionsSettings) def init_campaign_management_layout(self) -> None: campaign_layout = QVBoxLayout() campaign_layout.setAlignment(Qt.AlignTop) self.campaign_management_page.setLayout(campaign_layout) general = QGroupBox("General") campaign_layout.addWidget(general) general_layout = QGridLayout() general.setLayout(general_layout) def set_restict_weapons_by_date(value: bool) -> None: self.game.settings.restrict_weapons_by_date = value restrict_weapons = QCheckBox() restrict_weapons.setChecked( self.game.settings.restrict_weapons_by_date) restrict_weapons.toggled.connect(set_restict_weapons_by_date) tooltip_text = ( "Restricts weapon availability based on the campaign date. Data is " "extremely incomplete so does not affect all weapons.") restrict_weapons.setToolTip(tooltip_text) restrict_weapons_label = QLabel("Restrict weapons by date (WIP)") restrict_weapons_label.setToolTip(tooltip_text) general_layout.addWidget(restrict_weapons_label, 0, 0) general_layout.addWidget(restrict_weapons, 0, 1, Qt.AlignRight) def set_old_awec(value: bool) -> None: self.game.settings.disable_legacy_aewc = value old_awac = QCheckBox() old_awac.setChecked(self.game.settings.disable_legacy_aewc) old_awac.toggled.connect(set_old_awec) old_awec_info = ( "If checked, the invulnerable friendly AEW&C aircraft that begins " "the mission in the air will not be spawned. AEW&C missions must " "be planned in the ATO and will take time to arrive on-station.") old_awac.setToolTip(old_awec_info) old_awac_label = QLabel( "Disable invulnerable, always-available AEW&C (WIP)") old_awac_label.setToolTip(old_awec_info) general_layout.addWidget(old_awac_label, 1, 0) general_layout.addWidget(old_awac, 1, 1, Qt.AlignRight) automation = QGroupBox("HQ Automation") campaign_layout.addWidget(automation) automation_layout = QGridLayout() automation.setLayout(automation_layout) def set_runway_automation(value: bool) -> None: self.game.settings.automate_runway_repair = value def set_front_line_automation(value: bool) -> None: self.game.settings.automate_front_line_reinforcements = value def set_aircraft_automation(value: bool) -> None: self.game.settings.automate_aircraft_reinforcements = value runway_repair = QCheckBox() runway_repair.setChecked(self.game.settings.automate_runway_repair) runway_repair.toggled.connect(set_runway_automation) automation_layout.addWidget(QLabel("Automate runway repairs"), 0, 0) automation_layout.addWidget(runway_repair, 0, 1, Qt.AlignRight) front_line = QCheckBox() front_line.setChecked( self.game.settings.automate_front_line_reinforcements) front_line.toggled.connect(set_front_line_automation) automation_layout.addWidget(QLabel("Automate front-line purchases"), 1, 0) automation_layout.addWidget(front_line, 1, 1, Qt.AlignRight) aircraft = QCheckBox() aircraft.setChecked( self.game.settings.automate_aircraft_reinforcements) aircraft.toggled.connect(set_aircraft_automation) automation_layout.addWidget(QLabel("Automate aircraft purchases"), 2, 0) automation_layout.addWidget(aircraft, 2, 1, Qt.AlignRight) def initGeneratorLayout(self): self.generatorPage = QWidget() self.generatorLayout = QVBoxLayout() self.generatorLayout.setAlignment(Qt.AlignTop) self.generatorPage.setLayout(self.generatorLayout) self.gameplay = QGroupBox("Gameplay") self.gameplayLayout = QGridLayout() self.gameplayLayout.setAlignment(Qt.AlignTop) self.gameplay.setLayout(self.gameplayLayout) self.supercarrier = QCheckBox() self.supercarrier.setChecked(self.game.settings.supercarrier) self.supercarrier.toggled.connect(self.applySettings) self.generate_marks = QCheckBox() self.generate_marks.setChecked(self.game.settings.generate_marks) self.generate_marks.toggled.connect(self.applySettings) self.generate_dark_kneeboard = QCheckBox() self.generate_dark_kneeboard.setChecked( self.game.settings.generate_dark_kneeboard) self.generate_dark_kneeboard.toggled.connect(self.applySettings) self.never_delay_players = QCheckBox() self.never_delay_players.setChecked( self.game.settings.never_delay_player_flights) self.never_delay_players.toggled.connect(self.applySettings) self.never_delay_players.setToolTip( "When checked, player flights with a delayed start time will be " "spawned immediately. AI wingmen may begin startup immediately.") self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0) self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight) self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"), 1, 0) self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight) dark_kneeboard_label = QLabel( "Generate Dark Kneeboard <br />" "<strong>Dark kneeboard for night missions.<br />" "This will likely make the kneeboard on the pilot leg unreadable.</strong>" ) self.gameplayLayout.addWidget(dark_kneeboard_label, 2, 0) self.gameplayLayout.addWidget(self.generate_dark_kneeboard, 2, 1, Qt.AlignRight) spawn_players_immediately_tooltip = ( "Always spawns player aircraft immediately, even if their start time is " "more than 10 minutes after the start of the mission. <strong>This does " "not alter the timing of your mission. Your TOT will not change. This " "option only allows the player to wait on the ground.</strong>") spawn_immediately_label = QLabel( "Player flights ignore TOT and spawn immediately<br />" "<strong>Does not adjust package waypoint times.<br />" "Should not be used if players have runway or in-air starts.</strong>" ) spawn_immediately_label.setToolTip(spawn_players_immediately_tooltip) self.gameplayLayout.addWidget(spawn_immediately_label, 3, 0) self.gameplayLayout.addWidget(self.never_delay_players, 3, 1, Qt.AlignRight) start_type_label = QLabel( "Default start type for AI aircraft<br /><strong>Warning: " "Any option other than Cold breaks OCA/Aircraft missions.</strong>" ) start_type_label.setToolTip(START_TYPE_TOOLTIP) start_type = StartTypeComboBox(self.game.settings) start_type.setCurrentText(self.game.settings.default_start_type) self.gameplayLayout.addWidget(start_type_label, 4, 0) self.gameplayLayout.addWidget(start_type, 4, 1) self.performance = QGroupBox("Performance") self.performanceLayout = QGridLayout() self.performanceLayout.setAlignment(Qt.AlignTop) self.performance.setLayout(self.performanceLayout) self.smoke = QCheckBox() self.smoke.setChecked(self.game.settings.perf_smoke_gen) self.smoke.toggled.connect(self.applySettings) self.red_alert = QCheckBox() self.red_alert.setChecked(self.game.settings.perf_red_alert_state) self.red_alert.toggled.connect(self.applySettings) self.arti = QCheckBox() self.arti.setChecked(self.game.settings.perf_artillery) self.arti.toggled.connect(self.applySettings) self.moving_units = QCheckBox() self.moving_units.setChecked(self.game.settings.perf_moving_units) self.moving_units.toggled.connect(self.applySettings) self.infantry = QCheckBox() self.infantry.setChecked(self.game.settings.perf_infantry) self.infantry.toggled.connect(self.applySettings) self.destroyed_units = QCheckBox() self.destroyed_units.setChecked( self.game.settings.perf_destroyed_units) self.destroyed_units.toggled.connect(self.applySettings) self.culling = QCheckBox() self.culling.setChecked(self.game.settings.perf_culling) self.culling.toggled.connect(self.applySettings) self.culling_distance = QSpinBox() self.culling_distance.setMinimum(10) self.culling_distance.setMaximum(10000) self.culling_distance.setValue( self.game.settings.perf_culling_distance) self.culling_distance.valueChanged.connect(self.applySettings) self.culling_do_not_cull_carrier = QCheckBox() self.culling_do_not_cull_carrier.setChecked( self.game.settings.perf_do_not_cull_carrier) self.culling_do_not_cull_carrier.toggled.connect(self.applySettings) self.performanceLayout.addWidget( QLabel("Smoke visual effect on frontline"), 0, 0) self.performanceLayout.addWidget(self.smoke, 0, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget( QLabel("SAM starts in RED alert mode"), 1, 0) self.performanceLayout.addWidget(self.red_alert, 1, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Artillery strikes"), 2, 0) self.performanceLayout.addWidget(self.arti, 2, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Moving ground units"), 3, 0) self.performanceLayout.addWidget(self.moving_units, 3, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget( QLabel("Generate infantry squads along vehicles"), 4, 0) self.performanceLayout.addWidget(self.infantry, 4, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget( QLabel("Include destroyed units carcass"), 6, 0) self.performanceLayout.addWidget(self.destroyed_units, 6, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1, 2) self.performanceLayout.addWidget( QLabel("Culling of distant units enabled"), 8, 0) self.performanceLayout.addWidget(self.culling, 8, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0) self.performanceLayout.addWidget(self.culling_distance, 9, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget( QLabel("Do not cull carrier's surroundings"), 10, 0) self.performanceLayout.addWidget(self.culling_do_not_cull_carrier, 10, 1, alignment=Qt.AlignRight) self.generatorLayout.addWidget(self.gameplay) self.generatorLayout.addWidget( QLabel( "Disabling settings below may improve performance, but will impact the overall quality of the experience." )) self.generatorLayout.addWidget(self.performance) def initCheatLayout(self): self.cheatPage = QWidget() self.cheatLayout = QVBoxLayout() self.cheatPage.setLayout(self.cheatLayout) self.cheat_options = CheatSettingsBox(self.game, self.applySettings) self.cheatLayout.addWidget(self.cheat_options) self.moneyCheatBox = QGroupBox("Money Cheat") self.moneyCheatBox.setAlignment(Qt.AlignTop) self.moneyCheatBoxLayout = QGridLayout() self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout) cheats_amounts = [25, 50, 100, 200, 500, 1000, -25, -50, -100, -200] for i, amount in enumerate(cheats_amounts): if amount > 0: btn = QPushButton("Cheat +" + str(amount) + "M") btn.setProperty("style", "btn-success") else: btn = QPushButton("Cheat " + str(amount) + "M") btn.setProperty("style", "btn-danger") btn.clicked.connect(self.cheatLambda(amount)) self.moneyCheatBoxLayout.addWidget(btn, i / 2, i % 2) self.cheatLayout.addWidget(self.moneyCheatBox, stretch=1) def cheatLambda(self, amount): return lambda: self.cheatMoney(amount) def cheatMoney(self, amount): logging.info("CHEATING FOR AMOUNT : " + str(amount) + "M") self.game.budget += amount if amount > 0: self.game.informations.append( Information( "CHEATER", "You are a cheater and you should feel bad", self.game.turn, )) else: self.game.informations.append( Information("CHEATER", "You are still a cheater !", self.game.turn)) GameUpdateSignal.get_instance().updateGame(self.game) def applySettings(self): self.game.settings.player_skill = CONST.SKILL_OPTIONS[ self.playerCoalitionSkill.currentIndex()] self.game.settings.enemy_skill = CONST.SKILL_OPTIONS[ self.enemyCoalitionSkill.currentIndex()] self.game.settings.enemy_vehicle_skill = CONST.SKILL_OPTIONS[ self.enemyAASkill.currentIndex()] self.game.settings.player_income_multiplier = self.player_income.value self.game.settings.enemy_income_multiplier = self.enemy_income.value self.game.settings.manpads = self.manpads.isChecked() self.game.settings.labels = CONST.LABELS_OPTIONS[ self.difficultyLabel.currentIndex()] self.game.settings.night_disabled = self.noNightMission.isChecked() self.game.settings.map_coalition_visibility = ( self.mapVisibiitySelection.currentData()) self.game.settings.external_views_allowed = self.ext_views.isChecked() self.game.settings.generate_marks = self.generate_marks.isChecked() self.game.settings.never_delay_player_flights = ( self.never_delay_players.isChecked()) self.game.settings.supercarrier = self.supercarrier.isChecked() self.game.settings.generate_dark_kneeboard = ( self.generate_dark_kneeboard.isChecked()) self.game.settings.perf_red_alert_state = self.red_alert.isChecked() self.game.settings.perf_smoke_gen = self.smoke.isChecked() self.game.settings.perf_artillery = self.arti.isChecked() self.game.settings.perf_moving_units = self.moving_units.isChecked() self.game.settings.perf_infantry = self.infantry.isChecked() self.game.settings.perf_destroyed_units = self.destroyed_units.isChecked( ) self.game.settings.perf_culling = self.culling.isChecked() self.game.settings.perf_culling_distance = int( self.culling_distance.value()) self.game.settings.perf_do_not_cull_carrier = ( self.culling_do_not_cull_carrier.isChecked()) self.game.settings.show_red_ato = self.cheat_options.show_red_ato self.game.settings.enable_frontline_cheats = ( self.cheat_options.show_frontline_cheat) self.game.settings.enable_base_capture_cheat = ( self.cheat_options.show_base_capture_cheat) self.game.compute_conflicts_position() GameUpdateSignal.get_instance().updateGame(self.game) def onSelectionChanged(self): index = self.categoryList.selectionModel().currentIndex().row() self.right_layout.setCurrentIndex(index)
def init_tab2(paths): tab2 = QWidget() tab2_layout = QHBoxLayout() tab2.setLayout(tab2_layout) filler = QLabel('') filler.setFixedWidth(1) # Left box tab2_leftbox = QWidget() tab2_leftbox_layout = QVBoxLayout() tab2_leftbox.setLayout(tab2_leftbox_layout) # Top tab2_leftbox_top = QWidget() tab2_leftbox_top_layout = QFormLayout() tab2_leftbox_top.setLayout(tab2_leftbox_top_layout) tab2_choose_option_workflow = choose_option('workflow', paths['nf']) tab2_choose_option_boxcar_convert = choose_option('boxcar_convert', paths['nf']) tab2_choose_option_profile = choose_option('profile', paths['sh']) tab2_choose_option_parallel_msconvert = choose_option( 'parallel_msconvert', paths['nf']) tab2_choose_option_parallel_quandenser = choose_option( 'parallel_quandenser', paths['nf']) # Always visible tab2_leftbox_top_layout.addRow(QLabel('Choose workflow'), tab2_choose_option_workflow) tab2_leftbox_top_layout.addRow(QLabel('Profile'), tab2_choose_option_profile) tab2_leftbox_top_layout.addRow(QLabel('Enable boxcar conversion'), tab2_choose_option_boxcar_convert) tab2_leftbox_top_layout.addRow(QLabel('Enable parallel MSconvert'), tab2_choose_option_parallel_msconvert) tab2_leftbox_top_layout.addRow(QLabel('Enable parallel quandenser'), tab2_choose_option_parallel_quandenser) tab2_leftbox_top_layout.addRow(filler, filler) # Empty space tab2_leftbox_layout.addWidget(tab2_leftbox_top) # Bottom, these will be hidden or shown depending on profile option tab2_hidden = QWidget() tab2_hidden.hidden_object = True tab2_hidden_layout = QStackedLayout() tab2_hidden.setLayout(tab2_hidden_layout) # Stack 1: Empty layout. Cluster disabled tab2_hidden_stack_1 = QWidget() tab2_hidden_stack_1_layout = QFormLayout() tab2_hidden_stack_1.setLayout(tab2_hidden_stack_1_layout) # Stack 2: Regular quandenser, cluster enabled tab2_hidden_stack_2 = QWidget() tab2_hidden_stack_2_layout = QFormLayout() tab2_hidden_stack_2_layout.setVerticalSpacing(0) tab2_hidden_stack_2.setLayout(tab2_hidden_stack_2_layout) stack_2_widgets = [] stack_2_widgets.append(get_tooltip('cluster-type')) stack_2_widgets.append(choose_option("process.executor", paths['nf'])) stack_2_widgets.append(filler) stack_2_widgets.append(get_tooltip('cluster-arguments')) stack_2_widgets.append( cluster_arguments("process.clusterOptions", paths['nf'])) stack_2_widgets.append(filler) stack_2_widgets.append(get_tooltip('cluster-queue')) stack_2_widgets.append(cluster_arguments("process.queue", paths['nf'])) stack_2_widgets.append(filler) stack_2_widgets.append(QLabel('MSconvert cpus + time')) stack_2_widgets.append(set_cpus("msconvert_cpus", paths['nf'])) stack_2_widgets.append(set_time("msconvert_time", paths['nf'])) stack_2_widgets.append(QLabel('Boxcar convert cpus + time')) stack_2_widgets.append(set_cpus("boxcar_convert_cpus", paths['nf'])) stack_2_widgets.append(set_time("boxcar_convert_time", paths['nf'])) stack_2_widgets.append(QLabel('Quandenser cpus + time')) stack_2_widgets.append(set_cpus("quandenser_cpus", paths['nf'])) stack_2_widgets.append(set_time("quandenser_time", paths['nf'])) stack_2_widgets.append(QLabel('Tide cpus + time')) stack_2_widgets.append(set_cpus("tide_search_cpus", paths['nf'])) stack_2_widgets.append(set_time("tide_search_time", paths['nf'])) stack_2_widgets.append(QLabel('Triqler cpus + time')) stack_2_widgets.append(set_cpus("triqler_cpus", paths['nf'])) stack_2_widgets.append(set_time("triqler_time", paths['nf'])) list_itr = iter(stack_2_widgets) for label in list_itr: combine_widget = QWidget() combine_widget_layout = QFormLayout() combine_widget.setLayout(combine_widget_layout) widget1, widget2 = next(list_itr), next(list_itr) combine_widget_layout.addRow(widget1, widget2) tab2_hidden_stack_2_layout.addRow(label, combine_widget) # Stack 3: Parallel quandenser, cluster enabled tab2_hidden_stack_3 = QWidget() tab2_hidden_stack_3_layout = QFormLayout() tab2_hidden_stack_3_layout.setVerticalSpacing(0) tab2_hidden_stack_3.setLayout(tab2_hidden_stack_3_layout) stack_3_widgets = [] stack_3_widgets.append(get_tooltip('cluster-type')) stack_3_widgets.append(choose_option("process.executor", paths['nf'])) stack_3_widgets.append(filler) stack_3_widgets.append(get_tooltip('cluster-arguments')) stack_3_widgets.append( cluster_arguments("process.clusterOptions", paths['nf'])) stack_3_widgets.append(filler) stack_3_widgets.append(get_tooltip('cluster-queue')) stack_3_widgets.append(cluster_arguments("process.queue", paths['nf'])) stack_3_widgets.append(filler) stack_3_widgets.append(QLabel('MSconvert cpus + time')) stack_3_widgets.append(set_cpus("msconvert_cpus", paths['nf'])) stack_3_widgets.append(set_time("msconvert_time", paths['nf'])) stack_3_widgets.append(QLabel('Boxcar convert cpus + time')) stack_3_widgets.append(set_cpus("boxcar_convert_cpus", paths['nf'])) stack_3_widgets.append(set_time("boxcar_convert_time", paths['nf'])) stack_3_widgets.append(QLabel('Quandenser p1 cpus + time')) stack_3_widgets.append(set_cpus("quandenser_parallel_1_cpus", paths['nf'])) stack_3_widgets.append(set_time("quandenser_parallel_1_time", paths['nf'])) stack_3_widgets.append(QLabel('Quandenser p2 cpus + time')) stack_3_widgets.append(set_cpus("quandenser_parallel_2_cpus", paths['nf'])) stack_3_widgets.append(set_time("quandenser_parallel_2_time", paths['nf'])) stack_3_widgets.append(QLabel('Quandenser p3 cpus + time')) stack_3_widgets.append(set_cpus("quandenser_parallel_3_cpus", paths['nf'])) stack_3_widgets.append(set_time("quandenser_parallel_3_time", paths['nf'])) stack_3_widgets.append(QLabel('Quandenser p4 cpus + time')) stack_3_widgets.append(set_cpus("quandenser_parallel_4_cpus", paths['nf'])) stack_3_widgets.append(set_time("quandenser_parallel_4_time", paths['nf'])) stack_3_widgets.append(QLabel('Tide cpus + time')) stack_3_widgets.append(set_cpus("tide_search_cpus", paths['nf'])) stack_3_widgets.append(set_time("tide_search_time", paths['nf'])) stack_3_widgets.append(QLabel('Triqler cpus + time')) stack_3_widgets.append(set_cpus("triqler_cpus", paths['nf'])) stack_3_widgets.append(set_time("triqler_time", paths['nf'])) stack_3_widgets.extend([filler, filler, filler]) # Empty space list_itr = iter(stack_3_widgets) for label in list_itr: combine_widget = QWidget() combine_widget_layout = QFormLayout() combine_widget.setLayout(combine_widget_layout) widget1, widget2 = next(list_itr), next(list_itr) combine_widget_layout.addRow(widget1, widget2) tab2_hidden_stack_3_layout.addRow(label, combine_widget) # Add stacks tab2_hidden_layout.addWidget(tab2_hidden_stack_1) tab2_hidden_layout.addWidget(tab2_hidden_stack_2) tab2_hidden_layout.addWidget(tab2_hidden_stack_3) # Add hidden stacked layout tab2_leftbox_layout.addWidget(tab2_hidden) # Right box tab2_rightbox = QWidget() tab2_rightbox_layout = QHBoxLayout() tab2_rightbox.setLayout(tab2_rightbox_layout) pipe_parser = custom_config_parser() pipe_parser.load(paths['pipe']) if pipe_parser.get('disable-opengl') in ['false', '']: tab2_workflow = workflow() tab2_rightbox_layout.addWidget(tab2_workflow) else: tab2_workflow = tooltip_label("OpenGL disabled", "OpenGL disabled", style=True) tab2_rightbox_layout.addWidget(tab2_workflow) tab2_layout.addWidget(tab2_rightbox) # Combine tab2_layout.addWidget(tab2_leftbox) tab2_layout.addWidget(tab2_rightbox) return tab2
class DLPGUI(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.parent = parent self.supported_setups = ['BOTTOM-UP', 'TOP-DOWN'] self.supported_projectors = ['VisitechLRSWQ', 'VisitechLRS4KA'] self.supported_motors = ['ClearpathSDSK', 'ClearpathSCSK', 'Nanostage'] self.selected_setup = self.supported_setups[0] self.selected_projector = self.supported_projectors[0] self.selected_motor = self.supported_motors[0] self.stacked_layout = QStackedLayout() self.__setup_widget = None self.__dlp_main_widget = None if not self.__load_settings__(): self.__init_configuration_selection_widget__() self.__init_projector_selection_widget__() self.__init_motor_selection_widget__() self.stacked_layout.setCurrentIndex(0) self.setLayout(self.stacked_layout) def minimumSizeHint(self): return self.stacked_layout.currentWidget().minimumSizeHint() def sizeHint(self): return self.stacked_layout.currentWidget().sizeHint() def __load_settings__(self): base_path = Path(__file__).parent settings_path = str( (base_path / '../resources/PRINTER_SETTINGS.json').resolve()) settings_file = QFile(settings_path) if settings_file.open(QIODevice.ReadOnly | QIODevice.Text): file_data = QJsonDocument.fromJson( settings_file.readAll()).object() if "dlp_settings" in file_data: printer_setup = str(file_data["dlp_settings"]["printer_setup"]) if printer_setup == self.supported_setups[0]: self.__select_setup__(0) elif printer_setup == self.supported_setups[1]: self.__select_setup__(1) else: return False projector_setup = str( file_data["dlp_settings"]["projector_setup"]) if projector_setup == self.supported_projectors[0]: self.__select_projector__(None, 0) elif projector_setup == self.supported_projectors[1]: self.__select_projector__(None, 1) else: return False motor_setup = str(file_data["dlp_settings"]["motor_setup"]) if motor_setup == self.supported_motors[0]: self.__select_motor__(None, 0) elif motor_setup == self.supported_motors[1]: self.__select_motor__(None, 1) elif motor_setup == self.supported_motors[2]: self.__select_motor__(None, 2) else: return False return True settings_file.close() return False def __init_configuration_selection_widget__(self): self.__setup_widget = QWidget(self) setup_layout = QHBoxLayout() for idx in range(len(self.supported_setups)): button = QPushButton(self.supported_setups[idx], self.__setup_widget) button.setFixedSize(200, 200) button.clicked.connect(self.__select_setup__) setup_layout.addWidget(button) self.__setup_widget.setLayout(setup_layout) self.stacked_layout.addWidget(self.__setup_widget) # self.stacked_layout.setCurrentIndex(0) def __init_projector_selection_widget__(self): self.__projector_setup_widget = QWidget(self) projector_setup_layout = QHBoxLayout() for idx in range(len(self.supported_projectors)): button = QPushButton(self.supported_projectors[idx], self.__setup_widget) button.setFixedSize(200, 200) button.clicked.connect( lambda state=None, x=idx: self.__select_projector__(state, x)) projector_setup_layout.addWidget(button) self.__projector_setup_widget.setLayout(projector_setup_layout) self.stacked_layout.addWidget(self.__projector_setup_widget) def __init_motor_selection_widget__(self): self.__motor_setup_widget = QWidget(self) motor_setup_layout = QHBoxLayout() for idx in range(len(self.supported_motors)): button = QPushButton(self.supported_motors[idx], self.__setup_widget) button.setFixedSize(200, 200) button.clicked.connect( lambda state=None, x=idx: self.__select_motor__(state, x)) motor_setup_layout.addWidget(button) self.__motor_setup_widget.setLayout(motor_setup_layout) self.stacked_layout.addWidget(self.__motor_setup_widget) def __select_setup__(self, idx): self.selected_setup = self.supported_setups[idx] self.stacked_layout.setCurrentIndex(1) def __select_projector__(self, button_state, projector_id): self.selected_projector = self.supported_projectors[projector_id] self.stacked_layout.setCurrentIndex(2) def __select_motor__(self, button_state, motor_id): self.selected_motor = self.supported_motors[motor_id] self.__init_main_widget__() self.stacked_layout.setCurrentIndex(3) # self.parent.move(self.desktops.screen(0).rect().center() - self.__dlp_main_widget.rect().center()) def __init_main_widget__(self): self.__dlp_main_widget = QTabWidget(self) self.__dlp_main_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.dlp_controller = DLPMainController(self.selected_setup, self.selected_projector, self.selected_motor) self.__printer_widget = DLPPrinterGUI( dlp_controller=self.dlp_controller, parent=self.__dlp_main_widget) self.__slicer_widget = DLPSlicerGUI(dlp_controller=self.dlp_controller, parent=self.__dlp_main_widget) self.__settings_widget = DLPSettingsGUI( dlp_controller=self.dlp_controller, parent=self.__dlp_main_widget) self.__printer_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.__slicer_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.__settings_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.__dlp_main_widget.addTab(self.__printer_widget, 'DLP') self.__dlp_main_widget.addTab(self.__slicer_widget, 'Slicer') self.__dlp_main_widget.addTab(self.__settings_widget, 'Advanced Settings') self.stacked_layout.addWidget(self.__dlp_main_widget) self.dlp_controller.save_default_parameters() # self.__dlp_main_widget.move() # self.desktops = QDesktopWidget() # self.parent.move(self.desktops.screen(0).rect().center() - self.__dlp_main_widget.rect().center()) # self.__dlp_main_widget.move(QGuiApplication.desktop().screen().rect().center() - self.rect().center()) def reset_main_widget(self): self.dlp_controller.close_projector() self.__init_main_widget__() self.stacked_layout.setCurrentIndex(3) # self.parent.move(self.desktops.screen(0).rect().center() - self.__dlp_main_widget.rect().center()) @Slot() def closeEvent(self, event: QCloseEvent): if self.__setup_widget: self.__setup_widget.close() if self.__dlp_main_widget: self.__printer_widget.close() self.__slicer_widget.close() self.__settings_widget.close() self.__dlp_main_widget.close() event.accept() def get_settings_window(self, parent=None): printer_settings = QGroupBox("DLP Printer Settings:", parent) dlp_setup_label = QLabel("DLP Setup:", printer_settings) self.dlp_setup_combo = QComboBox(printer_settings) self.dlp_setup_combo.addItems(self.supported_setups) self.dlp_setup_combo.setCurrentIndex( self.supported_setups.index(self.selected_setup)) dlp_projector_label = QLabel("DLP Projector:", printer_settings) self.dlp_projector_combo = QComboBox(printer_settings) self.dlp_projector_combo.addItems(self.supported_projectors) self.dlp_projector_combo.setCurrentIndex( self.supported_projectors.index(self.selected_projector)) dlp_motor_label = QLabel("DLP Motor:", printer_settings) self.dlp_motor_combo = QComboBox(printer_settings) self.dlp_motor_combo.addItems(self.supported_motors) self.dlp_motor_combo.setCurrentIndex( self.supported_motors.index(self.selected_motor)) apply_button = QPushButton("Apply Changes", printer_settings) apply_button.clicked.connect(self.__apply_settings) printer_settings_layout = QGridLayout(printer_settings) printer_settings_layout.addWidget(dlp_setup_label, 1, 0) printer_settings_layout.addWidget(self.dlp_setup_combo, 1, 1) printer_settings_layout.addWidget(dlp_projector_label, 2, 0) printer_settings_layout.addWidget(self.dlp_projector_combo, 2, 1) printer_settings_layout.addWidget(dlp_motor_label, 3, 0) printer_settings_layout.addWidget(self.dlp_motor_combo, 3, 1) printer_settings_layout.addWidget(apply_button, 4, 1) return printer_settings @Slot() def __apply_settings(self): self.selected_setup = self.supported_setups[ self.dlp_setup_combo.currentIndex()] if self.supported_motors[self.dlp_motor_combo.currentIndex( )] is not self.selected_motor: self.selected_motor = self.supported_motors[ self.dlp_motor_combo.currentIndex()] self.dlp_controller.change_motor(self.selected_setup, self.selected_motor) if self.supported_projectors[self.dlp_projector_combo.currentIndex( )] is not self.selected_projector: self.selected_projector = self.supported_projectors[ self.dlp_projector_combo.currentIndex()] self.dlp_controller.change_projector(self.selected_projector) self.dlp_controller.save_default_parameters()
class DataProcessingDialog(QDialog): ''' Signals ''' newDataAdded = Signal(str, str, str) dataChanged = Signal(str, str, str) def __init__(self, dataManager, parent=None, inputList=None): self.operations = { 'Filtering': [FilterGroup, 'Filter settings', -1], 'Average': [AverageGroup, 'Window settings', -1], 'Energy': [EnergyGroup, 'Window settings', -1], 'Power': [PowerGroup, 'Window settings', -1], 'Peak-To-Peak': [Peak2PeakGroup, 'Window settings', -1], 'Variance': [VarianceGroup, 'Window settings', -1], 'Entropy': [EntropyGroup, 'Window settings', -1], 'Skewness': [SkewnessGroup, 'Window settings', -1], 'Thresholding': [ThresholdGroup, 'Settings', -1], 'Detrend': [DetrendGroup, 'Settings', -1], 'STFT': [STFTGroup, 'Spectrum settings', -1], 'CWT': [CWTGroup, 'CWT settings', -1] } QDialog.__init__(self, parent) self.dataManager = dataManager self.setWindowTitle('Data Processing') self.inputList = inputList #Setup Layouts self.mainLayout = QGridLayout(self) self.setupInLayout() self.setupProcessLayout() self.setupOutLayout() self.setupBtnBoxLayout() ''' Input Layout ''' def setupInLayout(self): inGroup = QGroupBox('Input to process') inLayout = QFormLayout(inGroup) self.inTree = DataSelector(self.dataManager, inputList=self.inputList) self.operChooser = QComboBox() [self.operChooser.addItem(i) for i in self.operations] self.operChooser.currentTextChanged.connect(self.setOperation) inLayout.addRow(QLabel('Select Input')) inLayout.addRow(self.inTree) inLayout.addRow(QLabel('Operation'), self.operChooser) self.mainLayout.addWidget(inGroup, 0, 0) def setOperation(self): print('Set Operation') index = self.operations[self.operChooser.currentText()][2] self.processLayout.setCurrentIndex(index) ''' Signal Processing Settings Layout ''' def setupProcessLayout(self): processGroup = QGroupBox('Processing settings') self.processLayout = QStackedLayout() self.mainLayout.addLayout(self.processLayout, 1, 0) # Setup Processing Sublayouts for op in self.operations: index = self.createGroup(self.operations[op][0], op, self.operations[op][1]) self.operations[op][2] = index ''' Create Groups ''' def createGroup(self, GroupClass, name, title): newGroup = GroupClass(title, fs=self.dataManager.getFs()) newGroup.progress.connect(self.updateProgress) index = self.processLayout.addWidget(newGroup) return index ''' Output Layout ''' def setupOutLayout(self): outGroup = QGroupBox('Output') outLayout = QFormLayout(outGroup) self.outNameEdit = QLineEdit() inAsOutCheck = QCheckBox('Replace input') inAsOutCheck.toggled.connect(self.setInputAsOutput) outLayout.addWidget(inAsOutCheck) outLayout.addRow('Output name', self.outNameEdit) self.mainLayout.addWidget(outGroup, 2, 0) def setInputAsOutput(self, isOn): if isOn: inStruct = self.inTree.getSelectedStruct() wName = list(inStruct.keys())[0] gName = list(inStruct[wName].keys())[0] self.outNameEdit.setText(gName) self.outNameEdit.setDisabled(True) else: self.outNameEdit.setEnabled(True) ''' Button Box Layout ''' def setupBtnBoxLayout(self): bottomLayout = QHBoxLayout() self.progBar = QProgressBar() self.progBar.setVisible(False) bottomLayout.addWidget(self.progBar) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Close) buttonBox.accepted.connect(self.okBtnBox) buttonBox.rejected.connect(self.close) bottomLayout.addWidget(buttonBox) self.mainLayout.addLayout(bottomLayout, 3, 0) def okBtnBox(self): inStruct = self.inTree.getSelectedStruct() data = self.dataManager.getData(inStruct, inv=True) wName = list(data.keys())[0] gName = list(data[wName].keys())[0] outName = self.outNameEdit.text() if outName in self.dataManager[wName].getColumnNames(): msgBox = QMessageBox() msgBox.setText('Signal already exists') msgBox.setInformativeText("Do you want to replace it?") msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Ok) ret = msgBox.exec() if ret == QMessageBox.Ok: self.dataManager.removeSignal(wName, outName) print('removed') else: return self.progBar.setVisible(True) outData = self.processLayout.currentWidget().process( data[wName][gName]) self.dataManager.appendSignal(wName, outName, inStruct[wName][gName], outData) self.newDataAdded.emit(wName, gName, self.outNameEdit.text()) def updateProgress(self, prog): self.progBar.setValue(prog)
def buildLayout(self): stacked_layout_1 = QStackedLayout() # stacked_layout_1.addWidget(QWidget()) stacked_layout_1.addWidget(self.p_top_bar) stacked_layout_1.addWidget(self.s_top_bar) stacked_layout_2 = QStackedLayout() # stacked_layout_2.addWidget(QWidget()) stacked_layout_2.addWidget(self.p_options_1) stacked_layout_2.addWidget(self.p_options_2) stacked_layout_2.addWidget(self.p_options_3) stacked_layout_2.addWidget(self.p_options_4) stacked_layout_2.addWidget(self.p_options_5) stacked_layout_2.addWidget(self.p_options_6) stacked_layout_2.addWidget(self.s_options_1) stacked_layout_2.addWidget(self.s_options_2) stacked_layout_2.addWidget(self.s_options_3) stacked_layout_2.addWidget(self.s_options_4) self.stacked_layout_3 = QStackedLayout() self.stacked_layout_3.addWidget(self.scroll_area_1) self.stacked_layout_3.addWidget(self.scroll_area_2) central_widget_layout = QVBoxLayout() central_widget_layout.addWidget(self.bar_widget) central_widget_layout.addLayout(self.stacked_layout_3) self.central_widget.setLayout(central_widget_layout) self.bar_widget.setLayout(stacked_layout_1) self.options_widget.setLayout(stacked_layout_2)
class ScaleWidget(QWidget): stretches_list = ['powerdist', 'asinh', 'contrastbias', 'histogram', 'linear', 'log', 'power', 'sinh', 'sqrt', 'square'] intervals_list = ['zscale', 'minmax', 'manual', 'percentile', 'asymetric'] def __init__(self, parent, scales_model, cmap_model): QWidget.__init__(self, parent) self.parent = parent self.scalesModel = scales_model self.cmapModel = cmap_model self.ignore_signals = False layout = QVBoxLayout() layout.setSpacing(0) # pernament linear stretch self.perm_linear_widget = self.createLinearSliders() layout.addWidget(QLabel('Linear')) layout.addWidget(self.perm_linear_widget) # comboboxes self.combobox_widget = QWidget() self.combobox_layout = self.createComboboxes() self.combobox_widget.setLayout(self.combobox_layout) layout.addWidget(self.combobox_widget) # Stretch self.stretch_sliders_widget = QWidget() self.stretch_sliders_layout = self.createStretchStackedLayout() self.stretch_sliders_widget.setLayout(self.stretch_sliders_layout) layout.addWidget(self.stretch_sliders_widget) # Interval self.interval_sliders_widget = QWidget() self.interval_sliders_layout = self.createIntervalStackedLayout() self.interval_sliders_widget.setLayout(self.interval_sliders_layout) layout.addWidget(self.interval_sliders_widget) self.setLayout(layout) self.adjustCombos() self.adjustCmapCombo() self.adjustSliders() self.scalesModel.observe(lambda change: self.onScaleModelChange(change)) self.cmapModel.observe(lambda change: self.onCmapModelChange(change)) def createStretchStackedLayout(self): self.stretchStackedLayout = QStackedLayout() asinh = self.createAsinhParamsSliders() contrastbias = self.createContrastbiasParamsSliders() histogram = QLabel('') linear = QLabel('') log = self.createLogSliders() powerdist = self.createPowerdistSliders() power = self.createPowerSliders() sinh = self.createSinhSliders() sqrt = QLabel('') square = QLabel('') self.stretchStackedLayout.addWidget(powerdist) self.stretchStackedLayout.addWidget(asinh) self.stretchStackedLayout.addWidget(contrastbias) self.stretchStackedLayout.addWidget(histogram) self.stretchStackedLayout.addWidget(linear) self.stretchStackedLayout.addWidget(log) self.stretchStackedLayout.addWidget(power) self.stretchStackedLayout.addWidget(sinh) self.stretchStackedLayout.addWidget(sqrt) self.stretchStackedLayout.addWidget(square) return self.stretchStackedLayout def createIntervalStackedLayout(self): self.intervalStackedLayout = QStackedLayout() manual = self.createManualParamsSliders() percentile = self.createPercentileParamsSliders() asymetric = self.createAsymetricParamsSliders() zscale = self.createZscaleParamsSliders() self.intervalStackedLayout.addWidget(zscale) self.intervalStackedLayout.addWidget(QLabel("")) self.intervalStackedLayout.addWidget(manual) self.intervalStackedLayout.addWidget(percentile) self.intervalStackedLayout.addWidget(asymetric) return self.intervalStackedLayout def createManualParamsSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.manual_vmin = FloatSlider(min=0.0, max=30000.0) self.manual_vmax = IntSlider(min=0, max=30000) self.manual_vmin.valueChanged.connect(lambda val=vars: self.onSliderChange('interval_manual_vmin', val)) self.manual_vmax.valueChanged.connect(lambda val=vars: self.onSliderChange('interval_manual_vmax', val)) layout.addRow('vmin', self.manual_vmin) layout.addRow('vmax', self.manual_vmax) widget.setLayout(layout) return widget def createPercentileParamsSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.percentile_percentile = FloatSlider(min=0.1, max=2.0) self.percentile_nsamples = IntSlider(min=1, max=2000) self.percentile_percentile.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_percentile_percentile', val)) self.percentile_nsamples.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_percentile_nsamples', val)) layout.addRow('percentile', self.percentile_percentile) layout.addRow('samples', self.percentile_nsamples) widget.setLayout(layout) return widget def createAsymetricParamsSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.asymetric_lpercentile = FloatSlider(min=0.0, max=2.0) self.asymetric_upercentile = FloatSlider(min=0.0, max=2.0) self.asymetric_nsamples = IntSlider(min=0, max=2000) self.asymetric_lpercentile.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_asymetric_lower_percentile', val)) self.asymetric_upercentile.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_asymetric_upper_percentile', val)) self.asymetric_nsamples.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_asymetric_nsamples', val)) layout.addRow("l_percentile", self.asymetric_lpercentile) layout.addRow("u_percentile", self.asymetric_upercentile) layout.addRow("samples", self.asymetric_nsamples) widget.setLayout(layout) widget.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) return widget def createZscaleParamsSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.zscale_nsamples = IntSlider(min=0, max=2000) self.zscale_contrast = FloatSlider(min=0.0, max=2.0) self.zscale_mreject = FloatSlider(min=0.0, max=2.0) self.zscale_minpixels = IntSlider(min=0.0, max=20) self.zscale_krej = FloatSlider(min=0.0, max=5.0) self.zscale_miterations = IntSlider(min=0, max=20) self.zscale_nsamples.valueChanged.connect(lambda val=vars: self.onSliderChange('interval_zscale_nsamples', val)) self.zscale_contrast.valueChanged.connect(lambda val=vars: self.onSliderChange('interval_zscale_contrast', val)) self.zscale_mreject.valueChanged.connect(lambda val=vars: self.onSliderChange('interval_zscale_maxreject', val)) self.zscale_minpixels.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_zscale_minpixels', val)) self.zscale_krej.valueChanged.connect(lambda val=vars: self.onSliderChange('interval_zscale_krej', val)) self.zscale_miterations.valueChanged.connect( lambda val=vars: self.onSliderChange('interval_zscale_maxiterations', val)) layout.addRow("samples", self.zscale_nsamples) layout.addRow("contrast", self.zscale_contrast) layout.addRow("max reject", self.zscale_mreject) layout.addRow("pixels", self.zscale_minpixels) layout.addRow("krej", self.zscale_krej) layout.addRow("m_iterations", self.zscale_miterations) widget.setLayout(layout) return widget def createComboboxes(self): layout = QHBoxLayout() self.stretch_combobox = QComboBox() self.stretch_combobox.setFocusPolicy(Qt.NoFocus) self.stretch_combobox.addItems(self.stretches_list) self.interval_combobox = QComboBox() self.interval_combobox.setFocusPolicy(Qt.NoFocus) self.interval_combobox.addItems(self.intervals_list) self.color_combobox = QComboBox() self.color_combobox.setFocusPolicy(Qt.NoFocus) self.color_combobox.addItems(self.cmapModel.colormaps.keys()) self.color_combobox.setCurrentText(self.cmapModel.cmap_idx) layout.addWidget(self.stretch_combobox) layout.addWidget(self.interval_combobox) layout.addWidget(self.color_combobox) self.stretch_combobox.activated.connect(lambda activated: self.on_select_stretch()) self.interval_combobox.activated.connect(lambda activated: self.on_select_interval()) self.color_combobox.activated.connect(lambda activated: self.on_select_cmap()) return layout # For functionalty below, see FitsPlotterControlled.scale_from_model() # def fitsNormalization(self, stretch, interval): # self.parent.fits_image.set_normalization(stretch=stretch, # interval=interval, # stretchkwargs=self.scalesModel.dictionary[stretch], # intervalkwargs=self.scalesModel.dictionary[interval]) # # self.parent.fits_image.invalidate() # self.parent.updateFitsInWidgets() def createAsinhParamsSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.asinh_a = FloatSlider(min=0.1, max=2.0) self.asinh_a.valueChanged.connect( lambda val=vars: self.onSliderChange('stretch_asinh_a', val)) layout.addRow('a', self.asinh_a) widget.setLayout(layout) return widget def createContrastbiasParamsSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.contrast_contrast = FloatSlider(min=0.0, max=4.0) self.contrast_bias = FloatSlider(min=0.0, max=2.0) self.contrast_contrast.valueChanged.connect( lambda val=vars: self.onSliderChange('stretch_contrastbias_contrast', val)) self.contrast_bias.valueChanged.connect(lambda val=vars: self.onSliderChange('stretch_contrastbias_bias', val)) layout.addRow('contrast', self.contrast_contrast) layout.addRow('bias', self.contrast_bias) widget.setLayout(layout) return widget def createLinearSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.linear_slope = FloatSlider(min=0.1, max=3.0) self.linear_intercept = FloatSlider(min=-1.0, max=1.0) self.linear_slope.valueChanged.connect(lambda val=vars: self.onSliderChange('stretch_linear_slope', val)) self.linear_intercept.valueChanged.connect( lambda val=vars: self.onSliderChange('stretch_linear_intercept', val)) layout.addRow('slope', self.linear_slope) layout.addRow('intercept', self.linear_intercept) widget.setLayout(layout) return widget def createLogSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.log_a = FloatSlider(min=0.1, max=2000.0) self.log_a.valueChanged.connect(lambda val=vars: self.onSliderChange('stretch_log_a', val)) layout.addRow('a', self.log_a) widget.setLayout(layout) return widget def createPowerdistSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.powerdist_a = FloatSlider(min=10.0, max=2000.0) self.powerdist_a.valueChanged.connect(lambda val=vars: self.onSliderChange('stretch_powerdist_a', val)) layout.addRow('a', self.powerdist_a) widget.setLayout(layout) return widget def createPowerSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.power_a = FloatSlider(min=0.1, max=2.0) self.power_a.valueChanged.connect(lambda val=vars: self.onSliderChange('stretch_power_a', val)) layout.addRow('a', self.power_a) widget.setLayout(layout) return widget def createSinhSliders(self): widget = QWidget() layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.sinh_a = FloatSlider(min=0.1, max=1.0) self.sinh_a.valueChanged.connect(lambda val=vars: self.onSliderChange('stretch_sinh_a', val)) layout.addRow('a', self.sinh_a) widget.setLayout(layout) return widget def onSliderChange(self, param, value): if self.ignore_signals: return self.ignore_signals = True try: setattr(self.scalesModel, param, value) finally: self.ignore_signals = False def onScaleModelChange(self, change): if self.ignore_signals: # avoid selfupdate on moving sliders return self.adjustCombos() self.adjustSliders() def onCmapModelChange(self, change): self.adjustCmapCombo() def on_select_stretch(self): self.scalesModel.selected_stretch = self.stretch_combobox.currentText() def on_select_interval(self): self.scalesModel.selected_interval = self.interval_combobox.currentText() def on_select_cmap(self): self.cmapModel.cmap_idx = self.color_combobox.currentText() def adjustCombos(self): """Select layout page from model and set scale combos value""" self.stretch_combobox.setCurrentText(self.scalesModel.selected_stretch) self.interval_combobox.setCurrentText(self.scalesModel.selected_interval) try: self.stretchStackedLayout.setCurrentIndex( self.stretches_list.index(self.scalesModel.selected_stretch)) except ValueError: pass try: self.intervalStackedLayout.setCurrentIndex( self.intervals_list.index(self.scalesModel.selected_interval)) except ValueError: pass try: self.adjustWidgetHeight(self.scalesModel.selected_stretch, self.scalesModel.selected_interval) except ValueError: pass # self.fitsNormalization(self.stretch_combobox.currentText(), self.interval_combobox.currentText()) def adjustWidgetHeight(self, stretch, interval): self.perm_linear_widget.setMaximumHeight(100) self.combobox_widget.setMaximumHeight(40) widget_height = 160 if stretch == 'linear' or stretch == 'histogram' or stretch == 'sqrt' or stretch == 'square': self.stretch_sliders_widget.hide() else: self.stretch_sliders_widget.show() if stretch == 'contrastbias' or stretch == 'linear': widget_height = widget_height + 100 self.stretch_sliders_widget.setMaximumHeight(100) else: widget_height = widget_height + 50 self.stretch_sliders_widget.setMaximumHeight(50) if interval == 'minmax': self.interval_sliders_widget.hide() else: self.interval_sliders_widget.show() if interval == 'asymetric': widget_height = widget_height + 120 self.interval_sliders_widget.setMaximumHeight(120) elif interval == 'zscale': widget_height = widget_height + 210 self.interval_sliders_widget.setMaximumHeight(210) else: widget_height = widget_height + 80 self.interval_sliders_widget.setMaximumHeight(80) self.setMaximumHeight(widget_height) def adjustCmapCombo(self): """Set combo value""" self.color_combobox.setCurrentText(self.cmapModel.cmap_idx) def adjustSliders(self): ignore_signals = self.ignore_signals self.ignore_signals = True try: self.manual_vmin.set_value_from_settings(self.scalesModel.interval_manual_vmin) self.manual_vmax.set_value_from_settings(self.scalesModel.interval_manual_vmax) self.percentile_percentile.set_value_from_settings(self.scalesModel.interval_percentile_percentile) self.percentile_nsamples.set_value_from_settings(self.scalesModel.interval_percentile_nsamples) self.asymetric_lpercentile.set_value_from_settings(self.scalesModel.interval_asymetric_lower_percentile) self.asymetric_upercentile.set_value_from_settings(self.scalesModel.interval_asymetric_upper_percentile) self.asymetric_nsamples.set_value_from_settings(self.scalesModel.interval_asymetric_nsamples) self.zscale_nsamples.set_value_from_settings(self.scalesModel.interval_zscale_nsamples) self.zscale_contrast.set_value_from_settings(self.scalesModel.interval_zscale_contrast) self.zscale_mreject.set_value_from_settings(self.scalesModel.interval_zscale_maxreject) self.zscale_minpixels.set_value_from_settings(self.scalesModel.interval_zscale_minpixels) self.zscale_krej.set_value_from_settings(self.scalesModel.interval_zscale_krej) self.zscale_miterations.set_value_from_settings(self.scalesModel.interval_zscale_maxiterations) self.asinh_a.set_value_from_settings(self.scalesModel.stretch_asinh_a) self.contrast_contrast.set_value_from_settings(self.scalesModel.stretch_contrastbias_contrast) self.contrast_bias.set_value_from_settings(self.scalesModel.stretch_contrastbias_bias) self.linear_slope.set_value_from_settings(self.scalesModel.stretch_linear_slope) self.linear_intercept.set_value_from_settings(self.scalesModel.stretch_linear_intercept) self.log_a.set_value_from_settings(self.scalesModel.stretch_log_a) self.powerdist_a.set_value_from_settings(self.scalesModel.stretch_powerdist_a) self.power_a.set_value_from_settings(self.scalesModel.stretch_power_a) self.sinh_a.set_value_from_settings(self.scalesModel.stretch_sinh_a) finally: self.ignore_signals = ignore_signals def writeSlidersValues(self): # TODO: Move Save/Load settings to model object settings = QSettings() settings.beginGroup("Sliders") settings.setValue("asinh/a", self.scalesModel.stretch_asinh_a) settings.setValue("contrast/contrast", self.scalesModel.stretch_contrastbias_contrast) settings.setValue("contrast/bias", self.scalesModel.stretch_contrastbias_bias) settings.setValue("linear/slope", self.scalesModel.stretch_linear_slope) settings.setValue("linear/intercept", self.scalesModel.stretch_linear_intercept) settings.setValue("log/a", self.scalesModel.stretch_log_a) settings.setValue("powerdist/a", self.scalesModel.stretch_powerdist_a) settings.setValue("power/a", self.scalesModel.stretch_power_a) settings.setValue("sinh/a", self.scalesModel.stretch_sinh_a) settings.setValue("manual/vmin", self.scalesModel.interval_manual_vmin) settings.setValue("manual/vmax", self.scalesModel.interval_manual_vmax) settings.setValue("percentile/percentile", self.scalesModel.interval_percentile_percentile) settings.setValue("percentile/nsamples", self.scalesModel.interval_percentile_nsamples) settings.setValue("asymetric/lpercentile", self.scalesModel.interval_asymetric_lower_percentile) settings.setValue("asymetric/upercentile", self.scalesModel.interval_asymetric_upper_percentile) settings.setValue("asymetric/nsamples", self.scalesModel.interval_asymetric_nsamples) settings.setValue("zscale/contrast", self.scalesModel.interval_zscale_contrast) settings.setValue("zscale/nsamples", self.scalesModel.interval_zscale_nsamples) settings.setValue("zscale/maxreject", self.scalesModel.interval_zscale_maxreject) settings.setValue("zscale/minpixels", self.scalesModel.interval_zscale_minpixels) settings.setValue("zscale/krej", self.scalesModel.interval_zscale_krej) settings.setValue("zscale/maxiterations", self.scalesModel.interval_zscale_maxiterations) settings.setValue("cmap", self.cmapModel.cmap_idx) settings.setValue("stretch", self.scalesModel.selected_stretch) settings.setValue("interval", self.scalesModel.selected_interval) # settings.setValue("cmap", self.color_combobox.currentIndex()) settings.endGroup() def readSlidersValues(self): settings = QSettings() settings.beginGroup("Sliders") self.setModelValue('cmap_idx', settings.value("cmap"), model=self.cmapModel) self.setModelValue('selected_stretch', settings.value("stretch")) self.setModelValue('selected_interval', settings.value("interval")) # self.color_combobox.setCurrentIndex(settings.value("cmap", 3)) self.setModelValue('stretch_asinh_a', float(settings.value('asinh/a'))) self.setModelValue('stretch_contrastbias_contrast', float(settings.value('contrast/contrast'))) self.setModelValue('stretch_contrastbias_bias', float(settings.value('contrast/bias'))) self.setModelValue('stretch_linear_slope', float(settings.value('linear/slope'))) self.setModelValue('stretch_linear_intercept', float(settings.value('linear/intercept'))) self.setModelValue('stretch_log_a', float(settings.value('log/a'))) self.setModelValue('stretch_powerdist_a', float(settings.value('powerdist/a'))) self.setModelValue('stretch_power_a', float(settings.value('power/a'))) self.setModelValue('stretch_sinh_a', float(settings.value('sinh/a'))) self.setModelValue('interval_manual_vmin', float(settings.value('manual/vmin'))) self.setModelValue('interval_manual_vmax', int(settings.value('manual/vmax'))) self.setModelValue('interval_percentile_percentile', float(settings.value('percentile/percentile'))) self.setModelValue('interval_percentile_nsamples', int(settings.value('percentile/nsamples'))) self.setModelValue('interval_asymetric_lower_percentile', float(settings.value('asymetric/lpercentile'))) self.setModelValue('interval_asymetric_upper_percentile', float(settings.value('asymetric/upercentile'))) self.setModelValue('interval_asymetric_nsamples', int(settings.value('asymetric/nsamples'))) self.setModelValue('interval_zscale_nsamples', int(settings.value('zscale/nsamples'))) self.setModelValue('interval_zscale_contrast', float(settings.value('zscale/contrast'))) self.setModelValue('interval_zscale_maxreject', float(settings.value('zscale/maxreject'))) self.setModelValue('interval_zscale_minpixels', int(settings.value('zscale/minpixels'))) self.setModelValue('interval_zscale_krej', float(settings.value('zscale/krej'))) self.setModelValue('interval_zscale_maxiterations', int(settings.value('zscale/maxiterations'))) settings.endGroup() def setModelValue(self, model_key, value, model=None): if model is None: model = self.scalesModel try: setattr(model, model_key, value) pass except TraitError: if value is not None: print(f'Attempt to set {model_key} := {value} caused exception. Ignored')
class SongDetailPage(QWidget): def __init__(self, url=None): super(SongDetailPage, self).__init__() self.url = url self.loading = False self.artwork_content = None self.artwork_size = 400 self.song = None self.layout = QStackedLayout() self.layout.setMargin(0) self.loading_label = QLabel('Loading...', alignment=Qt.AlignCenter) self.layout.addWidget(self.loading_label) self.layout.setCurrentWidget(self.loading_label) self.page_widget = QScrollArea() self.page_widget.setWidgetResizable(True) widget = QWidget(self.page_widget) widget.setMinimumWidth(800) self.page_widget.setWidget(widget) self.page_layout = QVBoxLayout(widget, alignment=Qt.AlignTop) self.page_layout.setContentsMargins(25, 25, 25, 25) self.layout.addWidget(self.page_widget) self.setLayout(self.layout) self.thread = RunThread(self.get_song_info, self.on_song_info) def render_song_info(self): # Header self.page_layout.addWidget(Header(song=self.song)) # Title title = H2(self.song['title']) title.setWordWrap(True) title.setStyleSheet('padding-top: 20px;') self.page_layout.addWidget(title) # Inner container that contains Image + Songlist inner_container = QWidget() inner_container_layout = QHBoxLayout(alignment=Qt.AlignTop | Qt.AlignLeft) inner_container_layout.setMargin(0) inner_container_layout.setSpacing(25) inner_container_layout.setContentsMargins(0, 25, 0, 0) inner_container.setLayout(inner_container_layout) self.page_layout.addWidget(inner_container) # Image self.artwork_label = QLabel() self.artwork_label.setStyleSheet( css('background-color: {{color}};', color=colors.PLACEHOLDER_COLOR)) self.artwork_label.setFixedWidth(self.artwork_size) self.artwork_label.setFixedHeight(self.artwork_size) inner_container_layout.addWidget(self.artwork_label, alignment=Qt.AlignTop) self.get_artwork_thread = RunThread(self.fetch_artwork, self.on_artwork_loaded) # Songlist inner_container_layout.addWidget( Songlist(songlist=self.song['songlist']), alignment=Qt.AlignTop) def fetch_artwork(self): time.sleep(1) logging.info('GET {}'.format(self.song['artwork'])) try: response = requests.get(self.song['artwork']) self.artwork_content = response.content except Exception: return True return True def on_artwork_loaded(self): if self.artwork_content: imgWidget = QImage() imgWidget.loadFromData(self.artwork_content) picture = QPixmap(imgWidget) picture = picture.scaled(self.artwork_size, self.artwork_size, Qt.KeepAspectRatio) self.artwork_label.setPixmap(picture) else: logging.warn('[FAILED] GET {}'.format(self.song['artwork'])) def get_song_info(self): self.loading = True spider = CoreRadioSpider() self.song = spider.get_song_info(url=self.url) return True def on_song_info(self): if self.song is not None: self.render_song_info() self.loading = False self.layout.setCurrentWidget(self.page_widget) else: self.loading_label.setText( "Something wen't wrong, please try again")
class QSettingsWindow(QDialog): def __init__(self, game: Game): super().__init__() self.game = game self.pluginsPage = None self.pluginsOptionsPage = None self.pages: dict[str, AutoSettingsPage] = {} for page in Settings.pages(): self.pages[page] = AutoSettingsPage(page, game.settings, self.applySettings) self.setModal(True) self.setWindowTitle("Settings") self.setWindowIcon(CONST.ICONS["Settings"]) self.setMinimumSize(600, 250) self.initUi() def initUi(self): self.layout = QGridLayout() self.categoryList = QListView() self.right_layout = QStackedLayout() self.categoryList.setMaximumWidth(175) self.categoryModel = QStandardItemModel(self.categoryList) self.categoryList.setIconSize(QSize(32, 32)) for name, page in self.pages.items(): page_item = QStandardItem(name) if name in CONST.ICONS: page_item.setIcon(CONST.ICONS[name]) else: page_item.setIcon(CONST.ICONS["Generator"]) page_item.setEditable(False) page_item.setSelectable(True) self.categoryModel.appendRow(page_item) self.right_layout.addWidget(page) self.initCheatLayout() cheat = QStandardItem("Cheat Menu") cheat.setIcon(CONST.ICONS["Cheat"]) cheat.setEditable(False) cheat.setSelectable(True) self.categoryModel.appendRow(cheat) self.right_layout.addWidget(self.cheatPage) self.pluginsPage = PluginsPage() plugins = QStandardItem("LUA Plugins") plugins.setIcon(CONST.ICONS["Plugins"]) plugins.setEditable(False) plugins.setSelectable(True) self.categoryModel.appendRow(plugins) self.right_layout.addWidget(self.pluginsPage) self.pluginsOptionsPage = PluginOptionsPage() pluginsOptions = QStandardItem("LUA Plugins Options") pluginsOptions.setIcon(CONST.ICONS["PluginsOptions"]) pluginsOptions.setEditable(False) pluginsOptions.setSelectable(True) self.categoryModel.appendRow(pluginsOptions) self.right_layout.addWidget(self.pluginsOptionsPage) self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows) self.categoryList.setModel(self.categoryModel) self.categoryList.selectionModel().setCurrentIndex( self.categoryList.indexAt(QPoint(1, 1)), QItemSelectionModel.Select ) self.categoryList.selectionModel().selectionChanged.connect( self.onSelectionChanged ) self.layout.addWidget(self.categoryList, 0, 0, 1, 1) self.layout.addLayout(self.right_layout, 0, 1, 5, 1) self.setLayout(self.layout) def initCheatLayout(self): self.cheatPage = QWidget() self.cheatLayout = QVBoxLayout() self.cheatPage.setLayout(self.cheatLayout) self.cheat_options = CheatSettingsBox(self.game, self.applySettings) self.cheatLayout.addWidget(self.cheat_options) self.moneyCheatBox = QGroupBox("Money Cheat") self.moneyCheatBox.setAlignment(Qt.AlignTop) self.moneyCheatBoxLayout = QGridLayout() self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout) cheats_amounts = [25, 50, 100, 200, 500, 1000, -25, -50, -100, -200] for i, amount in enumerate(cheats_amounts): if amount > 0: btn = QPushButton("Cheat +" + str(amount) + "M") btn.setProperty("style", "btn-success") else: btn = QPushButton("Cheat " + str(amount) + "M") btn.setProperty("style", "btn-danger") btn.clicked.connect(self.cheatLambda(amount)) self.moneyCheatBoxLayout.addWidget(btn, i / 2, i % 2) self.cheatLayout.addWidget(self.moneyCheatBox, stretch=1) def cheatLambda(self, amount): return lambda: self.cheatMoney(amount) def cheatMoney(self, amount): logging.info("CHEATING FOR AMOUNT : " + str(amount) + "M") self.game.blue.budget += amount GameUpdateSignal.get_instance().updateGame(self.game) def applySettings(self): self.game.settings.show_red_ato = self.cheat_options.show_red_ato self.game.settings.enable_frontline_cheats = ( self.cheat_options.show_frontline_cheat ) self.game.settings.enable_base_capture_cheat = ( self.cheat_options.show_base_capture_cheat ) self.game.compute_unculled_zones() GameUpdateSignal.get_instance().updateGame(self.game) def onSelectionChanged(self): index = self.categoryList.selectionModel().currentIndex().row() self.right_layout.setCurrentIndex(index)
class MainWidget(QWidget): def __init__(self, app): QWidget.__init__(self) log.info('Creating MainWidget') # Configurar janela e sessão requests self.setWindowTitle('Desafio Upload') self.setWindowIcon(QIcon("icon.png")) self.session = requests.Session() # Configurar telas mostradas em StackedLayout self.stackedLayout = QStackedLayout() self.login_layout = LoginWidget(self.session) self.login_layout.did_login.connect(self.go_to_main_ui) self.setFixedSize(self.login_layout.size()) self.main_layout = UploadViewWidget(self.session) self.stackedLayout.addWidget(self.login_layout) self.stackedLayout.addWidget(self.main_layout) self.setLayout(self.stackedLayout) # Inicializar variáveis relacionadas ao comportamento de system tray self.closeEvent = self.on_close self.system_tray = QSystemTrayIcon() self.system_tray.setContextMenu(QMenu('Hi!', self)) # Tray menu self.tray = QSystemTrayIcon(QIcon("icon.png"), self) self.tray_menu = QMenu(self) action_show_window = QAction("Mostrar janela principal", self) action_show_window.triggered.connect(self.on_show_main_window) self.tray_menu.addAction(action_show_window) action_exit = QAction("Fechar", self) action_exit.triggered.connect(app.exit) self.tray_menu.addAction(action_exit) self.tray.setContextMenu(self.tray_menu) self.tray.activated.connect(self.on_tray_activated) self.tray.hide() # # # # # # # # # # # # # # # # # # # # # Transição entre telas def go_to_main_ui(self, username: str): self.main_layout.label_welcome_username.setText( f'Bem-vindo, {username}.') self.stackedLayout.setCurrentIndex(1) # # # # # # # # # # # # # # # # # # # # # Interação com o system tray e visibilidade da janela principal def on_close(self, event): log.info('Moving program to tray') self.tray.show() def on_show_main_window(self): log.info('Moving program from tray to window') self.show() self.tray.hide() def on_tray_activated(self, event: QSystemTrayIcon.ActivationReason): if event == QSystemTrayIcon.ActivationReason.Trigger: self.on_show_main_window()
class SidePanel(QDockWidget): saved = Signal(dict) def __init__(self): super(SidePanel, self).__init__() # Internal variables self._coverdir = path.join("data", "images", "covers") self._id = 0 self._imagedata = "" size = [220, 16] # Width, Height (for QLineEdits/QTextEdits) # QDockWidget settings self.setAllowedAreas(Qt.RightDockWidgetArea) self.setFeatures(QDockWidget.DockWidgetClosable) self.setFixedWidth(350) self.setVisible(False) # Fonts bold = QFont() bold.setBold(True) boldUnderline = QFont() boldUnderline.setBold(True) boldUnderline.setUnderline(True) # Horizontal line hline = QFrame() hline.setFrameShape(QFrame.HLine) hline.setFrameShadow(QFrame.Sunken) """Widgets""" # Cover self.cover = QLabel() self.cover.setAlignment(Qt.AlignCenter) self.cover.setMinimumHeight(200) self.cover.setMaximumSize(self.width(), 250) # Buttons self.fetchInfoButton = QPushButton("Fetch missing info") self.fetchInfoButton.setToolTip("Try to fetch info from MobyGames") self.fetchInfoButton.clicked.connect(self._fetchInfo) self.editDetailsButton = QPushButton("Edit") self.editDetailsButton.setCheckable(True) self.editDetailsButton.clicked.connect(self._editDetails) self.saveDetailsButton = QPushButton("Save") self.saveDetailsButton.clicked.connect(self._saveInfo) self.fetchPriceButton = QPushButton("Update price data") self.fetchPriceButton.setToolTip("Try to update price data from Pricecharting") self.fetchPriceButton.clicked.connect(self._fetchPriceData) self.savePriceButton = QPushButton("Save") self.savePriceButton.clicked.connect(self._saveInfo) # Info layout widgets self.nameInfoLabel = QLabel("Name:") self.nameInfoLabel.setFont(bold) self.nameDataLabel = QLabel() self.nameDataLabel.setWordWrap(True) self.platformInfoLabel = QLabel("Platform:") self.platformInfoLabel.setFont(bold) self.platformDataLabel = QLabel() self.publisherInfoLabel = QLabel("Publisher:") self.publisherInfoLabel.setFont(bold) self.publisherDataLabel = QLabel() self.developerInfoLabel = QLabel("Developer:") self.developerInfoLabel.setFont(bold) self.developerDataLabel = QLabel() self.regionInfoLabel = QLabel("Region:") self.regionInfoLabel.setFont(bold) self.regionDataLabel = QLabel() self.codeInfoLabel = QLabel("Code:") self.codeInfoLabel.setFont(bold) self.codeDataLabel = QLabel() self.codeDataLabel.setWordWrap(True) self.itemInfoLabel = QLabel("Game:") self.itemInfoLabel.setFont(bold) self.itemDataLabel = QLabel() self.boxInfoLabel = QLabel("Box:") self.boxInfoLabel.setFont(bold) self.boxDataLabel = QLabel() self.manualInfoLabel = QLabel("Manual:") self.manualInfoLabel.setFont(bold) self.manualDataLabel = QLabel() self.genreInfoLabel = QLabel("Genre:") self.genreInfoLabel.setFont(bold) self.genreDataLabel = QLabel() self.yearInfoLabel = QLabel("Year:") self.yearInfoLabel.setFont(bold) self.yearDataLabel = QLabel() self.commentInfoLabel = QLabel("Comment:") self.commentInfoLabel.setFont(bold) self.commentDataLabel = QLabel() self.commentDataLabel.setWordWrap(True) self.platformsInfoLabel = QLabel("Available for:") self.platformsInfoLabel.setFont(bold) self.platformsDataLabel = QLabel() self.platformsDataLabel.setWordWrap(True) self.platformsDataLabel.setMaximumHeight(50) # Can get quite large otherwise # Edit layout widgets self.nameEditLabel = QLabel("Name:") self.nameEditLabel.setFont(bold) self.nameDataTE = QTextEdit() self.nameDataTE.setMaximumSize(size[0], size[1] * 2) self.platformEditLabel = QLabel("Platform:") self.platformEditLabel.setFont(bold) self.platformDataLE = QLineEdit() self.platformDataLE.setMaximumSize(size[0], size[1]) self.publisherEditLabel = QLabel("Publisher:") self.publisherEditLabel.setFont(bold) self.publisherDataLE = QLineEdit() self.publisherDataLE.setMaximumSize(size[0], size[1]) self.developerEditLabel = QLabel("Developer:") self.developerEditLabel.setFont(bold) self.developerDataLE = QLineEdit() self.developerDataLE.setMaximumSize(size[0], size[1]) self.regionEditLabel = QLabel("Region:") self.regionEditLabel.setFont(bold) self.regionDataCoB = QComboBox() self.regionDataCoB.addItems(("NTSC (JP)", "NTSC (NA)", "PAL")) self.regionDataCoB.setMinimumWidth(size[0]) # If not set it will be too small self.regionDataCoB.setMaximumSize(size[0], size[1]) self.codeEditLabel = QLabel("Code:") self.codeEditLabel.setFont(bold) self.codeDataLE = QLineEdit() self.codeDataLE.setMaximumSize(size[0], size[1]) self.itemEditLabel = QLabel("Game:") self.itemEditLabel.setFont(bold) self.itemDataCB = QCheckBox() self.itemDataCB.setChecked(False) self.boxEditLabel = QLabel("Box:") self.boxEditLabel.setFont(bold) self.boxDataCB = QCheckBox() self.boxDataCB.setChecked(False) self.manualEditLabel = QLabel("Manual:") self.manualEditLabel.setFont(bold) self.manualDataCB = QCheckBox() self.manualDataCB.setChecked(False) self.genreEditLabel = QLabel("Genre:") self.genreEditLabel.setFont(bold) self.genreDataLE = QLineEdit() self.genreDataLE.setMaximumSize(size[0], size[1]) self.yearEditLabel = QLabel("Year:") self.yearEditLabel.setFont(bold) self.yearDataLE = QLineEdit() self.yearDataLE.setMaximumSize(size[0], size[1]) self.commentEditLabel = QLabel("Comment:") self.commentEditLabel.setFont(bold) self.commentDataTE = QTextEdit() self.commentDataTE.setMaximumSize(size[0], size[1] * 2) self.platformsEditLabel = QLabel("Available for:") self.platformsEditLabel.setFont(bold) self.platformsDataTE = QTextEdit() self.platformsDataTE.setMaximumSize(size[0], size[1] * 2) # Price widgets self.paidPriceLabel = QLabel("Paid:") self.paidPriceLabel.setFont(bold) self.paidPriceDataLE = QLineEdit() self.paidPriceDataLE.setMaximumSize(60, size[1]) self.paidPriceDataLE.setAlignment(Qt.AlignRight) self.loosePriceLabel = QLabel("Loose:") self.loosePriceLabel.setFont(bold) self.loosePriceDataLabel = QLabel() self.loosePriceDataLabel.setAlignment(Qt.AlignRight) self.cibPriceLabel = QLabel("CIB:") self.cibPriceLabel.setFont(bold) self.cibPriceDataLabel = QLabel() self.cibPriceDataLabel.setAlignment(Qt.AlignRight) self.newPriceLabel = QLabel("New:") self.newPriceLabel.setFont(bold) self.newPriceDataLabel = QLabel() self.newPriceDataLabel.setAlignment(Qt.AlignRight) """Layouts""" # Cover self.coverVbox = QVBoxLayout() self.coverVbox.addWidget(self.cover, 1) self.coverVbox.addWidget(hline, 0) # Buttons self.detailsButtonHbox = QHBoxLayout() self.detailsButtonHbox.addWidget(self.fetchInfoButton, 0) self.detailsButtonHbox.addWidget(self.editDetailsButton, 0) self.detailsButtonHbox.addWidget(self.saveDetailsButton, 0) self.priceButtonHbox = QHBoxLayout() self.priceButtonHbox.addWidget(self.fetchPriceButton, 0) self.priceButtonHbox.addWidget(self.savePriceButton, 0) # Info layouts self.nameInfoHbox = QHBoxLayout() self.nameInfoHbox.addWidget(self.nameInfoLabel, 0) self.nameInfoHbox.addWidget(self.nameDataLabel, 0) self.platformInfoHbox = QHBoxLayout() self.platformInfoHbox.addWidget(self.platformInfoLabel, 0) self.platformInfoHbox.addWidget(self.platformDataLabel, 0) self.publisherInfoHbox = QHBoxLayout() self.publisherInfoHbox.addWidget(self.publisherInfoLabel, 0) self.publisherInfoHbox.addWidget(self.publisherDataLabel, 0) self.developerInfoHbox = QHBoxLayout() self.developerInfoHbox.addWidget(self.developerInfoLabel, 0) self.developerInfoHbox.addWidget(self.developerDataLabel, 0) self.regionInfoHbox = QHBoxLayout() self.regionInfoHbox.addWidget(self.regionInfoLabel, 0) self.regionInfoHbox.addWidget(self.regionDataLabel, 0) self.codeInfoHbox = QHBoxLayout() self.codeInfoHbox.addWidget(self.codeInfoLabel, 0) self.codeInfoHbox.addWidget(self.codeDataLabel, 0) self.itemInfoHbox = QHBoxLayout() self.itemInfoHbox.addWidget(self.itemInfoLabel, 0) self.itemInfoHbox.addWidget(self.itemDataLabel, 0) self.boxInfoHbox = QHBoxLayout() self.boxInfoHbox.addWidget(self.boxInfoLabel, 0) self.boxInfoHbox.addWidget(self.boxDataLabel, 0) self.manualInfoHbox = QHBoxLayout() self.manualInfoHbox.addWidget(self.manualInfoLabel, 0) self.manualInfoHbox.addWidget(self.manualDataLabel, 0) self.genreInfoHbox = QHBoxLayout() self.genreInfoHbox.addWidget(self.genreInfoLabel, 0) self.genreInfoHbox.addWidget(self.genreDataLabel, 0) self.yearInfoHbox = QHBoxLayout() self.yearInfoHbox.addWidget(self.yearInfoLabel, 0) self.yearInfoHbox.addWidget(self.yearDataLabel, 0) self.commentInfoHbox = QHBoxLayout() self.commentInfoHbox.addWidget(self.commentInfoLabel, 0) self.commentInfoHbox.addWidget(self.commentDataLabel, 0) self.platformsInfoHbox = QHBoxLayout() self.platformsInfoHbox.addWidget(self.platformsInfoLabel, 0) self.platformsInfoHbox.addWidget(self.platformsDataLabel, 0) # Edit layouts self.nameEditHbox = QHBoxLayout() self.nameEditHbox.addWidget(self.nameEditLabel, 0) self.nameEditHbox.addWidget(self.nameDataTE, 0) self.platformEditHbox = QHBoxLayout() self.platformEditHbox.addWidget(self.platformEditLabel, 0) self.platformEditHbox.addWidget(self.platformDataLE, 0) self.publisherEditHbox = QHBoxLayout() self.publisherEditHbox.addWidget(self.publisherEditLabel, 0) self.publisherEditHbox.addWidget(self.publisherDataLE, 0) self.developerEditHbox = QHBoxLayout() self.developerEditHbox.addWidget(self.developerEditLabel, 0) self.developerEditHbox.addWidget(self.developerDataLE, 0) self.regionEditHbox = QHBoxLayout() self.regionEditHbox.addWidget(self.regionEditLabel, 0) self.regionEditHbox.addWidget(self.regionDataCoB, 0) self.codeEditHbox = QHBoxLayout() self.codeEditHbox.addWidget(self.codeEditLabel, 0) self.codeEditHbox.addWidget(self.codeDataLE, 0) self.itemEditHbox = QHBoxLayout() self.itemEditHbox.addWidget(self.itemEditLabel, 0) self.itemEditHbox.addWidget(self.itemDataCB, 0) self.itemEditHbox.addSpacing(135) self.boxEditHbox = QHBoxLayout() self.boxEditHbox.addWidget(self.boxEditLabel, 0) self.boxEditHbox.addWidget(self.boxDataCB, 0) self.boxEditHbox.addSpacing(135) self.manualEditHbox = QHBoxLayout() self.manualEditHbox.addWidget(self.manualEditLabel, 0) self.manualEditHbox.addWidget(self.manualDataCB, 0) self.manualEditHbox.addSpacing(135) self.genreEditHbox = QHBoxLayout() self.genreEditHbox.addWidget(self.genreEditLabel, 0) self.genreEditHbox.addWidget(self.genreDataLE, 0) self.yearEditHbox = QHBoxLayout() self.yearEditHbox.addWidget(self.yearEditLabel, 0) self.yearEditHbox.addWidget(self.yearDataLE, 0) self.commentEditHbox = QHBoxLayout() self.commentEditHbox.addWidget(self.commentEditLabel, 0) self.commentEditHbox.addWidget(self.commentDataTE, 0) self.platformsEditHbox = QHBoxLayout() self.platformsEditHbox.addWidget(self.platformsEditLabel, 0) self.platformsEditHbox.addWidget(self.platformsDataTE, 0) # Price layouts self.paidPriceHbox = QHBoxLayout() self.paidPriceHbox.addWidget(self.paidPriceLabel, 0) self.paidPriceHbox.addWidget(self.paidPriceDataLE, 0) self.loosePriceHbox = QHBoxLayout() self.loosePriceHbox.addWidget(self.loosePriceLabel, 0) self.loosePriceHbox.addWidget(self.loosePriceDataLabel, 0) self.cibPriceHbox = QHBoxLayout() self.cibPriceHbox.addWidget(self.cibPriceLabel, 0) self.cibPriceHbox.addWidget(self.cibPriceDataLabel, 0) self.newPriceHbox = QHBoxLayout() self.newPriceHbox.addWidget(self.newPriceLabel, 0) self.newPriceHbox.addWidget(self.newPriceDataLabel, 0) # Info layout self.infoLayout = QVBoxLayout() self.infoLayout.addLayout(self.nameInfoHbox, 0) self.infoLayout.addLayout(self.platformInfoHbox, 0) self.infoLayout.addLayout(self.publisherInfoHbox, 0) self.infoLayout.addLayout(self.developerInfoHbox, 0) self.infoLayout.addLayout(self.genreInfoHbox, 0) self.infoLayout.addLayout(self.regionInfoHbox, 0) self.infoLayout.addLayout(self.yearInfoHbox, 0) self.infoLayout.addLayout(self.codeInfoHbox, 0) self.infoLayout.addLayout(self.itemInfoHbox, 0) self.infoLayout.addLayout(self.boxInfoHbox, 0) self.infoLayout.addLayout(self.manualInfoHbox, 0) self.infoLayout.addLayout(self.commentInfoHbox, 0) self.infoLayout.addLayout(self.platformsInfoHbox, 0) # Edit layout self.editLayout = QVBoxLayout() self.editLayout.addLayout(self.nameEditHbox, 0) self.editLayout.addLayout(self.platformEditHbox, 0) self.editLayout.addLayout(self.publisherEditHbox, 0) self.editLayout.addLayout(self.developerEditHbox, 0) self.editLayout.addLayout(self.genreEditHbox, 0) self.editLayout.addLayout(self.regionEditHbox, 0) self.editLayout.addLayout(self.yearEditHbox, 0) self.editLayout.addLayout(self.codeEditHbox, 0) self.editLayout.addLayout(self.itemEditHbox, 0) self.editLayout.addLayout(self.boxEditHbox, 0) self.editLayout.addLayout(self.manualEditHbox, 0) self.editLayout.addLayout(self.commentEditHbox, 0) self.editLayout.addLayout(self.platformsEditHbox, 0) # Price layout self.priceLayout = QVBoxLayout() self.priceLayout.addLayout(self.paidPriceHbox, 0) self.priceLayout.addLayout(self.loosePriceHbox, 0) self.priceLayout.addLayout(self.cibPriceHbox, 0) self.priceLayout.addLayout(self.newPriceHbox, 0) self.priceLayout.addStretch(1) self.priceLayout.addLayout(self.priceButtonHbox, 0) """Main layout""" self.infoWidget = QWidget() self.infoWidget.setLayout(self.infoLayout) self.editWidget = QWidget() self.editWidget.setLayout(self.editLayout) # Add info and edit widgets to a stacked layout so we can switch layouts when editing self.stackedLayout = QStackedLayout() self.stackedLayout.addWidget(self.infoWidget) self.stackedLayout.addWidget(self.editWidget) self.stackedLayout.setCurrentIndex(0) # Default to info layout self.detailsLayout = QVBoxLayout() self.detailsLayout.addLayout(self.coverVbox, 1) self.detailsLayout.addLayout(self.stackedLayout, 0) self.detailsLayout.addLayout(self.detailsButtonHbox, 0) self.detailsWidget = QWidget() self.detailsWidget.setLayout(self.detailsLayout) self.priceWidget = QWidget() self.priceWidget.setLayout(self.priceLayout) self.tab = QTabWidget() self.tab.addTab(self.detailsWidget, "Details") self.tab.addTab(self.priceWidget, "Price info") self.setWidget(self.tab) def _editDetails(self): if self.editDetailsButton.isChecked(): self._updateWidgetData(1) self.stackedLayout.setCurrentIndex(1) else: self._updateWidgetData(0) self.stackedLayout.setCurrentIndex(0) def _fetchInfo(self): name = self.nameDataLabel.text() platform = self.platformDataLabel.text() region = self.regionDataLabel.text() info = getMobyRelease(name, platform, region) if "image" in info.keys() and info["image"] != "": self._imagedata = requests.get(info["image"]).content pixmap = QPixmap() pixmap.loadFromData(self._imagedata) w = self.cover.width() h = self.cover.height() self.cover.setPixmap(pixmap.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation)) if self.publisherDataLabel.text() == "": self.publisherDataLabel.setText(info["publisher"]) if self.developerDataLabel.text() == "": self.developerDataLabel.setText(info["developer"]) if self.genreDataLabel.text() == "": self.genreDataLabel.setText(info["genre"]) if self.yearDataLabel.text() == "": self.yearDataLabel.setText(info["year"]) if self.codeDataLabel.text() == "": self.codeDataLabel.setText(info["code"]) if self.platformsDataLabel.text() == "": self.platformsDataLabel.setText(info["platforms"]) # Update edit widgets if we're editing: if self.editDetailsButton.isChecked(): self._updateWidgetData(1) def _fetchPriceData(self): name = self.nameDataLabel.text() platform = self.platformDataLabel.text() region = self.regionDataLabel.text() prices = getPriceData(name, platform, region) self.loosePriceDataLabel.setText(prices["loose"]) self.cibPriceDataLabel.setText(prices["cib"]) self.newPriceDataLabel.setText(prices["new"]) def _saveInfo(self): if self.editDetailsButton.isChecked(): self._updateWidgetData(0) paidPrice = str(self.paidPriceDataLE.text()).replace(",", ".") # Better use '.' as decimal denominator info = {"id": self._id, "name": self.nameDataLabel.text(), "platform": self.platformDataLabel.text(), "publisher": self.publisherDataLabel.text(), "developer": self.developerDataLabel.text(), "genre": self.genreDataLabel.text(), "region": self.regionDataLabel.text(), "year": self.yearDataLabel.text(), "code": self.codeDataLabel.text(), "item": self.itemDataLabel.text(), "box": self.boxDataLabel.text(), "manual": self.manualDataLabel.text(), "comment": self.commentDataLabel.text(), "platforms": self.platformsDataLabel.text(), "price": ",".join((paidPrice, self.loosePriceDataLabel.text(), self.cibPriceDataLabel.text(), self.newPriceDataLabel.text()))} # Save imagedata to file if self._imagedata != "" and not path.exists(path.join(self._coverdir, str(self._id) + ".jpg")): with open(path.join(self._coverdir, str(self._id) + ".jpg"), "wb") as f: f.write(self._imagedata) self.saved.emit(info) def _updateWidgetData(self, layoutIndex: int): if layoutIndex == 0: self.nameDataLabel.setText(self.nameDataTE.toPlainText()) self.platformDataLabel.setText(self.platformDataLE.text()) self.publisherDataLabel.setText(self.publisherDataLE.text()) self.developerDataLabel.setText(self.developerDataLE.text()) self.genreDataLabel.setText(self.genreDataLE.text()) self.regionDataLabel.setText(self.regionDataCoB.currentText()) self.yearDataLabel.setText(self.yearDataLE.text()) self.codeDataLabel.setText(self.codeDataLE.text()) self.itemDataLabel.setText("Yes") if self.itemDataCB.isChecked() else self.itemDataLabel.setText("No") self.boxDataLabel.setText("Yes") if self.boxDataCB.isChecked() else self.boxDataLabel.setText("No") self.manualDataLabel.setText("Yes") if self.manualDataCB.isChecked() else self.manualDataLabel.setText("No") self.commentDataLabel.setText(self.commentDataTE.toPlainText()) self.platformsDataLabel.setText(self.platformsDataTE.toPlainText()) else: self.nameDataTE.setText(self.nameDataLabel.text()) self.platformDataLE.setText(self.platformDataLabel.text()) self.publisherDataLE.setText(self.publisherDataLabel.text()) self.developerDataLE.setText(self.developerDataLabel.text()) self.genreDataLE.setText(self.genreDataLabel.text()) self.regionDataCoB.setCurrentIndex(0) if self.regionDataLabel.text == "NTSC (JP)"\ else self.regionDataCoB.setCurrentIndex(1) if self.regionDataLabel.text == "NTSC (NA)"\ else self.regionDataCoB.setCurrentIndex(2) self.yearDataLE.setText(self.yearDataLabel.text()) self.codeDataLE.setText(self.codeDataLabel.text()) self.itemDataCB.setChecked(True) if self.itemDataLabel.text() == "Yes" \ else self.itemDataCB.setChecked("False") self.boxDataCB.setChecked(True) if self.boxDataLabel.text() == "Yes" \ else self.boxDataCB.setChecked(False) self.manualDataCB.setChecked(True) if self.manualDataLabel.text() == "Yes" \ else self.manualDataCB.setChecked(False) self.commentDataTE.setText(self.commentDataLabel.text()) self.platformsDataTE.setText(self.platformsDataLabel.text()) def showDetails(self, info: dict): if not self.isVisible(): self.setVisible(True) self.tab.setCurrentIndex(0) # Show details tab initially if self.editDetailsButton.isChecked(): self.editDetailsButton.setChecked(False) self.stackedLayout.setCurrentIndex(0) # Show info layout initially self._id = info["id"] self._imagedata = "" pixmap = path.join(self._coverdir, "none.png") if path.exists(path.join(self._coverdir, str(self._id) + ".jpg")) and info["table"] == "games": pixmap = path.join(self._coverdir, str(self._id) + ".jpg") p = QPixmap(pixmap) w = self.cover.width() h = self.cover.height() self.cover.setPixmap(p.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation)) # Price data is stored in form $x,$x,$x,$x [paid, loose, cib, new] paidPrice, loosePrice, cibPrice, newPrice = info["price"].split(",") self.nameDataLabel.setText(info["name"]) self.platformDataLabel.setText(info["platform"]) self.regionDataLabel.setText(info["region"]) self.boxDataLabel.setText(info["box"]) self.manualDataLabel.setText(info["manual"]) self.yearDataLabel.setText(str(info["year"])) self.commentDataLabel.setText(info["comment"]) self.paidPriceDataLE.setText(paidPrice) self.loosePriceDataLabel.setText(loosePrice) self.cibPriceDataLabel.setText(cibPrice) self.newPriceDataLabel.setText(newPrice) if info["table"] == "games": self.publisherDataLabel.setText(info["publisher"]) self.developerDataLabel.setText(info["developer"]) self.genreInfoLabel.setText("Genre:") self.genreEditLabel.setText("Genre:") self.genreDataLabel.setText(info["genre"]) self.codeInfoLabel.setText("Code:") self.codeInfoLabel.setVisible(True) self.codeEditLabel.setText("Code") self.codeEditLabel.setVisible(True) self.codeDataLabel.setText(info["code"]) self.codeDataLabel.setVisible(True) self.codeDataLE.setVisible(True) self.itemInfoLabel.setText("Game:") self.itemEditLabel.setText("Game:") self.itemDataLabel.setText(info["game"]) self.platformsDataLabel.setText(info["platforms"]) self.platformsDataLabel.setVisible(True) self.platformsInfoLabel.setVisible(True) self.fetchInfoButton.setEnabled(True) self.fetchInfoButton.setVisible(True) self.fetchInfoButton.setToolTip("Try to fetch info from MobyGames") self.saveDetailsButton.setEnabled(True) self.saveDetailsButton.setVisible(True) elif info["table"] == "consoles": self.genreInfoLabel.setText("Country:") self.genreEditLabel.setText("Country:") self.genreDataLabel.setText(info["country"]) self.codeInfoLabel.setText("Serial Number:") self.codeInfoLabel.setVisible(True) self.codeEditLabel.setText("Serial Number:") self.codeEditLabel.setVisible(True) self.codeDataLabel.setText(info["serial number"]) self.codeDataLabel.setVisible(True) self.codeDataLE.setVisible(True) self.itemInfoLabel.setText("Console:") self.itemEditLabel.setText("Console:") self.itemDataLabel.setText(info["console"]) self.platformsInfoLabel.setVisible(False) self.platformsDataLabel.setVisible(False) self.fetchInfoButton.setEnabled(False) self.fetchInfoButton.setToolTip("Not available for Consoles tab") elif info["table"] == "accessories": self.genreInfoLabel.setText("Country:") self.genreEditLabel.setText("Country:") self.genreDataLabel.setText(info["country"]) self.itemInfoLabel.setText("Accessory:") self.itemEditLabel.setText("Accessory:") self.itemDataLabel.setText(info["accessory"]) self.codeInfoLabel.setVisible(False) self.codeEditLabel.setVisible(False) self.codeDataLabel.setVisible(False) self.codeDataLE.setVisible(False) self.platformsInfoLabel.setVisible(False) self.platformsDataLabel.setVisible(False) self.fetchInfoButton.setEnabled(False) self.fetchInfoButton.setToolTip("Not avaiable for Accessories tab") def hideDetails(self): self.setVisible(False)
class MainWindow(QMainWindow): changePage = Signal(bool) def __init__(self): super().__init__() self.setWindowTitle('Petro-Explorer v1.0') win_icon = QIcon('icons/Logo.ico') self.setWindowIcon(win_icon) self.setStyleSheet('background-color: #363f49;') self.header = Header() self.navigation = Navigation() self.p_top_bar = PetrophysicsTopBar() self.s_top_bar = StatisticsTopBar() self.p_options_1 = PetrophysicsOptions(_mode='KCarman') self.p_options_2 = PetrophysicsOptions(_mode='TCoates') self.p_options_3 = PetrophysicsOptions(_mode='Winland') self.p_options_4 = PetrophysicsOptions(_mode='RQIFZI') self.p_options_5 = PetrophysicsOptions(_mode='Lucia') self.p_options_6 = PetrophysicsOptions(_mode='DParsons') self.s_options_1 = StatisticsOptions(_mode='Regression') self.s_options_2 = StatisticsOptions(_mode='Statistics') self.s_options_3 = StatisticsOptions(_mode='Histogram') self.s_options_4 = StatisticsOptions(_mode='Boxplot') self.sp_controls = SpreadsheetControls() self.plot_controls = PlotControls() self.plot_viewer = PlotViewer() self.spreadsheet = Spreadsheet() self.status_bar = QStatusBar() self.scroll_area_1 = QScrollArea() self.scroll_area_1.setWidget(self.spreadsheet) self.scroll_area_1.setWidgetResizable(True) self.scroll_area_2 = QScrollArea() self.scroll_area_2.setWidget(self.plot_viewer) self.scroll_area_2.setWidgetResizable(True) self.bar_widget = QWidget() self.bar_widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum) self.central_widget = QWidget() self.options_widget = QWidget() self.docking_options = QDockWidget() self.docking_options.setWidget(self.options_widget) self.docking_options.setTitleBarWidget( DockWidgetRibbon(' Opções de cálculo')) self.docking_options2 = QDockWidget() self.docking_options2.setWidget(self.sp_controls) self.docking_options2.setTitleBarWidget( DockWidgetRibbon(' Controles de visualização')) self.setCentralWidget(self.central_widget) self.setStatusBar(self.status_bar) self.addToolBar(self.navigation) self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.docking_options) self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.docking_options2) self.connections() self.buildLayout() self.centralWidget().setStyleSheet('background-color: #2e3843') self.spreadsheet.setStyleSheet('background-color: white') self.status_bar.setStyleSheet('color: white') def buildLayout(self): stacked_layout_1 = QStackedLayout() # stacked_layout_1.addWidget(QWidget()) stacked_layout_1.addWidget(self.p_top_bar) stacked_layout_1.addWidget(self.s_top_bar) stacked_layout_2 = QStackedLayout() # stacked_layout_2.addWidget(QWidget()) stacked_layout_2.addWidget(self.p_options_1) stacked_layout_2.addWidget(self.p_options_2) stacked_layout_2.addWidget(self.p_options_3) stacked_layout_2.addWidget(self.p_options_4) stacked_layout_2.addWidget(self.p_options_5) stacked_layout_2.addWidget(self.p_options_6) stacked_layout_2.addWidget(self.s_options_1) stacked_layout_2.addWidget(self.s_options_2) stacked_layout_2.addWidget(self.s_options_3) stacked_layout_2.addWidget(self.s_options_4) self.stacked_layout_3 = QStackedLayout() self.stacked_layout_3.addWidget(self.scroll_area_1) self.stacked_layout_3.addWidget(self.scroll_area_2) central_widget_layout = QVBoxLayout() central_widget_layout.addWidget(self.bar_widget) central_widget_layout.addLayout(self.stacked_layout_3) self.central_widget.setLayout(central_widget_layout) self.bar_widget.setLayout(stacked_layout_1) self.options_widget.setLayout(stacked_layout_2) def connections(self): self.navigation.PetroAnalysis.connect( lambda: self.bar_widget.layout().setCurrentIndex(0)) self.navigation.StatsAnalysis.connect( lambda: self.bar_widget.layout().setCurrentIndex(1)) self.navigation.Save.connect(lambda: self.saveDialog()) self.navigation.Import.connect(lambda: self.importDialog()) self.navigation.About.connect(lambda: self.aboutDialog()) self.navigation.Help.connect(lambda: self.helpDialog()) self.navigation.header.HomePage.connect( lambda: self.changePage.emit(True)) self.navigation.ViewSheet.connect(lambda: self.displaySheet()) self.navigation.ViewPlot.connect(lambda: self.displayPltE()) self.navigation.New.connect(lambda: self.spreadsheet.addBlankSheet()) self.p_top_bar.KCarman.connect( lambda: self.options_widget.layout().setCurrentIndex(0)) self.p_top_bar.TCoates.connect( lambda: self.options_widget.layout().setCurrentIndex(1)) self.p_top_bar.Winland.connect( lambda: self.options_widget.layout().setCurrentIndex(2)) self.p_top_bar.DParsons.connect( lambda: self.options_widget.layout().setCurrentIndex(5)) self.p_top_bar.Lucia.connect( lambda: self.options_widget.layout().setCurrentIndex(4)) self.p_top_bar.RF.connect( lambda: self.options_widget.layout().setCurrentIndex(3)) self.s_top_bar.Regr.connect( lambda: self.options_widget.layout().setCurrentIndex(6)) self.s_top_bar.StatDesc.connect( lambda: self.options_widget.layout().setCurrentIndex(7)) self.s_top_bar.Boxplt.connect( lambda: self.options_widget.layout().setCurrentIndex(9)) self.s_top_bar.Hist.connect( lambda: self.options_widget.layout().setCurrentIndex(8)) self.s_options_1.run_button.clicked.connect(self.startRegr) self.s_options_2.run_button.clicked.connect(self.startStat) self.s_options_3.run_button.clicked.connect(self.startHist) self.s_options_4.run_button.clicked.connect(self.startBxpl) self.p_options_1.run.clicked.connect(self.startKCoz) self.p_options_2.run.clicked.connect(self.startTCoa) self.p_options_3.run.clicked.connect(self.startWinl) self.p_options_4.run.clicked.connect(self.startFZIR) self.p_options_5.run.clicked.connect(self.startLuci) self.p_options_6.run.clicked.connect(self.startDyks) self.sp_controls.AddColumn.connect( lambda: self.spreadsheet.addColumn()) self.sp_controls.AddRow.connect(lambda: self.spreadsheet.addRow()) self.sp_controls.DeleteRow.connect( lambda: self.spreadsheet.deleteRow()) self.sp_controls.DeleteColumn.connect( lambda: self.spreadsheet.deleteColumn()) self.plot_controls.run_button.clicked.connect(lambda: self.startPltE()) self.plot_controls.erasePlot.connect( lambda: self.plot_viewer.erasePlot()) self.plot_viewer.feedPlotControls.connect( self.plot_controls.fillFromJson) def startPltE(self): old_json = self.plot_viewer.json_data title = self.plot_controls.modify_title.text() xtype = self.plot_controls.modify_x_axis_type.currentText() ytype = self.plot_controls.modify_y_axis_type.currentText() xlabel = self.plot_controls.modify_x_axis_label.text() ylabel = self.plot_controls.modify_y_axis_label.text() if len(self.plot_controls.modify_lower_x_range.text()) > 0: lxrange = float(self.plot_controls.modify_lower_x_range.text()) else: lxrange = None if len(self.plot_controls.modify_upper_x_range.text()) > 0: uxrange = float(self.plot_controls.modify_upper_x_range.text()) else: uxrange = None if len(self.plot_controls.modify_lower_y_range.text()) > 0: lyrange = float(self.plot_controls.modify_lower_y_range.text()) else: lyrange = None if len(self.plot_controls.modify_upper_y_range.text()) > 0: uyrange = float(self.plot_controls.modify_upper_y_range.text()) else: uyrange = None if len(self.plot_controls.add_x_trace.text()) > 0 and len( self.plot_controls.add_y_trace.text()): trace_type = self.plot_controls.type_of_trace.currentText() x_trace = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.plot_controls. add_x_trace.text( ))] y_trace = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.plot_controls. add_y_trace.text( ))] trace_name = self.plot_controls.trace_name.text() else: trace_type = None x_trace = None y_trace = None trace_name = None io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.loadPltE(io_operations_handler.results)) io_operations_handler.loadParameters(f=pceManifold, _args=[ old_json, title, xtype, ytype, xlabel, ylabel, lxrange, uxrange, lyrange, uyrange, trace_type, x_trace, y_trace, trace_name ]) io_operations_handler.start() def loadPltE(self, results, typ='Regressão'): self.plot_viewer.loadPlot(results[0], results[1], _type=typ) self.displayPltE() def displayPltE(self): self.stacked_layout_3.setCurrentIndex(1) self.docking_options2.setWidget(self.plot_controls) #self.removeDockWidget(self.docking_options3) #self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.docking_options2) def loadSheet(self, df): self.spreadsheet.changeModel(data=df, header=list(df.keys())) self.displaySheet() def displaySheet(self): self.stacked_layout_3.setCurrentIndex(0) self.docking_options2.setWidget(self.sp_controls) self.status_bar.clearMessage() #self.removeDockWidget(self.docking_options2) #self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.docking_options3) def importDialog(self): func = None file_settings = QFileDialog().getOpenFileName( self, 'Importar Arquivo', filter= "Todos os arquivos (*);; Arquivo de Texto (*.txt);; Arquivo CSV (*.csv);; " "Planilha Excel (*.xlsx)") if ".txt" in file_settings[0]: func = Data.readTXT if ".csv" in file_settings[0]: func = Data.readCSV if ".xlsx" in file_settings[0]: func = Data.readExcel self.status_bar.showMessage('Importando arquivo. Aguarde.') io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.loadSheet(io_operations_handler.results)) io_operations_handler.loadParameters(f=func, _args=[ file_settings[0], ]) io_operations_handler.start() def saveDialog(self): func = None file_settings = QFileDialog().getSaveFileName( self, "Salvar Arquivo", filter="Arquivo de Texto (*.txt);; Arquivo CSV (*.csv);; " "Planilha Excel (*.xlsx)") if ".txt" in file_settings[0]: func = Data.toTXT if ".csv" in file_settings[0]: func = Data.toCSV if ".xlsx" in file_settings[0]: func = Data.toExcel io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.loadParameters( f=func, _args=[self.spreadsheet.retrieveModel(), file_settings[0]]) io_operations_handler.start() def aboutDialog(self): icon = QIcon(r'icons/sobre.png') text = "O Petro-Explorer é um software desenvolvido no Laboratório de Exploração e Produção de Petróleo (" \ "LENEP) da UENF para análises petrofísicas e estatísticas de dados de rocha. " msg = QMessageBox() msg.setWindowTitle('Sobre Petro-Explorer') msg.setWindowIcon(icon) msg.setText(text) msg.exec_() def helpDialog(self): icon = QIcon(r'icons/ajuda.png') text = r"Para utilizar o Petro-Explorer de maneira correta siga os seguintes passos:" \ "\n1 - Clique no botão Novo na barra de navegação, isto irá limpar quaisquer dados de antigas análises.\n" \ "2 - Para começar a sua análise é preciso importar os dados, assim, clique no botão Importar para escolher o seu arquivo. Atente para o fato que somente três tipos de arquivo são suportados (i.e. *.txt, *.csv, *.xlsx). Depois da sua escolha, os dados devem aparecer na planilha do software.\n" \ "3 - Se você desejar realizar uma análise petrofísica, clique no botão de Análise Petrofísica na barra de navegação. Caso queira realizar uma análise estatística, clique no botão de Análise Estatística na barra de navegação.\n" \ "4 - Selecione na barra superior à planilha, a análise que desejas realizar sobre seus dados.\n" \ "5 - No canto direito da janela, selecione os parâmetros de sua análise assim como o destino de seus resultados. Clique no botão 'Começar Análise' para continuar.\n" \ "6 - Analise seus resultados na planilha, e, quando disponível, no gráfico também.\n" \ "7 - Quando terminar, clique no botão Salvar para salvar os resultados de suas análises no disco.\n" \ "8 - Caso queira realizar outra análise, clique no botão \"Novo\" e comece novamente.\n" msg = QMessageBox() msg.setWindowTitle('Ajuda') msg.setWindowIcon(icon) msg.setText(text) msg.exec_() def startRegr(self): xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.s_options_1. payload['x_column'])] ydata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.s_options_1. payload['y_column'])] _type = self.s_options_1.payload['calculate'] dgr = self.s_options_1.degree.value() io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayRegr(self.s_options_1.payload['output_column'], io_operations_handler.results)) io_operations_handler.loadParameters(f=regressionManifold, _args=[xdata, ydata, dgr, _type]) io_operations_handler.start() def startStat(self): xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.s_options_2. payload['x_column'])] mthd = self.s_options_2.payload['calculate'] qtl = self.s_options_2.quartile.value() pctl = self.s_options_2.percentile.value() io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayStat(self.s_options_2.payload['output_column'], io_operations_handler.results)) io_operations_handler.loadParameters(f=statisticsManifold, _args=[xdata, mthd, qtl, pctl]) io_operations_handler.start() def startHist(self): xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.s_options_3. payload['x_column'])] nbins = self.s_options_3.payload['y_column'] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayHist(io_operations_handler.results)) io_operations_handler.loadParameters(f=histogramManifold, _args=[xdata, nbins]) io_operations_handler.start() def startBxpl(self): indexes = [] columns = self.s_options_4.payload['column_range'] for col in columns: indexes.append(self.spreadsheet.model.header_info.index(col)) xdata = self.spreadsheet.model.input_data[:, indexes] box_orientation = self.s_options_4.payload['y_column'] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayBxpl(io_operations_handler.results)) io_operations_handler.loadParameters(f=boxplotManifold, _args=[xdata, box_orientation]) io_operations_handler.start() def startKCoz(self): #you need to ascertain if x corresponds to Permeability, y to Porosity and z to Swir/Svgr k = None phi = None svgr = None prp = self.p_options_1.payload['calculate'] if prp == 'Permeabilidade (mD)': phi = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.p_options_1. payload['x_column'])] svgr = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_1. payload['y_column'])] elif prp == 'SVgr (cm-1)': k = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.p_options_1. payload['x_column'])] phi = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.p_options_1. payload['y_column'])] else: k = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.p_options_1. payload['x_column'])] phi = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info. index(self.p_options_1. payload['y_column'])] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayKCoz(io_operations_handler.results)) io_operations_handler.loadParameters(f=kCarmanManifold, _args=[k, phi, svgr, prp]) io_operations_handler.start() def startTCoa(self): #you need to ascertain if x corresponds to Permeability, y to Porosity and z to Swir/Svgr prp = self.p_options_2.payload['calculate'] if prp == "Swir (%)": xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_2. payload['x_column'])] ydata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_2. payload['y_column'])] zdata = None else: xdata = None ydata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_2. payload['y_column'])] zdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_2. payload['x_column'])] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayTCoa(io_operations_handler.results)) io_operations_handler.loadParameters(f=tCoatesManifold, _args=[xdata, ydata, zdata, prp]) io_operations_handler.start() def startWinl(self): #you need to ascertain if x corresponds to Permeability, y to Porosity and z to Swir/Svgr if self.p_options_3.payload['x_column'] != '': xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_3. payload['x_column'])] else: xdata = [] if self.p_options_3.payload['y_column'] != '': ydata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_3. payload['y_column'])] else: ydata = [] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayWinl(io_operations_handler.results)) io_operations_handler.loadParameters(f=winlandManifold, _args=[xdata, ydata]) io_operations_handler.start() def startFZIR(self): # you need to ascertain if x corresponds to Permeability, y to Porosity and z to Swir/Svgr if self.p_options_4.payload['x_column'] != '': xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_4. payload['x_column'])] else: xdata = None if self.p_options_4.payload['y_column'] != '': ydata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_4. payload['y_column'])] else: ydata = None if self.p_options_4.payload['z_column'] != '': zdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_4. payload['z_column'])] else: zdata = None prp = self.p_options_4.payload['calculate'] un = self.p_options_4.payload['column_range'] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayFZIR(io_operations_handler.results)) io_operations_handler.loadParameters( f=fzManifold, _args=[xdata, ydata, zdata, un, prp]) io_operations_handler.start() def startLuci(self): #you need to ascertain if x corresponds to Permeability, y to Porosity and z to Swir/Svgr if self.p_options_5.payload['x_column'] != '': xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_5. payload['x_column'])] else: xdata = [] if self.p_options_5.payload['y_column'] != '': ydata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_5. payload['y_column'])] else: ydata = [] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayLuci(io_operations_handler.results)) io_operations_handler.loadParameters(f=luciaManifold, _args=[xdata, ydata]) io_operations_handler.start() def startDyks(self): #you need to ascertain if x corresponds to Permeability, y to Porosity and z to Swir/Svgr if self.p_options_6.payload['x_column'] != '': xdata = self.spreadsheet.model.input_data[:, self.spreadsheet.model. header_info.index( self.p_options_6. payload['x_column'])] else: xdata = [] prp = self.p_options_6.payload['calculate'] io_operations_handler = HandlerThread() io_operations_handler.messageSent.connect(self.status_bar.showMessage) io_operations_handler.daemon = True io_operations_handler.hasFinished.connect( lambda: self.displayDyks(io_operations_handler.results)) io_operations_handler.loadParameters(f=dParsonsManifold, _args=[xdata, prp]) io_operations_handler.start() def displayKCoz(self, content): content = list(content) content.insert(0, 'Resultados - Kozeny-Carman') self.spreadsheet.addColumn(content) def displayWinl(self, content): self.loadPltE(content[:2]) content[2].insert(0, 'R35 - Winland') content[3].insert(0, 'Ports - Winland') self.spreadsheet.addColumn(content[2]) self.spreadsheet.addColumn(content[3]) def displayTCoa(self, content): content.insert(0, 'Resultados - Timur Coates') self.spreadsheet.addColumn(content) def displayDyks(self, content): content.insert(0, 'Resultados - Dykstra-Parsons') self.spreadsheet.addColumn(content) self.p_options_6.results.setText( 'Atenção! Resultado pode ser diferente do coeficiente calculado através do gráfico de probabilidade. \n' + str(content[0]) + ': ' + str(content[1])) def displayLuci(self, results): self.loadPltE(results[:2]) results[2].insert(0, 'Resultados - RFN/Lucia') self.spreadsheet.addColumn(results[2]) def displayFZIR(self, results): results[0].insert(0, 'Resultados - RQI (μm)') self.spreadsheet.addColumn(results[0]) results[1].insert(0, 'Resultados - PhiZ') self.spreadsheet.addColumn(results[1]) self.loadPltE(results[2:]) def displayRegr(self, display_name, results): self.s_options_1.results.setText(str(results[0])) self.loadPltE(results[-2:]) def displayStat(self, display_name, results): self.s_options_2.results.setText(str(results)) def displayHist(self, results): self.loadPltE(results, 'Histograma') def displayBxpl(self, results): self.loadPltE(results, 'Boxplot')
class Sidebar(QWidget): def __init__(self, *args, **kwargs): super(Sidebar, self).__init__(*args, **kwargs) self.settings_scroll_area = QScrollArea() self.settings_scroll_area.setWidgetResizable(True) self.navigation = ImagesNav(parent=self) self.log = QTextEdit() self.log.setReadOnly(True) self.tabs = QTabWidget() self.tabs.addTab(self.navigation, "Images list") self.tabs.addTab(self.log, "Application log") self.layout = QStackedLayout() self.layout.addWidget(self.settings_scroll_area) self.layout.addWidget(self.tabs) self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.MinimumExpanding) self.setLayout(self.layout) self.layout.setCurrentWidget(self.tabs) def log_text(self, text, color="black"): time = datetime.datetime.now().time() if color == "red": self.log.setTextColor(QColor("red")) else: self.log.setTextColor(QColor("black")) self.log.append(f"{time}:\n {text}") main_window = self.parent().parent() main_window.statusBar().showMessage(text) self.log.setTextColor(QColor("grey")) self.log.append("--------------") def init_font_settings(self, text_item): font_layout = QVBoxLayout() font_layout.setAlignment(Qt.AlignTop) font_layout.addWidget(QLabel("Family")) font_layout.addWidget(init_font_families_widget(text_item)) font_layout.addWidget(QLabel("Size")) font_layout.addLayout(init_font_size_layout(text_item)) font_layout.addWidget(QLabel("Color")) font_layout.addWidget(init_font_color_widget(text_item)) font_layout.addWidget(QLabel("Style")) font_layout.addWidget(init_font_style_widget(text_item)) font_layout.addWidget(QLabel("Weight")) font_layout.addWidget(init_font_weight_widget(text_item)) font_layout.addWidget(QLabel("Capitalization")) font_layout.addWidget(init_capitalization_widget(text_item)) font_layout.addWidget(QLabel("Stretch")) font_layout.addWidget(init_stretch_layout(text_item)) font_layout.addWidget(init_kerning_widget(text_item)) font_layout.addWidget(init_overline_widget(text_item)) font_layout.addWidget(init_strikeout_widget(text_item)) font_layout.addWidget(init_underline_widget(text_item)) font_layout.addWidget(init_letter_spacing_widget(text_item)) font_group_box = QGroupBox("Font") font_group_box.setLayout(font_layout) layout = QVBoxLayout() layout.addWidget(font_group_box) text_item_group_box = QGroupBox("Text item") text_item_layout = QVBoxLayout() text_item_layout.setAlignment(Qt.AlignTop) text_item_layout.addLayout( init_item_opacity_layout(text_item)) text_item_layout.addLayout(init_item_rotation_layout(text_item)) text_item_group_box.setLayout(text_item_layout) layout.addWidget(text_item_group_box) layout.addWidget(self.init_item_duplicate_widget(text_item)) layout.addWidget(init_item_delete_widget(text_item)) settings = QWidget() settings.setLayout(layout) self.settings_scroll_area.setWidget(settings) self.layout.setCurrentWidget(self.settings_scroll_area) def init_image_settings(self, image_item): image_layout = QVBoxLayout() image_layout.setAlignment(Qt.AlignTop) image_group_box = QGroupBox("Image") image_layout.addLayout(init_item_opacity_layout(image_item)) image_layout.addSpacing(30) image_layout.addLayout(init_item_rotation_layout(image_item)) image_layout.addSpacing(30) image_layout.addLayout(init_image_scale_layout(image_item)) image_group_box.setLayout(image_layout) layout = QVBoxLayout() layout.addWidget(image_group_box) layout.addWidget(self.init_item_duplicate_widget(image_item)) layout.addWidget(init_item_delete_widget(image_item)) settings = QWidget() settings.setLayout(layout) self.settings_scroll_area.setWidget(settings) self.layout.setCurrentWidget(self.settings_scroll_area) def duplicate_item(self, item): item_config = item.get_config() if item_config["item_type"] == "text": new_item = custom_items.CustomQGraphicsTextItem() new_item.setParent(self) else: new_item = custom_items.CustomQGraphicsPixmapItem(item_config[ "image_path"]) new_item.parent = self new_item.path = item_config["image_path"] item.scene().addItem(new_item) new_item.load_config(item_config) new_item.scene().clearSelection() new_item.setSelected(True) def init_item_duplicate_widget(self, item): button = QPushButton("Duplicate") button.clicked.connect(lambda: self.duplicate_item(item)) return button
class QSettingsWindow(QDialog): def __init__(self, game: Game): super(QSettingsWindow, self).__init__() self.game = game self.setModal(True) self.setWindowTitle("Settings") self.setWindowIcon(CONST.ICONS["Settings"]) self.setMinimumSize(600, 250) self.initUi() def initUi(self): self.layout = QGridLayout() self.categoryList = QListView() self.right_layout = QStackedLayout() self.categoryList.setMaximumWidth(175) self.categoryModel = QStandardItemModel(self.categoryList) difficulty = QStandardItem("Difficulty") difficulty.setIcon(CONST.ICONS["Missile"]) difficulty.setEditable(False) difficulty.setSelectable(True) generator = QStandardItem("Mission Generator") generator.setIcon(CONST.ICONS["Generator"]) generator.setEditable(False) generator.setSelectable(True) cheat = QStandardItem("Cheat Menu") cheat.setIcon(CONST.ICONS["Cheat"]) cheat.setEditable(False) cheat.setSelectable(True) self.categoryList.setIconSize(QSize(32, 32)) self.categoryModel.appendRow(difficulty) self.categoryModel.appendRow(generator) self.categoryModel.appendRow(cheat) self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows) self.categoryList.setModel(self.categoryModel) self.categoryList.selectionModel().setCurrentIndex(self.categoryList.indexAt(QPoint(1,1)), QItemSelectionModel.Select) self.categoryList.selectionModel().selectionChanged.connect(self.onSelectionChanged) self.initDifficultyLayout() self.initGeneratorLayout() self.initCheatLayout() self.right_layout.addWidget(self.difficultyPage) self.right_layout.addWidget(self.generatorPage) self.right_layout.addWidget(self.cheatPage) self.layout.addWidget(self.categoryList, 0, 0, 1, 1) self.layout.addLayout(self.right_layout, 0, 1, 5, 1) self.setLayout(self.layout) def init(self): pass def initDifficultyLayout(self): self.difficultyPage = QWidget() self.difficultyLayout = QGridLayout() self.difficultyLayout.setAlignment(Qt.AlignTop) self.difficultyPage.setLayout(self.difficultyLayout) self.playerCoalitionSkill = QComboBox() self.enemyCoalitionSkill = QComboBox() self.enemyAASkill = QComboBox() for skill in CONST.SKILL_OPTIONS: self.playerCoalitionSkill.addItem(skill) self.enemyCoalitionSkill.addItem(skill) self.enemyAASkill.addItem(skill) self.playerCoalitionSkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.player_skill)) self.enemyCoalitionSkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill)) self.enemyAASkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill)) self.playerCoalitionSkill.currentIndexChanged.connect(self.applySettings) self.enemyCoalitionSkill.currentIndexChanged.connect(self.applySettings) self.enemyAASkill.currentIndexChanged.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0) self.difficultyLayout.addWidget(self.playerCoalitionSkill, 0, 1, Qt.AlignRight) self.difficultyLayout.addWidget(QLabel("Enemy skill"), 1, 0) self.difficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1, Qt.AlignRight) self.difficultyLayout.addWidget(QLabel("Enemy AA and vehicles skill"), 2, 0) self.difficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight) self.difficultyLabel = QComboBox() [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS] self.difficultyLabel.setCurrentIndex(CONST.LABELS_OPTIONS.index(self.game.settings.labels)) self.difficultyLabel.currentIndexChanged.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("In Game Labels"), 3, 0) self.difficultyLayout.addWidget(self.difficultyLabel, 3, 1, Qt.AlignRight) self.noNightMission = QCheckBox() self.noNightMission.setChecked(self.game.settings.night_disabled) self.noNightMission.toggled.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("No night missions"), 4, 0) self.difficultyLayout.addWidget(self.noNightMission, 4, 1, Qt.AlignRight) self.mapVisibiitySelection = QComboBox() self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All: self.mapVisibiitySelection.setCurrentIndex(0) self.mapVisibiitySelection.addItem("Fog of War", ForcedOptions.Views.Allies) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies: self.mapVisibiitySelection.setCurrentIndex(1) self.mapVisibiitySelection.addItem("Allies Only", ForcedOptions.Views.OnlyAllies) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyAllies: self.mapVisibiitySelection.setCurrentIndex(2) self.mapVisibiitySelection.addItem("Own Aircraft Only", ForcedOptions.Views.MyAircraft) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.MyAircraft: self.mapVisibiitySelection.setCurrentIndex(3) self.mapVisibiitySelection.addItem("Map Only", ForcedOptions.Views.OnlyMap) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap: self.mapVisibiitySelection.setCurrentIndex(4) self.mapVisibiitySelection.currentIndexChanged.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("Map visibility options"), 5, 0) self.difficultyLayout.addWidget(self.mapVisibiitySelection, 5, 1, Qt.AlignRight) self.ext_views = QCheckBox() self.ext_views.setChecked(self.game.settings.external_views_allowed) self.ext_views.toggled.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("Allow external views"), 6, 0) self.difficultyLayout.addWidget(self.ext_views, 6, 1, Qt.AlignRight) def initGeneratorLayout(self): self.generatorPage = QWidget() self.generatorLayout = QVBoxLayout() self.generatorLayout.setAlignment(Qt.AlignTop) self.generatorPage.setLayout(self.generatorLayout) self.gameplay = QGroupBox("Gameplay") self.gameplayLayout = QGridLayout(); self.gameplayLayout.setAlignment(Qt.AlignTop) self.gameplay.setLayout(self.gameplayLayout) self.supercarrier = QCheckBox() self.supercarrier.setChecked(self.game.settings.supercarrier) self.supercarrier.toggled.connect(self.applySettings) self.generate_marks = QCheckBox() self.generate_marks.setChecked(self.game.settings.generate_marks) self.generate_marks.toggled.connect(self.applySettings) if not hasattr(self.game.settings, "include_jtac_if_available"): self.game.settings.include_jtac_if_available = True self.include_jtac_if_available = QCheckBox() self.include_jtac_if_available.setChecked(self.game.settings.include_jtac_if_available) self.include_jtac_if_available.toggled.connect(self.applySettings) self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0) self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight) self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"), 1, 0) self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight) self.gameplayLayout.addWidget(QLabel("Include JTAC (If available)"), 2, 0) self.gameplayLayout.addWidget(self.include_jtac_if_available, 2, 1, Qt.AlignRight) self.performance = QGroupBox("Performance") self.performanceLayout = QGridLayout() self.performanceLayout.setAlignment(Qt.AlignTop) self.performance.setLayout(self.performanceLayout) self.smoke = QCheckBox() self.smoke.setChecked(self.game.settings.perf_smoke_gen) self.smoke.toggled.connect(self.applySettings) self.red_alert = QCheckBox() self.red_alert.setChecked(self.game.settings.perf_red_alert_state) self.red_alert.toggled.connect(self.applySettings) self.arti = QCheckBox() self.arti.setChecked(self.game.settings.perf_artillery) self.arti.toggled.connect(self.applySettings) self.moving_units = QCheckBox() self.moving_units.setChecked(self.game.settings.perf_moving_units) self.moving_units.toggled.connect(self.applySettings) self.infantry = QCheckBox() self.infantry.setChecked(self.game.settings.perf_infantry) self.infantry.toggled.connect(self.applySettings) self.ai_parking_start = QCheckBox() self.ai_parking_start.setChecked(self.game.settings.perf_ai_parking_start) self.ai_parking_start.toggled.connect(self.applySettings) self.destroyed_units = QCheckBox() self.destroyed_units.setChecked(self.game.settings.perf_destroyed_units) self.destroyed_units.toggled.connect(self.applySettings) self.culling = QCheckBox() self.culling.setChecked(self.game.settings.perf_culling) self.culling.toggled.connect(self.applySettings) self.culling_distance = QSpinBox() self.culling_distance.setMinimum(50) self.culling_distance.setMaximum(10000) self.culling_distance.setValue(self.game.settings.perf_culling_distance) self.culling_distance.valueChanged.connect(self.applySettings) self.performanceLayout.addWidget(QLabel("Smoke visual effect on frontline"), 0, 0) self.performanceLayout.addWidget(self.smoke, 0, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("SAM starts in RED alert mode"), 1, 0) self.performanceLayout.addWidget(self.red_alert, 1, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Artillery strikes"), 2, 0) self.performanceLayout.addWidget(self.arti, 2, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Moving ground units"), 3, 0) self.performanceLayout.addWidget(self.moving_units, 3, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Generate infantry squads along vehicles"), 4, 0) self.performanceLayout.addWidget(self.infantry, 4, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("AI planes parking start (AI starts in flight if disabled)"), 5, 0) self.performanceLayout.addWidget(self.ai_parking_start, 5, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Include destroyed units carcass"), 6, 0) self.performanceLayout.addWidget(self.destroyed_units, 6, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1, 2) self.performanceLayout.addWidget(QLabel("Culling of distant units enabled"), 8, 0) self.performanceLayout.addWidget(self.culling, 8, 1, alignment=Qt.AlignRight) self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0) self.performanceLayout.addWidget(self.culling_distance, 9, 1, alignment=Qt.AlignRight) self.generatorLayout.addWidget(self.gameplay) self.generatorLayout.addWidget(QLabel("Disabling settings below may improve performance, but will impact the overall quality of the experience.")) self.generatorLayout.addWidget(self.performance) def initCheatLayout(self): self.cheatPage = QWidget() self.cheatLayout = QGridLayout() self.cheatPage.setLayout(self.cheatLayout) self.moneyCheatBox = QGroupBox("Money Cheat") self.moneyCheatBox.setAlignment(Qt.AlignTop) self.moneyCheatBoxLayout = QGridLayout() self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout) self.cheat25M = QPushButton("Cheat +25M") self.cheat50M = QPushButton("Cheat +50M") self.cheat100M = QPushButton("Cheat +100M") self.cheat200M = QPushButton("Cheat +200M") self.cheat500M = QPushButton("Cheat +500M") self.cheat1000M = QPushButton("Cheat +1000M") self.cheat25M.clicked.connect(lambda: self.cheatMoney(25)) self.cheat50M.clicked.connect(lambda: self.cheatMoney(50)) self.cheat100M.clicked.connect(lambda: self.cheatMoney(100)) self.cheat200M.clicked.connect(lambda: self.cheatMoney(200)) self.cheat500M.clicked.connect(lambda: self.cheatMoney(500)) self.cheat1000M.clicked.connect(lambda: self.cheatMoney(1000)) self.moneyCheatBoxLayout.addWidget(self.cheat25M, 0, 0) self.moneyCheatBoxLayout.addWidget(self.cheat50M, 0, 1) self.moneyCheatBoxLayout.addWidget(self.cheat100M, 1, 0) self.moneyCheatBoxLayout.addWidget(self.cheat200M, 1, 1) self.moneyCheatBoxLayout.addWidget(self.cheat500M, 2, 0) self.moneyCheatBoxLayout.addWidget(self.cheat1000M, 2, 1) self.cheatLayout.addWidget(self.moneyCheatBox, 0, 0) def cheatMoney(self, amount): self.game.budget += amount self.game.informations.append(Information("CHEATER", "You are a cheater and you should feel bad", self.game.turn)) GameUpdateSignal.get_instance().updateGame(self.game) def applySettings(self): self.game.settings.player_skill = CONST.SKILL_OPTIONS[self.playerCoalitionSkill.currentIndex()] self.game.settings.enemy_skill = CONST.SKILL_OPTIONS[self.enemyCoalitionSkill.currentIndex()] self.game.settings.enemy_vehicle_skill = CONST.SKILL_OPTIONS[self.enemyAASkill.currentIndex()] self.game.settings.labels = CONST.LABELS_OPTIONS[self.difficultyLabel.currentIndex()] self.game.settings.night_disabled = self.noNightMission.isChecked() self.game.settings.map_coalition_visibility = self.mapVisibiitySelection.currentData() self.game.settings.external_views_allowed = self.ext_views.isChecked() self.game.settings.generate_marks = self.generate_marks.isChecked() self.game.settings.include_jtac_if_available = self.include_jtac_if_available.isChecked() print(self.game.settings.map_coalition_visibility) self.game.settings.supercarrier = self.supercarrier.isChecked() self.game.settings.perf_red_alert_state = self.red_alert.isChecked() self.game.settings.perf_smoke_gen = self.smoke.isChecked() self.game.settings.perf_artillery = self.arti.isChecked() self.game.settings.perf_moving_units = self.moving_units.isChecked() self.game.settings.perf_infantry = self.infantry.isChecked() self.game.settings.perf_ai_parking_start = self.ai_parking_start.isChecked() self.game.settings.perf_destroyed_units = self.destroyed_units.isChecked() self.game.settings.perf_culling = self.culling.isChecked() self.game.settings.perf_culling_distance = int(self.culling_distance.value()) GameUpdateSignal.get_instance().updateGame(self.game) def onSelectionChanged(self): index = self.categoryList.selectionModel().currentIndex().row() self.right_layout.setCurrentIndex(index)
class NetworkControllerWidget(QWidget): def __init__(self): super().__init__() self.main_layout = QGridLayout() self.main_layout.setAlignment(Qt.AlignTop) self.main_layout.setSpacing(0) self.main_layout.setContentsMargins(0, 0, 0, 0) self.main_layout.addWidget(QLabel("Optimizer :"), 0, 0) self.optimizer_selector = QComboBox() self.optimizer_selector.addItems(["SGD", "RMSprop", "Adam", "Adadelta", "Adagrad", "Adamax", "Nadam", "Ftrl", "Custom"]) self.optimizer_stack = QStackedLayout() self.optimizer_stack.addWidget(SGDUI()) self.optimizer_stack.addWidget(RMSpropUI()) self.optimizer_stack.addWidget(AdamUI()) self.optimizer_stack.addWidget(AdadeltaUI()) self.optimizer_stack.addWidget(AdagradUI()) self.optimizer_stack.addWidget(AdamaxUI()) self.optimizer_stack.addWidget(NadamUI()) self.optimizer_stack.addWidget(FtrlUI()) self.loss_selector = QComboBox() self.loss_selector.addItems([ "BinaryCrossentropy", "CategoricalCrossentropy", "SparseCategoricalCrossentropy", "Poisson", "binary_crossentropy function", "categorical_crossentropy function", "sparse_categorical_crossentropy function", "poisson function", "KLDivergence", "kl_divergence function", "MeanSquaredError", "MeanAbsoluteError", "MeanAbsolutePercentageError", "MeanSquaredLogarithmicError", "CosineSimilarity", "mean_squared_error function", "mean_absolute_error function", "mean_absolute_percentage_error function", "mean_squared_logarithmic_error function", "cosine_similarity function", "Huber", "huber function", "LogCosh", "log_cosh function", "Hinge", "SquaredHinge", "CategoricalHinge", "hinge function", "squared_hinge function", "categorical_hinge function", "CUSTOM_my1"]) self.metrics_selector = CheckableComboBox() self.metrics_selector.addItems([ "Accuracy", "BinaryAccuracy", "CategoricalAccuracy", "TopKCategoricalAccuracy", "SparseTopKCategoricalAccuracy", "BinaryCrossentropy", "CategoricalCrossentropy", "SparseCategoricalCrossentropy", "KLDivergence", "Poisson", "MeanSquaredError", "RootMeanSquaredError", "MeanAbsoluteError", "MeanAbsolutePercentageError", "MeanSquaredLogarithmicError", "CosineSimilarity", "LogCoshError", "MeanIoU", "AUC", "Precision", "Hinge", "SquaredHinge", "CategoricalHinge", "Recall", "TruePositives", "TrueNegatives", "FalsePositives", "FalseNegatives", "PrecisionAtRecall", "SensitivityAtSpecificity", "SpecificityAtSensitivity", "CUSTOM_my1" ]) self.optimizer_selector.currentIndexChanged[int].connect(lambda index: self.optimizer_stack.setCurrentIndex(index)) tmp = QWidget() tmp.setLayout(self.optimizer_stack) self.run_eagerly = QComboBox() self.run_eagerly.addItems(["True", "False"]) self.main_layout.addWidget(QLabel("Loss Function:"), 0, 0) self.main_layout.addWidget(self.loss_selector, 0, 1) self.main_layout.addWidget(QLabel("Metrics:"),1, 0) self.main_layout.addWidget(self.metrics_selector, 1, 1) self.main_layout.addWidget(QLabel("run_eagerly:"), 2, 0) self.main_layout.addWidget(self.run_eagerly, 2, 1) self.main_layout.addWidget(QLabel("Optimizer:"), 3, 0) self.main_layout.addWidget(self.optimizer_selector, 3 , 1) self.main_layout.addWidget(tmp, 4, 1) self.setLayout(self.main_layout) self.set_styling() self.setMinimumWidth(50) def set_styling(self): self.setStyleSheet("background-color:aliceblue;")