class DebugBackendWindow(ConnectionBackend, Ui_DebugBackendWindow): pickups: List[PickupEntry] permanent_pickups: List[PickupEntry] _inventory: CurrentResources def __init__(self): super().__init__() self.window = QMainWindow() self.setupUi(self.window) common_qt_lib.set_default_window_icon(self.window) for status in iterate_enum(ConnectionStatus): self.current_status_combo.addItem(status.value, status) self.permanent_pickups = [] self.pickups = [] self._inventory = {} self.collect_location_combo.setVisible(False) self.setup_collect_location_combo_button = QtWidgets.QPushButton( self.window) self.setup_collect_location_combo_button.setText( "Load list of locations") self.setup_collect_location_combo_button.clicked.connect( self._setup_locations_combo) self.gridLayout.addWidget(self.setup_collect_location_combo_button, 1, 0, 1, 1) self.collect_location_button.clicked.connect(self._emit_collection) self.collect_location_button.setEnabled(False) @property def current_status(self) -> ConnectionStatus: return self.current_status_combo.currentData() async def display_message(self, message: str): self.messages_list.addItem(message) async def get_inventory(self) -> CurrentResources: return self._inventory def send_pickup(self, pickup: PickupEntry): self.pickups.append(pickup) self._update_inventory() def set_permanent_pickups(self, pickups: List[PickupEntry]): self.permanent_pickups = pickups self._update_inventory() def _update_inventory(self): inventory = collections.defaultdict(int) for pickup in itertools.chain(self.pickups, self.permanent_pickups): inventory[pickup.name] += 1 self.inventory_label.setText("<br />".join( f"{name} x{quantity}" for name, quantity in sorted(inventory.items()))) @property def name(self) -> str: return "Debug" async def update(self, dt: float): pass def show(self): self.window.show() def _emit_collection(self): self.LocationCollected.emit(self.collect_location_combo.currentData()) @asyncSlot() async def _setup_locations_combo(self): game = default_database.default_prime2_game_description() index_to_name = { node.pickup_index.index: game.world_list.area_name(area, distinguish_dark_aether=True, separator=" - ") for world, area, node in game.world_list.all_worlds_areas_nodes if isinstance(node, PickupNode) } self.collect_location_combo.clear() for index, name in sorted(index_to_name.items()): self.collect_location_combo.addItem(name, index) self.collect_location_button.setEnabled(True) self.collect_location_combo.setVisible(True) self.setup_collect_location_combo_button.deleteLater() def clear(self): self.messages_list.clear() self.permanent_pickups = [] self.pickups.clear() self._update_inventory()
c2.setValue(1000) c3 = QSlider(Qt.Horizontal) c3.setRange(0, 100) c3.setValue(100) controlLay.addRow("Point light", c1) controlLay.addRow("Spot light", c2) controlLay.addRow("Directional light", c3) # We use QWidget.createWindowContainer to host the 3D content without any indirection. view3d = Window() container = QWidget.createWindowContainer(view3d, view) container.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) container.setMinimumWidth(500) container.setMinimumHeight(500) mainLay.addWidget(controlWidg) mainLay.addWidget(container) view.setCentralWidget(mainWidg) view.show() # Communication between the QWidget UI and the 3D scene c1.valueChanged.connect(lambda val: view3d.enablePointLight(val)) c2.valueChanged.connect(lambda val: view3d.enableSpotLight(val)) c3.valueChanged.connect(lambda val: view3d.enableDirectionalLight(val)) sys.exit(app.exec_())
import sys import MainWinVerticalLayout from PySide2.QtWidgets import QApplication, QMainWindow if __name__ == '__main__': app = QApplication(sys.argv) mainWindow = QMainWindow() ui = MainWinVerticalLayout.Ui_MainWindow() # 向主窗口上添加控件 ui.setupUi(mainWindow) mainWindow.show() sys.exit(app.exec_())
self.label_2.setText("List Before Operation") self.beforeTextEdit.setPlainText(str(self.lList.output_list())) # Remove user input to list. self.lList.remove_list_item_by_value(userInput) # Print new/current list. self.currentTextEdit.setPlainText(str(self.lList.output_list())) def findUserInputFromList(self): # Get inputPlainTextEdit string userInput = self.inputPlainTextEdit.toPlainText() # Print current list. self.currentTextEdit.setPlainText(str(self.lList.output_list())) self.label_2.setText("Element current position") # Print position of item in list. self.beforeTextEdit.setPlainText( "Position: " + str(self.lList.unordered_search(userInput))) if __name__ == "__main__": # Create the Qt Application app = QApplication(sys.argv) MainWindow = QMainWindow() # Create an instance and show the form ui = mainApp(MainWindow) # show the window and start the app MainWindow.show() app.exec_()
class DebugBackendWindow(ConnectionBackend, Ui_DebugBackendWindow): pickups: List[PickupEntry] permanent_pickups: List[PickupEntry] def __init__(self): super().__init__() self.logger.setLevel(logging.DEBUG) self.window = QMainWindow() self.setupUi(self.window) common_qt_lib.set_default_window_icon(self.window) for status in enum_lib.iterate_enum(GameConnectionStatus): self.current_status_combo.addItem(status.pretty_text, status) self.permanent_pickups = [] self.pickups = [] self.collect_location_combo.setVisible(False) self.setup_collect_location_combo_button = QtWidgets.QPushButton( self.window) self.setup_collect_location_combo_button.setText( "Load list of locations") self.setup_collect_location_combo_button.clicked.connect( self._setup_locations_combo) self.gridLayout.addWidget(self.setup_collect_location_combo_button, 1, 0, 1, 1) self.collect_location_button.clicked.connect(self._emit_collection) self.collect_location_button.setEnabled(False) self._expected_patches = dol_patcher.ALL_VERSIONS_PATCHES[0] # FIXME: use PAL again self.patches = self._expected_patches self._game_memory = bytearray(24 * (2**20)) self._game_memory_initialized = False self.patches = None async def _ensure_initialized_game_memory(self): if self._game_memory_initialized: return try: self.patches = self._expected_patches world = self.game.world_list.worlds[0] await self._perform_memory_operations([ # Build String MemoryOperation( self.patches.build_string_address, write_bytes=self._expected_patches.build_string), # current CWorld MemoryOperation(self.patches.game_state_pointer, offset=4, write_bytes=world.world_asset_id.to_bytes( 4, "big")), # CPlayer VTable MemoryOperation( self.patches.cstate_manager_global + 0x14fc, offset=0, write_bytes=self.patches.cplayer_vtable.to_bytes(4, "big")), # CPlayerState MemoryOperation(self.patches.cstate_manager_global + 0x150c, write_bytes=0xA00000.to_bytes(4, "big")), ]) self._game_memory_initialized = True finally: self.patches = None def _read_memory(self, address: int, count: int): address &= ~0x80000000 return self._game_memory[address:address + count] def _read_memory_format(self, format_string: str, address: int): return struct.unpack_from(format_string, self._game_memory, address & ~0x80000000) def _write_memory(self, address: int, data: bytes): address &= ~0x80000000 self._game_memory[address:address + len(data)] = data self.logger.info(f"Wrote {data.hex()} to {hex(address)}") @property def current_status(self) -> GameConnectionStatus: return self.current_status_combo.currentData() @property def backend_choice(self): return DebugGameBackendChoice() @property def lock_identifier(self) -> Optional[str]: return None @property def name(self) -> str: return "Debug" async def update(self, dt: float): await self._ensure_initialized_game_memory() if not self._enabled: return if not await self._identify_game(): return await self._interact_with_game(dt) self._read_message_from_game() self._update_inventory_label() def _update_inventory_label(self): s = "<br />".join(f"{name} x {quantity.amount}/{quantity.capacity}" for name, quantity in self._inventory.items()) self.inventory_label.setText(s) def show(self): self.window.show() def _get_magic_address(self): multiworld_magic_item = self.game.resource_database.multiworld_magic_item magic_address = 0xA00000 + _echoes_powerup_offset( multiworld_magic_item.index) return magic_address def _read_magic(self): return self._read_memory_format(">II", self._get_magic_address()) def _write_magic(self, magic_amount, magic_capacity): self._write_memory(self._get_magic_address(), struct.pack(">II", magic_amount, magic_capacity)) @asyncSlot() async def _emit_collection(self): new_magic_value = self.collect_location_combo.currentData() + 1 magic_amount, magic_capacity = self._read_magic() magic_amount += new_magic_value magic_capacity += new_magic_value self._write_magic(magic_amount, magic_capacity) @asyncSlot() @handle_network_errors async def _setup_locations_combo(self): network_client = common_qt_lib.get_network_client() game_session = network_client.current_game_session user = network_client.current_user game = self.game index_to_name = { node.pickup_index.index: game.world_list.area_name(area) for world, area, node in game.world_list.all_worlds_areas_nodes if isinstance(node, PickupNode) } if game_session is None: names = index_to_name else: patcher_data = await network_client.session_admin_player( user.id, SessionAdminUserAction.CREATE_PATCHER_FILE, CosmeticPatches().as_json) names = { pickup["pickup_index"]: "{}: {}".format(index_to_name[pickup["pickup_index"]], pickup["hud_text"][0]) for pickup in patcher_data["pickups"] } self.collect_location_combo.clear() for index, name in sorted(names.items()): self.collect_location_combo.addItem(name, index) self.collect_location_button.setEnabled(True) self.collect_location_combo.setVisible(True) self.setup_collect_location_combo_button.deleteLater() def clear(self): self.messages_list.clear() self.permanent_pickups = [] self.pickups.clear() def _memory_operation(self, op: MemoryOperation) -> Optional[bytes]: op.validate_byte_sizes() address = op.address if op.offset is not None: address = self._read_memory_format(">I", address)[0] address += op.offset result = None if op.read_byte_count is not None: result = self._read_memory(address, op.read_byte_count) if op.write_bytes is not None: self._write_memory(address, op.write_bytes) return result async def _perform_memory_operations( self, ops: List[MemoryOperation]) -> Dict[MemoryOperation, bytes]: result = {} for op in ops: op_result = self._memory_operation(op) if op_result is not None: result[op] = op_result return result def _read_message_from_game(self): has_message_address = self.patches.cstate_manager_global + 0x2 if self._read_memory(has_message_address, 1) == b"\x00": return string_start = self.patches.string_display.message_receiver_string_ref message_bytes = self._read_memory( string_start, self.patches.string_display.max_message_size + 2) message = message_bytes[:message_bytes.find(b"\x00\x00")].decode( "utf-16_be") self.messages_list.addItem(message) self._write_memory(has_message_address, b"\x00") self._write_magic(0, len(self.permanent_pickups))
#series.append("Axel", 5) #slc = series.slices()[1] #slc.setExploded() #slc.setLabelVisible() #slc.setPen(QPen(Qt.darkGreen, 2)) #slc.setBrush(Qt.green) for s in series.slices(): s.setLabelVisible() chart = QtCharts.QChart(); chart.addSeries(series); chart.setTitle("Simple piechart example"); # chart.legend()->hide(); chartView = QtCharts.QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing); window = QMainWindow() window.setCentralWidget(chartView) window.resize(400, 300) window.show() sys.exit(app.exec_())
from PySide2.QtWidgets import QApplication, QMainWindow #from PyQt5.QtWidgets import * #from PyQt5.QtCore import * #from PyQt5.QtGui import * import sys app = QApplication(sys.argv) window = QMainWindow() window.show() # IMPORTANT!!!!! Windows are hidden by default. # Start the event loop. app.exec_()
tabs.addTab(tab1, "Tab 1") tabs.addTab(tab2, "Tab 2") tabs.addTab(tab3, "Tab 3") # Setup Graph Update def updateGraph(): if len(x) > 1000: x.remove(x[0]) if len(x) == 0: x.append(0) else: x.append(x[-1] + 1) if len(y) > 1000: y.remove(y[0]) value = controller.read_register(77, number_of_decimals=1) y.append(value) line.setData(x, y) graphUpdateTimer = QTimer() graphUpdateTimer.setInterval(50) graphUpdateTimer.timeout.connect(updateGraph) # Window Setup win = QMainWindow() win.setCentralWidget(tabs) win.resize(800, 480) win.show() sys.exit(app.exec_())
class MainWindowView(BaseQtWidget): def __init__( self, _model: MainWindowViewModel, coronal_widget: Optional[QWidget] = None, axial_widget: Optional[QWidget] = None, sagittal_widget: Optional[QWidget] = None, volume_widget: Optional[QWidget] = None, slice_widget: Optional[QWidget] = None, side_controls: Optional[QWidget] = None, ): self._model = _model self._model.register(self.update) self.win = QMainWindow() widget = QWidget() self.win.setCentralWidget(widget) main_layout = QHBoxLayout() top_views_layout = QHBoxLayout() bottom_views_layout = QHBoxLayout() views_layout = QVBoxLayout() views_layout.addLayout(top_views_layout) views_layout.addLayout(bottom_views_layout) main_layout.addLayout(views_layout) widget.setLayout(main_layout) if coronal_widget: coronal_layout = QVBoxLayout() label = QLabel('Coronal') label.setAlignment(QtCore.Qt.AlignCenter) coronal_layout.addWidget(label) coronal_layout.addWidget(coronal_widget) top_views_layout.addLayout(coronal_layout) if axial_widget: axial_layout = QVBoxLayout() label = QLabel('Axial') label.setAlignment(QtCore.Qt.AlignCenter) axial_layout.addWidget(label) axial_layout.addWidget(axial_widget) top_views_layout.addLayout(axial_layout) if sagittal_widget: sagittal_layout = QVBoxLayout() label = QLabel('Sagittal') label.setAlignment(QtCore.Qt.AlignCenter) sagittal_layout.addWidget(label) sagittal_layout.addWidget(sagittal_widget) top_views_layout.addLayout(sagittal_layout) if slice_widget: bottom_views_layout.addWidget(slice_widget) if volume_widget: bottom_views_layout.addWidget(volume_widget) if side_controls: main_layout.addWidget(side_controls) self.statusbar = self.win.statusBar() self.image_coord_label = QLabel(text="Image Coords") self.statusbar.addPermanentWidget(self.image_coord_label) self.win.show() @property def qt_widget(self) -> QWidget: return self.win def update(self, changed: str) -> None: render_funs = { 'title': self._render_title, 'footer': self._render_footer, } render_funs[changed]() def _render_title(self): self.win.setWindowTitle(self._model.title) def _render_footer(self): self.image_coord_label.setText(self._model.footer)
class Ui_Application(object): # -------------------------------------------------------------------------------------------------------------------- # def getPin(self): self.inputWindow = inputDialog() pin = self.inputWindow.getint("Enter your pin: ") self.getPin = QMainWindow() self.getPin.resize(1000, 500) self.getPin.setWindowTitle("Insert Pin") self.label = QtWidgets.QLabel(self.getPin) self.label.setText(Main.run(pin)) self.label.setStyleSheet("QLabel {font: 15pt Times New Roman}") self.label.adjustSize() self.getPin.show() # -------------------------------------------------------------------------------------------------------------------- # def instructions(self): self.readMe = QMainWindow() self.readMe.resize(1000, 500) self.readMe.setWindowTitle("Instructions") self.label = QtWidgets.QLabel(self.readMe) self.label.setWordWrap(True) self.label.setText( "For first time use:\n" "1) Ensure desired website is most recent tab prior to clicking generate password.\n" "2) Click 'Generate Password'.\n" "3) Set unique pin when prompted.\n" "4) Camera application will pop up. Look towards camera and press space to store picture of yourself, this will be used for generation and authentication.\n" "5) Your unique password for desired website will be copied to clipboard. Set this as your new password for desired website.\n\n" "For subsequent use:\n" "1) Ensure desired website is most recent tab prior to clicking generate password.\n" "2) Click 'Generate Password'\n" "3) Enter same pin as inputted during setup\n" "4) Look towards camera and password will be generated and pasted to your clipboard\n" "5) Paste password into website.") self.label.setStyleSheet("QLabel {font: 15pt Times New Roman}") self.label.adjustSize() self.readMe.show() # -------------------------------------------------------------------------------------------------------------------- # def setupUi(self, Application): Application.setObjectName("Application") Application.resize(1000, 500) # Default size self.gridLayout = QtWidgets.QGridLayout(Application) self.gridLayout.setObjectName("gridLayout") # Top Label self.label = QtWidgets.QLabel(Application) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label.setStyleSheet("QLabel {font: 20pt Times New Roman}") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) # Line for visual separation self.line = QtWidgets.QFrame(Application) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.gridLayout.addWidget(self.line, 1, 0, 1, 1) # Generate Button self.pushButton = QtWidgets.QPushButton(Application) self.pushButton.setObjectName("pushButton") self.pushButton.setStyleSheet( 'QPushButton {font: 20pt Times New Roman}') self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 1) self.pushButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # Read Me self.pushButton_2 = QtWidgets.QPushButton(Application) self.pushButton_2.setObjectName("pushButton") self.pushButton_2.setStyleSheet( 'QPushButton {font: 20pt Times New Roman}') self.gridLayout.addWidget(self.pushButton_2, 3, 0, 1, 1) self.pushButton_2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.retranslateUi(Application) QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.getPin) QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), self.instructions) QtCore.QMetaObject.connectSlotsByName(Application) # -------------------------------------------------------------------------------------------------------------------- # def retranslateUi(self, Application): Application.setWindowTitle( QtWidgets.QApplication.translate("Application", "Unique Password Generator", None, -1)) # Top Label self.label.setText( QtWidgets.QApplication.translate("Application", "Unique Password Generator", None, -1)) # Generate Button self.pushButton.setText( QtWidgets.QApplication.translate("Application", "Generate Password", None, -1)) # Instructions Button self.pushButton_2.setText( QtWidgets.QApplication.translate("Application", "Instructions", None, -1))
#inlet from PySide2.QtWidgets import QApplication, QLabel, QMainWindow, QDockWidget, QWidget global mainwindow global remove_widget_list remove_widget_list = [] app = QApplication() mainwindow = QMainWindow() mainwindow.setWindowTitle('world conqueror 2') mainwindow.show()
def showWindow(window: QtWidgets.QMainWindow) -> None: window.show() window.raise_() window.activateWindow() if not (window.isMaximized() or window.isFullScreen()): window.showNormal()
self.btnConvert.setEnabled(True) @Slot(str) def display(self, str): self.showLog.appendPlainText(str) class convThread(QtCore.QRunnable): def __init__(self, inputFile, outputFile): super(convThread, self).__init__() self.inputFile = inputFile self.outputFile = outputFile self.objConnection = ConvConnection() def run(self): conv_nc2txt(self.inputFile, self.outputFile) self.objConnection.finish.emit(self.inputFile + " finish") class ConvConnection(QtCore.QObject): finish = QtCore.Signal(str) if __name__ == '__main__': app = QApplication(sys.argv) Mainwindwo = QMainWindow() ui = Ui_Form() ui.setupUi(Mainwindwo) Mainwindwo.show() sys.exit(app.exec_())
series2 = QtCharts.QPieSeries() series2.setName("Renewables") series2.append("Wood fuels", 319663) series2.append("Hydro power", 45875) series2.append("Wind power", 1060) series3 = QtCharts.QPieSeries() series3.setName("Others") series3.append("Nuclear energy", 238789) series3.append("Import energy", 37802) series3.append("Other", 32441) donut_breakdown = DonutBreakdownChart() donut_breakdown.setAnimationOptions(QtCharts.QChart.AllAnimations) donut_breakdown.setTitle("Total consumption of energy in Finland 2010") donut_breakdown.legend().setAlignment(Qt.AlignRight) donut_breakdown.add_breakdown_series(series1, Qt.red) donut_breakdown.add_breakdown_series(series2, Qt.darkGreen) donut_breakdown.add_breakdown_series(series3, Qt.darkBlue) window = QMainWindow() chart_view = QtCharts.QChartView(donut_breakdown) chart_view.setRenderHint(QPainter.Antialiasing) window.setCentralWidget(chart_view) available_geometry = app.desktop().availableGeometry(window) size = available_geometry.height() * 0.75 window.resize(size, size * 0.8) window.show() sys.exit(app.exec_())
class Main: page = 0 current_plugin = None def __init__(self): # init config self.config = RawConfigParser() self.config.read_file(codecs.open('config.ini', encoding='utf8')) logger.info('Configuration loaded') # init database self.session = Session() # init Qt windows self.app = QApplication(sys.argv) self.window = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.window) self.update_mpc_plugin_list() self.ui.mpc_title_frame_title.setText( self.config['options']['project_name']) self.window.setWindowTitle(self.config['options']['project_name']) self.ui.mpc_btn_import.clicked.connect(self.import_plugin) self.ui.mpc_plugins_list.itemClicked.connect(self.load_plugin_by_item) self.ui.ps_btn_back.clicked.connect(self.go_to_main_screen) self.ui.ps_delete_plugin_btn.clicked.connect(self.delete_plugin) self.go_to_main_screen() self.window.show() # todo: Delete this part before first release self.garbage_test_code() sys.exit(self.app.exec_()) def update_mpc_plugin_list(self): list_ = self.ui.mpc_plugins_list list_.clear() for plugin in self.session.query(Plugin.name, Plugin.id): string = plugin.name if len(string) > int( self.config['options']['plugin_list_max_len']): string = string[:int(self.config['options'] ['plugin_list_max_len'])] + ' ...' item = QListWidgetItem(string) item.setStatusTip(str(plugin.id)) list_.addItem(item) def import_plugin(self): path = QFileDialog.getOpenFileName( dir=self.config['history']['last_open_folder'], filter='*.txt')[0] logger.debug(f'Selected path: {path}') if path: name = path.split('/')[-1] p = Plugin(name=name, path=path) self.session.add(p) self.session.commit() self.update_mpc_plugin_list() self.import_plugin_files(p) def load_plugin_by_item(self, item): layout = self.ui.ps_plugin_language_frame.layout() for i in reversed(range(layout.count())): widget = layout.takeAt(i) if hasattr(widget, 'widget') and widget.widget() is not None: if hasattr(widget.widget(), 'deleteLater'): widget.widget().deleteLater() layout.removeItem(widget) logger.debug(item) logger.debug(item.text()) logger.debug(item.statusTip()) self.current_plugin = item.statusTip() self.ui.ps_plugin_name.setText(item.text()) pls = self.session.query(Plugin_language).filter( Plugin_language.plugin_id == self.current_plugin).all() languages = self.session.query(Language).all() lw = Language_Widget() for pl in pls: w = QWidget() lw.setupUi(w) lw.label.setText(languages[pl.language_id - 1].short) lw.progressBar.setValue(pl.progression) lw.flag.setPixmap( QPixmap( f":/flag/ressources/flag_famfamfam/{languages[pl.language_id-1].icon}.png" )) layout.addWidget(w) self.ui.stackedWidget.setCurrentIndex(1) def go_to_main_screen(self): self.ui.stackedWidget.setCurrentIndex(0) def delete_plugin(self): plugin = self.session.query(Plugin).filter( Plugin.id == self.current_plugin).first() answer = QMessageBox.question(None, f"Deleting plugin {plugin.name}", "Are you sure ?") if answer == QMessageBox.StandardButton.Yes: self.session.query(Plugin).filter( Plugin.id == self.current_plugin).delete() self.update_mpc_plugin_list() self.go_to_main_screen() self.session.commit() def import_plugin_files(self, plugin): backslash = '\\' path = backslash.join(plugin.path.split('/')[:-1]) logger.debug(plugin.name) logger.debug(path) for root, dirs, files in os.walk(path): if root != path: for file in files: language = root.split(backslash)[-1] if file == plugin.name: logger.debug(f"{language}\t{file}") l_id = self.session.query(Language.id).filter( Language.short == language).first().id pl = Plugin_language(plugin_id=plugin.id, language_id=l_id, progression=0) self.session.add(pl) self.session.commit() def garbage_test_code(self): pass
darkPalette.setColor(QPalette.WindowText, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.WindowText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Base, QColor(42, 42, 42)) darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66)) darkPalette.setColor(QPalette.ToolTipBase, Qt.white) darkPalette.setColor(QPalette.ToolTipText, Qt.white) darkPalette.setColor(QPalette.Text, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35)) darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20)) darkPalette.setColor(QPalette.Button, QColor(53, 53, 53)) darkPalette.setColor(QPalette.ButtonText, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.BrightText, Qt.red) darkPalette.setColor(QPalette.Link, QColor(42, 130, 218)) darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218)) darkPalette.setColor(QPalette.Disabled, QPalette.Highlight, QColor(80, 80, 80)) darkPalette.setColor(QPalette.HighlightedText, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(127, 127, 127)) app = QApplication(sys.argv) app.setPalette(darkPalette) w = QMainWindow() # Replace with your QMainWindow instance. w.show() app.exec_()
print(self.board.findChildren(QPushButton)[action.item()]) self.board.findChildren(QPushButton)[action.item()].setText(player) self.board.x_turn = not self.board.x_turn if (game_status := self.board.check_game_status()) == 0: self.game_status.setText("It's a tie!") self.done = True return torch.tensor([1], device=self.device) elif game_status == 1: self.game_status.setText("X has won!") self.done = True return torch.tensor([-1 + (self.board.x_turn) * 3], device=self.device) elif game_status == -1: self.game_status.setText("O has won!") self.done = True return torch.tensor([2 + (self.board.x_turn) * -3], device=self.device) return torch.tensor([0], device=self.device) if __name__ == "__main__": app = QApplication(sys.argv) # Game screen game_screen = GameScreen() main_window = QMainWindow() main_window.setCentralWidget(game_screen) with open("stylesheet.qss", "r") as stylesheet: main_window.setStyleSheet(stylesheet.read()) main_window.show() sys.exit(app.exec_())
class DebugBackendWindow(ConnectionBackend, Ui_DebugBackendWindow): pickups: List[PickupEntry] permanent_pickups: List[PickupEntry] _inventory: CurrentResources def __init__(self): super().__init__() self.window = QMainWindow() self.setupUi(self.window) common_qt_lib.set_default_window_icon(self.window) for status in enum_lib.iterate_enum(ConnectionStatus): self.current_status_combo.addItem(status.pretty_text, status) self.permanent_pickups = [] self.pickups = [] self._inventory = {} self.collect_location_combo.setVisible(False) self.setup_collect_location_combo_button = QtWidgets.QPushButton( self.window) self.setup_collect_location_combo_button.setText( "Load list of locations") self.setup_collect_location_combo_button.clicked.connect( self._setup_locations_combo) self.gridLayout.addWidget(self.setup_collect_location_combo_button, 1, 0, 1, 1) self.collect_location_button.clicked.connect(self._emit_collection) self.collect_location_button.setEnabled(False) @property def current_status(self) -> ConnectionStatus: return self.current_status_combo.currentData() @property def lock_identifier(self) -> Optional[str]: return None def display_message(self, message: str): self.messages_list.addItem(message) async def get_inventory(self) -> CurrentResources: return self._inventory def send_pickup(self, pickup: PickupEntry): self.pickups.append(pickup) self._update_inventory() def set_permanent_pickups(self, pickups: List[PickupEntry]): self.permanent_pickups = pickups self._update_inventory() def _update_inventory(self): inventory = collections.defaultdict(int) for pickup in itertools.chain(self.pickups, self.permanent_pickups): inventory[pickup.name] += 1 self.inventory_label.setText("\n".join( f"{name} x{quantity}" for name, quantity in inventory.items())) @property def name(self) -> str: return "Debug" async def update(self, dt: float): pass def show(self): self.window.show() @asyncSlot() async def _emit_collection(self): await self._emit_location_collected( self.collect_location_combo.currentData()) @asyncSlot() @handle_network_errors async def _setup_locations_combo(self): network_client = common_qt_lib.get_network_client() game_session = network_client.current_game_session user = network_client.current_user game = default_database.default_prime2_game_description() index_to_name = { node.pickup_index.index: game.world_list.area_name(area) for world, area, node in game.world_list.all_worlds_areas_nodes if isinstance(node, PickupNode) } if game_session is None: names = index_to_name else: patcher_data = await network_client.session_admin_player( user.id, SessionAdminUserAction.CREATE_PATCHER_FILE, CosmeticPatches().as_json) names = { pickup["pickup_index"]: "{}: {}".format(index_to_name[pickup["pickup_index"]], pickup["hud_text"][0]) for pickup in patcher_data["pickups"] } self.collect_location_combo.clear() for index, name in sorted(names.items()): self.collect_location_combo.addItem(name, index) self.collect_location_button.setEnabled(True) self.collect_location_combo.setVisible(True) self.setup_collect_location_combo_button.deleteLater() def clear(self): self.messages_list.clear() self.permanent_pickups = [] self.pickups.clear() self._update_inventory()
janela.setWindowTitle("Primeira Janela") slider = QSlider(janela) slider.resize(100, 30) slider.move(100, 20) slider.setOrientation(Qt.Horizontal) slider.setMinimum(0) slider.setMaximum(100) label = QLabel("Valor do slider", janela) label.move(100, 90) label.resize(100, 20) resultado = QLabel("", janela) resultado.move(100, 120) label.resize(100, 20) def onButtonClicked(): resultado.setText(str(slider.value())) botao = QPushButton("Obter valor", janela) botao.move(100, 60) botao.resize(100, 20) botao.clicked.connect(onButtonClicked) janela.show() aplicacao.exec_() sys.exit()
class MainWindow(QWidget): def __init__(self): QWidget.__init__(self) self.setFixedSize(400, 200) self.setWindowTitle("Clinic") # Other windows self.window = None self.ui = None # Widgets self.menu = QMenuBar() self.file_menu = self.menu.addMenu("Plik") self.help_menu = self.menu.addMenu("Pomoc") self.button1 = QPushButton("Wybierz pacjenta") self.button1.setMinimumHeight(50) self.button2 = QPushButton("Dodaj pacjenta") self.button2.setMinimumHeight(50) # Menu self.exit_action = QAction("Wyjdź") self.help_action = QAction("Pomoc") self.about_action = QAction("O programie") self.file_menu.addAction(self.exit_action) self.help_menu.addAction(self.help_action) self.help_menu.addAction(self.about_action) # Layout self.layout = QVBoxLayout() self.layout.addWidget(self.button1) self.layout.addWidget(self.button2) self.layout.setMenuBar(self.menu) self.setLayout(self.layout) # Actions self.button1.clicked.connect(self.show_choose_patient) self.button2.clicked.connect(self.show_add_patient) self.exit_action.triggered.connect(self.close) self.help_action.triggered.connect(self.show_help_dialog) self.about_action.triggered.connect(self.show_about_dialog) @Slot() def show_choose_patient(self): self.window = QMainWindow() self.ui = Ui_ChoosePatientWindow() self.ui.setupUi(self.window) self.window.show() @Slot() def show_add_patient(self): self.window = QMainWindow() self.ui = Ui_AddPatientWindow() self.ui.setupUi(self.window) self.window.show() @Slot() def show_help_dialog(self): window = HelpDialog(parent=self) window.show() @Slot() def show_about_dialog(self): window = AboutDialog(parent=self) window.show()