def __init__( self, parent: Optional[QWidget] = None, *args: Tuple[Any, Any], **kwargs: Tuple[Any, Any], ) -> None: """ The log layout consisting of, for each command: Left: Command name Right: Command result """ super(VerticalLogLayout, self).__init__(parent=parent, *args, **kwargs) # set layout and add placeholder layouts to ensure they aren't automatically destroyed later layout = QHBoxLayout() self.__commandNames.append("Command name") self.__commandResults.append("Result") commandNamesBox = QVBoxLayout() commandResultsBox = QVBoxLayout() # add the human descriptions text to the layouts for i in range(0, len(self.__commandNames)): commandNamesBox.addWidget(QLabel(self.__commandNames[i])) commandResultsBox.addWidget(QLabel(self.__commandResults[i])) layout.addLayout(commandNamesBox) layout.addLayout(commandResultsBox) # remember to set the layout! self.setLayout(layout)
def __init__(self, parent, top): super(QWidget, self).__init__(parent) self.top = top hlayout = QHBoxLayout() self.layout = QGridLayout() hlayout.addLayout(self.layout) hlayout.setAlignment(hlayout, Qt.Alignment.AlignTop) self.setLayout(hlayout) self.row = 0 self.__addLabel__("Gateway Services") self.__addLabel__("Gateway Host Name/IP Address") self.gatewayHostName = QLineEdit(self) self.__addInput__(self.gatewayHostName) self.__addLabel__("Exercise Data Server Host Name/IP Address") self.productionEDS = QLineEdit(self) self.prodEnable = QRadioButton("Production") self.prodEnable.setChecked(True) self.prodEnable.toggled.connect(self.radioProdClicked) self.prodEnable.setStyleSheet("QRadioButton{ width: 100; }") self.__addInputAndRadio__(self.productionEDS, self.prodEnable) self.testEDS = QLineEdit(self) self.testEnable = QRadioButton("Test") self.testEnable.toggled.connect(self.radioTestClicked) self.testEnable.setStyleSheet("QRadioButton{ width: 100; }") self.__addInputAndRadio__(self.testEDS, self.testEnable) self.__addLabel__("Messaging Port") self.messagePort = QLineEdit("61616") self.__addInput__(self.messagePort)
def __init__(self, parent, top): super(QWidget, self).__init__(parent) self.top = top hlayout = QHBoxLayout() self.layout = QGridLayout() hlayout.addLayout(self.layout) hlayout.setAlignment(hlayout, Qt.Alignment.AlignTop) self.setLayout(hlayout) self.row = 0 self.__addLabel__("Federate Name") self.federateName = QLineEdit('REMOTE_WORKSTATION') self.__addInput__(self.federateName) self.__addLabel__("Message Directory Cache") self.messageDirectoryCache = QLineEdit(self) self.__addInputAndSelect__(self.messageDirectoryCache, self.top) self.__addLabel__("Map Data Cache") self.mapDataCache = QLineEdit(self) self.__addInputAndSelect__(self.mapDataCache, self.top) self.__addLabel__("Raster Map Cache") self.rasterMapCache = QLineEdit(self) self.__addInputAndSelect__(self.rasterMapCache, self.top) self.__addLabel__("Remote Control Location") self.remoteControlLocation = QLineEdit(self) self.__addInputAndSelect__(self.remoteControlLocation, self.top)
class StatsFrame(QWidget): """Calculate statistics for each turn of the players.""" label_ssheet = """QLabel { font-size: 15pt; font-weight: bold; padding-right: 5px; color: #fca018;}""" def __init__(self, parent=None, window=None): super().__init__(parent=parent) self.window = window self.hlayout = QHBoxLayout() self.setLayout(self.hlayout) self.vbox1 = QVBoxLayout() self.vbox2 = QVBoxLayout() self.cardCount = HLabels("Cards in Deck: ", "0") self.deckCount = HLabels("Number of Decks: ", "0") self.playerCount = HLabels("Number of Players: ", "0") self.breaking21 = HLabels("Breaking 21: ", " 0") self.exactly = HLabels("Exactly 21: ", " 0") self.under21 = HLabels("Under 21: ", " 0") self.probabilities = QLabel("Probabilities", parent=self) self.quantities = QLabel("Quantities", parent=self) self.vbox2.addWidget(self.quantities) self.vbox2.addLayout(self.cardCount) self.vbox2.addLayout(self.deckCount) self.vbox2.addLayout(self.playerCount) self.vbox1.addWidget(self.probabilities) self.vbox1.addLayout(self.breaking21) self.vbox1.addLayout(self.exactly) self.vbox1.addLayout(self.under21) self.hlayout.addLayout(self.vbox1) self.hlayout.addLayout(self.vbox2) self.quantities.setStyleSheet(self.label_ssheet) self.probabilities.setStyleSheet(self.label_ssheet) self.probabilities.setAlignment(Qt.AlignmentFlag(4)) self.quantities.setAlignment(Qt.AlignmentFlag(4)) self.labels = { "cards": self.cardCount, "decks": self.deckCount, "players": self.playerCount, "breaking": self.breaking21, "exactly": self.exactly, "under": self.under21, } self.window.driver.hook(self.labels)
def enterQuestionCodePageUI(self): layout = QFormLayout() self.enterQuestionCodePage.currPlayerTurnDisplay = QLabel() layout.addRow(self.enterQuestionCodePage.currPlayerTurnDisplay) enterColorLayout = QFormLayout() enterColorButtonGroup = QButtonGroup(self.enterQuestionCodePage) self.enterQuestionCodePage.yellowRadio = QRadioButton() self.enterQuestionCodePage.blueRadio = QRadioButton() self.enterQuestionCodePage.redRadio = QRadioButton() self.enterQuestionCodePage.yellowRadio.toggled.connect( self.enterColorRadioToggle) self.enterQuestionCodePage.blueRadio.toggled.connect( self.enterColorRadioToggle) self.enterQuestionCodePage.redRadio.toggled.connect( self.enterColorRadioToggle) enterColorButtonGroup.addButton(self.enterQuestionCodePage.yellowRadio) enterColorButtonGroup.addButton(self.enterQuestionCodePage.blueRadio) enterColorButtonGroup.addButton(self.enterQuestionCodePage.redRadio) enterColorLayout.addRow("Yellow", self.enterQuestionCodePage.yellowRadio) enterColorLayout.addRow("Blue", self.enterQuestionCodePage.blueRadio) enterColorLayout.addRow("Red", self.enterQuestionCodePage.redRadio) combLayout = QHBoxLayout() combLayout.addLayout(enterColorLayout) layout.addRow(combLayout) self.enterQuestionCodePage.submitQuestionCodeButton = QPushButton( "&Submit Code!") self.enterQuestionCodePage.submitQuestionCodeButton.clicked.connect( self.submitQuestionCode) layout.addRow(self.enterQuestionCodePage.submitQuestionCodeButton) self.enterQuestionCodePage.setLayout(layout)
class Window(QMainWindow): """ Main Window.""" def __init__(self, parent=None): """Initializer.""" super().__init__(parent) self.setWindowTitle("RP Contacts") self.resize(550, 250) self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.layout = QHBoxLayout() self.centralWidget.setLayout(self.layout) self.ContactsModel = ContactsModel() self.setupUI() def setupUI(self): """Setup the main window's GUI.""" # Create the table view widget self.table = QTableView() self.table.setModel(self.contactsModel.model) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.resizeColumnsToContents() # Create buttons self.addButton = QPushButton("Add...") self.addButton.clicked.connect(self.openAddDialog) self.deleteButton = QPushButton("Delete") self.deleteButton.clicked.connect(self.deleteContact) self.clearAllButton = QPushButton("Clear All") self.clearAllButton.clicked.connect(self.clearContacts) # Lay out the GUI layout = QVBoxLayout() layout.addWidget(self.addButton) layout.addWidget(self.deleteButton) layout.addStretch() layout.addWidget(self.clearAllButton) self.layout.addWidget(self.table) self.layout.addLayout(layout) def openAddDialog(self): """Open the Add Contact dialog.""" dialog = AddDialog(self) if dialog.exec() == QDialog.Accepted: self.ContactsModel.addContact(dialog.data) self.table.resizeColumnsToContents() def deleteContact(self): row = self.table.currentIndex().row() if row < 0: return messageBox = QMessageBox.warning( self, "Warning!", "Do you want to remove the selected contact?", QMessageBox.Ok | QMessageBox.Cancel, ) if messageBox == QMessageBox.Ok: self.contactsModel.deleteContact(row) def clearContacts(self): """Remove all contacts from the database.""" messageBox = QMessageBox.warning( self, "Warning!", "Do you want to remove all your contacts?" QMessageBox.Ok | QMessageBox.Cancel, )
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # region Create CartPole instance and load initial settings # Create CartPole instance self.initial_state = create_cartpole_state() self.CartPoleInstance = CartPole(initial_state=self.initial_state) # Set timescales self.CartPoleInstance.dt_simulation = dt_simulation self.CartPoleInstance.dt_controller = controller_update_interval self.CartPoleInstance.dt_save = save_interval # set other settings self.CartPoleInstance.set_controller(controller_init) self.CartPoleInstance.stop_at_90 = stop_at_90_init self.set_random_experiment_generator_init_params() # endregion # region Decide whether to save the data in "CartPole memory" or not self.save_history = save_history_init self.show_experiment_summary = show_experiment_summary_init if self.save_history or self.show_experiment_summary: self.CartPoleInstance.save_data_in_cart = True else: self.CartPoleInstance.save_data_in_cart = False # endregion # region Other variables initial values as provided in gui_default_parameters.py # Start user controlled experiment/ start random experiment/ load and replay - on start button self.simulator_mode = simulator_mode_init self.slider_on_click = slider_on_click_init # Update slider on click/update slider while hoovering over it self.speedup = speedup_init # Default simulation speed-up # endregion # region Initialize loop-timer # This timer allows to relate the simulation time to user time # And (if your computer is fast enough) run simulation # slower or faster than real-time by predefined factor (speedup) self.looper = loop_timer( dt_target=(self.CartPoleInstance.dt_simulation / self.speedup)) # endregion # region Variables controlling the state of various processes (DO NOT MODIFY) self.terminate_experiment_or_replay_thread = False # True: gives signal causing thread to terminate self.pause_experiment_or_replay_thread = False # True: gives signal causing the thread to pause self.run_set_labels_thread = True # True if gauges (labels) keep being repeatedly updated # Stop threads by setting False # Flag indicating if the "START! / STOP!" button should act as start or as stop when pressed. # Can take values "START!" or "STOP!" self.start_or_stop_action = "START!" # Flag indicating whether the pause button should pause or unpause. self.pause_or_unpause_action = "PAUSE" # Flag indicating that saving of experiment recording to csv file has finished self.experiment_or_replay_thread_terminated = False self.user_time_counter = 0 # Measures the user time # Slider instant value (which is draw in GUI) differs from value saved in CartPole instance # if the option updating slider "on-click" is enabled. self.slider_instant_value = self.CartPoleInstance.slider_value self.noise = 'OFF' self.CartPoleInstance.NoiseAdderInstance.noise_mode = self.noise # endregion # region Create GUI Layout # region - Create container for top level layout layout = QVBoxLayout() # endregion # region - Change geometry of the main window self.setGeometry(300, 300, 2500, 1000) # endregion # region - Matplotlib figures (CartPole drawing and Slider) # Draw Figure self.fig = Figure( figsize=(25, 10) ) # Regulates the size of Figure in inches, before scaling to window size. self.canvas = FigureCanvas(self.fig) self.fig.AxCart = self.canvas.figure.add_subplot(211) self.fig.AxSlider = self.canvas.figure.add_subplot(212) self.fig.AxSlider.set_ylim(0, 1) self.CartPoleInstance.draw_constant_elements(self.fig, self.fig.AxCart, self.fig.AxSlider) # Attach figure to the layout lf = QVBoxLayout() lf.addWidget(self.canvas) # endregion # region - Radio buttons selecting current controller self.rbs_controllers = [] for controller_name in self.CartPoleInstance.controller_names: self.rbs_controllers.append(QRadioButton(controller_name)) # Ensures that radio buttons are exclusive self.controllers_buttons_group = QButtonGroup() for button in self.rbs_controllers: self.controllers_buttons_group.addButton(button) lr_c = QVBoxLayout() lr_c.addStretch(1) for rb in self.rbs_controllers: rb.clicked.connect(self.RadioButtons_controller_selection) lr_c.addWidget(rb) lr_c.addStretch(1) self.rbs_controllers[self.CartPoleInstance.controller_idx].setChecked( True) # endregion # region - Create central part of the layout for figures and radio buttons and add it to the whole layout lc = QHBoxLayout() lc.addLayout(lf) lc.addLayout(lr_c) layout.addLayout(lc) # endregion # region - Gauges displaying current values of various states and parameters (time, velocity, angle,...) # First row ld = QHBoxLayout() # User time self.labTime = QLabel("User's time (s): ") self.timer = QTimer() self.timer.setInterval(100) # Tick every 1/10 of the second self.timer.timeout.connect(self.set_user_time_label) self.timer.start() ld.addWidget(self.labTime) # Speed, angle, motor power (Q) self.labSpeed = QLabel('Speed (m/s):') self.labAngle = QLabel('Angle (deg):') self.labMotor = QLabel('') self.labTargetPosition = QLabel('') ld.addWidget(self.labSpeed) ld.addWidget(self.labAngle) ld.addWidget(self.labMotor) ld.addWidget(self.labTargetPosition) layout.addLayout(ld) # Second row of labels # Simulation time, Measured (real) speed-up, slider-value ld2 = QHBoxLayout() self.labTimeSim = QLabel('Simulation Time (s):') ld2.addWidget(self.labTimeSim) self.labSpeedUp = QLabel('Speed-up (measured):') ld2.addWidget(self.labSpeedUp) self.labSliderInstant = QLabel('') ld2.addWidget(self.labSliderInstant) layout.addLayout(ld2) # endregion # region - Buttons "START!" / "STOP!", "PAUSE", "QUIT" self.bss = QPushButton("START!") self.bss.pressed.connect(self.start_stop_button) self.bp = QPushButton("PAUSE") self.bp.pressed.connect(self.pause_unpause_button) bq = QPushButton("QUIT") bq.pressed.connect(self.quit_application) lspb = QHBoxLayout() # Sub-Layout for Start/Stop and Pause Buttons lspb.addWidget(self.bss) lspb.addWidget(self.bp) # endregion # region - Sliders setting initial state and buttons for kicking the pole # Sliders setting initial position and angle lb = QVBoxLayout() # Layout for buttons lb.addLayout(lspb) lb.addWidget(bq) ip = QHBoxLayout() # Layout for initial position sliders self.initial_position_slider = QSlider( orientation=Qt.Orientation.Horizontal) self.initial_position_slider.setRange( -int(float(1000 * TrackHalfLength)), int(float(1000 * TrackHalfLength))) self.initial_position_slider.setValue(0) self.initial_position_slider.setSingleStep(1) self.initial_position_slider.valueChanged.connect( self.update_initial_position) self.initial_angle_slider = QSlider( orientation=Qt.Orientation.Horizontal) self.initial_angle_slider.setRange(-int(float(100 * np.pi)), int(float(100 * np.pi))) self.initial_angle_slider.setValue(0) self.initial_angle_slider.setSingleStep(1) self.initial_angle_slider.valueChanged.connect( self.update_initial_angle) ip.addWidget(QLabel("Initial position:")) ip.addWidget(self.initial_position_slider) ip.addWidget(QLabel("Initial angle:")) ip.addWidget(self.initial_angle_slider) ip.addStretch(0.01) # Slider setting latency self.LATENCY_SLIDER_RANGE_INT = 1000 self.latency_slider = QSlider(orientation=Qt.Orientation.Horizontal) self.latency_slider.setRange(0, self.LATENCY_SLIDER_RANGE_INT) self.latency_slider.setValue( int(self.CartPoleInstance.LatencyAdderInstance.latency * self.LATENCY_SLIDER_RANGE_INT / self.CartPoleInstance.LatencyAdderInstance.max_latency)) self.latency_slider.setSingleStep(1) self.latency_slider.valueChanged.connect(self.update_latency) ip.addWidget(QLabel("Latency:")) ip.addWidget(self.latency_slider) self.labLatency = QLabel('Latency (ms): {:.1f}'.format( self.CartPoleInstance.LatencyAdderInstance.latency * 1000)) ip.addWidget(self.labLatency) # Buttons activating noise self.rbs_noise = [] for mode_name in ['ON', 'OFF']: self.rbs_noise.append(QRadioButton(mode_name)) # Ensures that radio buttons are exclusive self.noise_buttons_group = QButtonGroup() for button in self.rbs_noise: self.noise_buttons_group.addButton(button) lr_n = QHBoxLayout() lr_n.addWidget(QLabel('Noise:')) for rb in self.rbs_noise: rb.clicked.connect(self.RadioButtons_noise_on_off) lr_n.addWidget(rb) self.rbs_noise[1].setChecked(True) ip.addStretch(0.01) ip.addLayout(lr_n) ip.addStretch(0.01) # Buttons giving kick to the pole kick_label = QLabel("Kick pole:") kick_left_button = QPushButton() kick_left_button.setText("Left") kick_left_button.adjustSize() kick_left_button.clicked.connect(self.kick_pole) kick_right_button = QPushButton() kick_right_button.setText("Right") kick_right_button.adjustSize() kick_right_button.clicked.connect(self.kick_pole) ip.addWidget(kick_label) ip.addWidget(kick_left_button) ip.addWidget(kick_right_button) lb.addLayout(ip) layout.addLayout(lb) # endregion # region - Text boxes and Combobox to provide settings concerning generation of random experiment l_generate_trace = QHBoxLayout() l_generate_trace.addWidget(QLabel('Random experiment settings:')) l_generate_trace.addWidget(QLabel('Length (s):')) self.textbox_length = QLineEdit() l_generate_trace.addWidget(self.textbox_length) l_generate_trace.addWidget(QLabel('Turning Points (m):')) self.textbox_turning_points = QLineEdit() l_generate_trace.addWidget(self.textbox_turning_points) l_generate_trace.addWidget(QLabel('Interpolation:')) self.cb_interpolation = QComboBox() self.cb_interpolation.addItems( ['0-derivative-smooth', 'linear', 'previous']) self.cb_interpolation.currentIndexChanged.connect( self.cb_interpolation_selectionchange) self.cb_interpolation.setCurrentText( self.CartPoleInstance.interpolation_type) l_generate_trace.addWidget(self.cb_interpolation) layout.addLayout(l_generate_trace) # endregion # region - Textbox to provide csv file name for saving or loading data l_text = QHBoxLayout() textbox_title = QLabel('CSV file name:') self.textbox = QLineEdit() l_text.addWidget(textbox_title) l_text.addWidget(self.textbox) layout.addLayout(l_text) # endregion # region - Make strip of layout for checkboxes l_cb = QHBoxLayout() # endregion # region - Textbox to provide the target speed-up value l_text_speedup = QHBoxLayout() tx_speedup_title = QLabel('Speed-up (target):') self.tx_speedup = QLineEdit() l_text_speedup.addWidget(tx_speedup_title) l_text_speedup.addWidget(self.tx_speedup) self.tx_speedup.setText(str(self.speedup)) l_cb.addLayout(l_text_speedup) self.wrong_speedup_msg = QMessageBox() self.wrong_speedup_msg.setWindowTitle("Speed-up value problem") self.wrong_speedup_msg.setIcon(QMessageBox.Icon.Critical) # endregion # region - Checkboxes # region -- Checkbox: Save/don't save experiment recording self.cb_save_history = QCheckBox('Save results', self) if self.save_history: self.cb_save_history.toggle() self.cb_save_history.toggled.connect(self.cb_save_history_f) l_cb.addWidget(self.cb_save_history) # endregion # region -- Checkbox: Display plots showing dynamic evolution of the system as soon as experiment terminates self.cb_show_experiment_summary = QCheckBox('Show experiment summary', self) if self.show_experiment_summary: self.cb_show_experiment_summary.toggle() self.cb_show_experiment_summary.toggled.connect( self.cb_show_experiment_summary_f) l_cb.addWidget(self.cb_show_experiment_summary) # endregion # region -- Checkbox: Block pole if it reaches +/-90 deg self.cb_stop_at_90_deg = QCheckBox('Stop-at-90-deg', self) if self.CartPoleInstance.stop_at_90: self.cb_stop_at_90_deg.toggle() self.cb_stop_at_90_deg.toggled.connect(self.cb_stop_at_90_deg_f) l_cb.addWidget(self.cb_stop_at_90_deg) # endregion # region -- Checkbox: Update slider on click/update slider while hoovering over it self.cb_slider_on_click = QCheckBox('Update slider on click', self) if self.slider_on_click: self.cb_slider_on_click.toggle() self.cb_slider_on_click.toggled.connect(self.cb_slider_on_click_f) l_cb.addWidget(self.cb_slider_on_click) # endregion # endregion # region - Radio buttons selecting simulator mode: user defined experiment, random experiment, replay # List available simulator modes - constant self.available_simulator_modes = [ 'Slider-Controlled Experiment', 'Random Experiment', 'Replay' ] self.rbs_simulator_mode = [] for mode_name in self.available_simulator_modes: self.rbs_simulator_mode.append(QRadioButton(mode_name)) # Ensures that radio buttons are exclusive self.simulator_mode_buttons_group = QButtonGroup() for button in self.rbs_simulator_mode: self.simulator_mode_buttons_group.addButton(button) lr_sm = QHBoxLayout() lr_sm.addStretch(1) lr_sm.addWidget(QLabel('Simulator mode:')) for rb in self.rbs_simulator_mode: rb.clicked.connect(self.RadioButtons_simulator_mode) lr_sm.addWidget(rb) lr_sm.addStretch(1) self.rbs_simulator_mode[self.available_simulator_modes.index( self.simulator_mode)].setChecked(True) l_cb.addStretch(1) l_cb.addLayout(lr_sm) l_cb.addStretch(1) # endregion # region - Add checkboxes to layout layout.addLayout(l_cb) # endregion # region - Create an instance of a GUI window w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.show() self.setWindowTitle('CartPole Simulator') # endregion # endregion # region Open controller-specific popup windows self.open_additional_controller_widget() # endregion # region Activate functions capturing mouse movements and clicks over the slider # This line links function capturing the mouse position on the canvas of the Figure self.canvas.mpl_connect("motion_notify_event", self.on_mouse_movement) # This line links function capturing the mouse position on the canvas of the Figure click self.canvas.mpl_connect("button_press_event", self.on_mouse_click) # endregion # region Introducing multithreading # To ensure smooth functioning of the app, # the calculations and redrawing of the figures have to be done in a different thread # than the one capturing the mouse position and running the animation self.threadpool = QThreadPool() # endregion # region Starts a thread repeatedly redrawing gauges (labels) of the GUI # It runs till the QUIT button is pressed worker_labels = Worker(self.set_labels_thread) self.threadpool.start(worker_labels) # endregion # region Start animation repeatedly redrawing changing elements of matplotlib figures (CartPole drawing and slider) # This animation runs ALWAYS when the GUI is open # The buttons of GUI only decide if new parameters are calculated or not self.anim = self.CartPoleInstance.run_animation(self.fig)
def __init__(self): super().__init__() # setup some flags self.isFetching = False self.isDownloading = False # default output path self.outputPath = f'{QDir.homePath()}/videos' # setup some window specific things self.setWindowTitle('YouTube Downloader') self.setWindowIcon(QIcon('assets/yt-icon.ico')) self.setFixedSize(705, 343) # parent layout layout = QVBoxLayout() layout.setContentsMargins(15, 15, 15, 10) self.setLayout(layout) # top bar layout topBar = QHBoxLayout() # detail section detailSec = QHBoxLayout() metaSec = QVBoxLayout() # download section downloadSec = QHBoxLayout() downloadBtn = QVBoxLayout() # output path link button self.outputBtn = QPushButton('📂 Output Path') self.outputBtn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.outputBtn.setToolTip(self.outputPath) self.outputBtn.clicked.connect(self.setOutputPath) # status bar self.statusBar = QStatusBar() # message box self.message = QMessageBox() # setting up widgets self.urlBox = QLineEdit() self.urlBox.setFocusPolicy(Qt.FocusPolicy.ClickFocus or Qt.FocusPolicy.NoFocus) self.urlBox.setPlaceholderText('🔍 Enter or paste video URL...') self.button = QPushButton('Get') self.button.setDefault(True) self.button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.button.clicked.connect(self.getDetails) # thumbnail pixmap = QPixmap('assets\placeholder.jpg') self.thumb = QLabel() self.thumb.setFixedSize(250, 141) self.thumb.setScaledContents(True) self.thumb.setPixmap(pixmap) # detail widgets self.title = QLabel('Title: ') self.author = QLabel('Author: ') self.length = QLabel('Duration: ') self.publish_date = QLabel('Published: ') # progress bar self.progress_bar = QProgressBar() # download options self.download = QComboBox() self.download.setPlaceholderText('Download Video') self.download.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.download.activated.connect(lambda: self.getContent(0)) self.download.setEnabled(False) # download audio button self.download_audio = QPushButton('Download Audio') self.download_audio.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.download_audio.clicked.connect(lambda: self.getContent(1)) self.download_audio.setEnabled(False) # add widgets and layouts topBar.addWidget(self.urlBox) topBar.addWidget(self.button) # detail section metaSec.addWidget(self.title) metaSec.addWidget(self.author) metaSec.addWidget(self.length) metaSec.addWidget(self.publish_date) detailSec.addWidget(self.thumb) detailSec.addSpacing(20) detailSec.addLayout(metaSec) # download section downloadBtn.addWidget(self.download) downloadBtn.addWidget(self.download_audio) downloadSec.addWidget(self.progress_bar) downloadSec.addSpacing(10) downloadSec.addLayout(downloadBtn) # status bar self.statusBar.setSizeGripEnabled(False) self.statusBar.addPermanentWidget(self.outputBtn) # add content to parent layout layout.addLayout(topBar) layout.addSpacing(20) layout.addLayout(detailSec) layout.addSpacing(5) layout.addLayout(downloadSec) layout.addWidget(self.statusBar) # setup a connection thread to keep checking internet connectivity self.connection = ConnectionThread() self.connection.start() # catch the connection response signal self.connection.con_response.connect(self.connection_slot)
def __init__(self): super(B23Download, self).__init__() # setup some flags self.is_fetching = False self.is_downloading = False # default output path basepath = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(basepath, "videos") self.output_path = path # setup some window specific things self.setWindowTitle("Bilibili Favorite Downloader") self.setWindowIcon(QIcon("images/icon_bilibili.ico")) self.setFixedSize(705, 343) # parent layout main_layout = QVBoxLayout() main_layout.setContentsMargins(15, 15, 15, 10) self.setLayout(main_layout) # top bar layout top_layout = QHBoxLayout() # detail section mid_main_layout = QHBoxLayout() mid_right_layout = QVBoxLayout() # download section bottom_main_layout = QHBoxLayout() bottom_right_layout = QVBoxLayout() # output path link button self.output_btn = QPushButton("📂 Output Path") self.output_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.output_btn.setToolTip(self.output_path) self.output_btn.clicked.connect(self.set_output_path) # status bar self.status_bar = QStatusBar() # message box self.message_box = QMessageBox() # setting up widgets self.url_edit = QLineEdit() self.url_edit.setPlaceholderText("🔍 Enter or paste favorite URL...") self.get_btn = QPushButton("Get") self.get_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.get_btn.clicked.connect(self.get_details) # thumbnail pixmap = QPixmap("images/placeholder.png") self.thumb = QLabel() self.thumb.setFixedSize(250, 141) self.thumb.setScaledContents(True) self.thumb.setPixmap(pixmap) # detail widgets self.title = QLabel("Title: ") self.author = QLabel("Author: ") self.length = QLabel("Videos: ") self.publish_date = QLabel("Published: ") # progress bar self.progress_bar = QProgressBar() # download options self.download_btn = QPushButton(" Download Videos ") self.download_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.download_btn.clicked.connect(self.get_content) self.download_btn.setEnabled(False) self.download_btn.setShortcut("Ctrl+Return") self.download_btn.setMinimumWidth(200) # add widgets and layouts top_layout.addWidget(self.url_edit) top_layout.addWidget(self.get_btn) # detail section mid_right_layout.addWidget(self.title) mid_right_layout.addWidget(self.author) mid_right_layout.addWidget(self.length) mid_right_layout.addWidget(self.publish_date) mid_main_layout.addWidget(self.thumb) mid_main_layout.addSpacing(20) mid_main_layout.addLayout(mid_right_layout) # download section bottom_right_layout.addWidget(self.download_btn) bottom_main_layout.addWidget(self.progress_bar) bottom_main_layout.addSpacing(10) bottom_main_layout.addLayout(bottom_right_layout) # status bar self.status_bar.setSizeGripEnabled(False) self.status_bar.addPermanentWidget(self.output_btn) # add content to parent layout main_layout.addLayout(top_layout) main_layout.addSpacing(20) main_layout.addLayout(mid_main_layout) main_layout.addSpacing(5) main_layout.addLayout(bottom_main_layout) main_layout.addWidget(self.status_bar)
class View(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Editor de Tags') self.setFixedSize(700, 480) self._central_widget = QWidget(self) self.setCentralWidget(self._central_widget) self.left_widget = QWidget(self._central_widget) self.left_widget.setGeometry(0, 80, 300, 380) self.right_widget = QWidget(self._central_widget) self.right_widget.setGeometry(305, 50, 400, 480) self.left_widget_top = QWidget(self.left_widget) self.left_widget_top.setGeometry(21, 10, 300, 50) self.left_widget_bot = QWidget(self.left_widget) self.left_widget_bot.setGeometry(0, 40, 300, 300) self._create_file_path_display() self._create_metadata_display() self._create_buttons() self._create_tool_bar() self._create_status_bar() #crear el visor de archivos y los metadatos def _create_file_path_display(self): self.file_path_display = QLineEdit(parent=self._central_widget) self.file_path_display.setGeometry(0, 0, 700, 60) self.file_path_display.setAlignment(Qt.AlignmentFlag.AlignCenter) self.file_path_display.setReadOnly(True) def _create_metadata_display(self): self.hlayout_track_bpm = QHBoxLayout() self.form_layout_track = QFormLayout() self.form_layout_bpm = QFormLayout() self.display_title = QLineEdit() self.display_title.setFixedSize(200, 20) self.display_artist = QLineEdit() self.display_artist.setFixedSize(200, 20) self.display_album = QLineEdit() self.display_album.setFixedSize(200, 20) self.display_album_artist = QLineEdit() self.display_album_artist.setFixedSize(200, 20) self.display_genre = QLineEdit() self.display_genre.setFixedSize(200, 20) self.display_track = QLineEdit() self.display_track.setFixedSize(60, 20) self.display_release_date = QLineEdit() self.display_release_date.setFixedSize(200, 20) self.display_bpm = QLineEdit() self.display_bpm.setFixedSize(60, 20) self.display_publisher = QLineEdit() self.display_publisher.setFixedSize(200, 20) self.hlayout_track_bpm.addLayout(self.form_layout_track) self.form_layout_track.addRow('Pista:', self.display_track) self.hlayout_track_bpm.addLayout(self.form_layout_bpm) self.form_layout_bpm.addRow('BPM:', self.display_bpm) self.left_widget_top.setLayout(self.hlayout_track_bpm) self.form_layout = QFormLayout() self.form_layout.addRow('Titulo:', self.display_title) self.form_layout.addRow('Artista:', self.display_artist) self.form_layout.addRow('Album:', self.display_album) self.form_layout.addRow('Album artist:', self.display_album_artist) self.form_layout.addRow('Genero:', self.display_genre) self.form_layout.addRow('Fecha:', self.display_release_date) self.form_layout.addRow('Publicacion:', self.display_publisher) self.left_widget_bot.setLayout(self.form_layout) #crear barra de tareas y botones def _create_buttons(self): self.close_button = QPushButton('Cerrar', parent=self.right_widget) self.close_button.setGeometry(220, 350, 70, 30) self.save_button = QPushButton('Guardar', parent=self.right_widget) self.save_button.setGeometry(300, 350, 70, 30) def _create_tool_bar(self): self.tools = QToolBar() self.addToolBar(self.tools) def _create_status_bar(self): status = QStatusBar() status.showMessage("Activo") self.setStatusBar(status) #crear el texto del display def set_display_text(self, file_path, title, artist, album, album_artist, genre, track, release_date, bpm, publisher): self.file_path_display.setText(file_path) self.display_title.setText(title) self.display_artist.setText(artist) self.display_album.setText(album) self.display_album_artist.setText(album_artist) self.display_genre.setText(str(genre)) self.display_track.setText(str(track)) self.display_release_date.setText(str(release_date)) self.display_bpm.setText(str(bpm)) self.display_publisher.setText(publisher) def display_text(self): return self.display_title.text(), self.display_artist.text( ), self.display_album.text(), self.display_album_artist.text( ), self.display_genre.text(), self.display_track.text( ), self.display_release_date.text(), self.display_bpm.text( ), self.display_publisher.text()
def __init__(self, parent): super(QWidget, self).__init__(parent) hlayout = QHBoxLayout() self.layout = QGridLayout() hlayout.addLayout(self.layout) hlayout.setAlignment(hlayout, Qt.Alignment.AlignTop) self.setLayout(hlayout) self.row = 0 self.__addLine__( "Python Version:", "{}.{}.{} {}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro, sys.version_info.releaselevel)) self.__addLine__("Qt Version:", PYQT_VERSION_STR) if path.isfile('/etc/system-release'): with open('/etc/system-release', 'r') as reader: dist = reader.readline() self.__addLine__("Distribution:", dist.strip()) elif path.isfile('/etc/lsb-release'): with open('/etc/lsb-release') as reader: lsb = reader.readlines() line = str(lsb[-1]) dist = line.strip().split("=")[-1].strip('"') self.__addLine__("Distribution:", dist) self.__addLine__("Operating System:", platform.uname().system) self.__addLine__("Kernel Release:", platform.uname().release) self.__addLine__( "Total Physical Memory:", "{:.1f} GiB".format(psutil.virtual_memory().total / (1024**3))) self.__addLine__( "Root Disk Space as Total/Used/Free:", "{:.1f} GiB/{:.1f} GiB/{:.1f} GiB".format( psutil.disk_usage('/').total / (1024**3), psutil.disk_usage('/').used / (1024**3), psutil.disk_usage('/').free / (1024**3))) self.__addLine__( "Swap Space as Total/Used/Free:", "{:.1f} GiB/{:.2f} GiB/{:.1f} GiB".format( psutil.swap_memory().total / (1024**3), psutil.swap_memory().used / (1024**3), psutil.swap_memory().free / (1024**3))) if hasattr(psutil, 'cpu-thermal') and callable( getattr(psutil, 'cpu-thermal')): self.__addLine__( "CPU Temperature:", "{:.1f}\xb0 C".format( psutil.sensors_temperatures()['cpu-thermal'][0].current)) elif hasattr(psutil, 'thermal-fan-est') and callable( getattr(psutil, 'thermal-fan-est')): self.__addLine__( "CPU Temperature:", "{:.1f}\xb0 C".format(psutil.sensors_temperatures() ['thermal-fan-est'][0].current))
class UIComicInfoWidget(QWidget): load_chapter_list_signa = QtCore.pyqtSignal(ChapterInfo) load_download_task_signa = QtCore.pyqtSignal(DownloadTask) def __init__(self, comic_info: ComicInfo, down_v_box_layout: QVBoxLayout): super().__init__() self.comic_info = comic_info self.down_v_box_layout = down_v_box_layout self.img_label = QLabel(self) self.img_label.setScaledContents(True) img = QImage.fromData(comic_info.cover) w, h = image_resize(comic_info.cover, width=200) self.img_label.resize(QtCore.QSize(w, h)) self.img_label.setGeometry(10, 10, w, h) self.img_label.setPixmap(QPixmap.fromImage(img)) # self.img_label.setPixmap(QtGui.QPixmap("/Users/bo/my/tmp/老夫子2/第1卷/1.jpg")) self.title = QLabel(self) self.title.setGeometry(220, 10, 100, 40) title_font = QtGui.QFont() title_font.setPointSize(16) title_font.setBold(True) title_font.setUnderline(True) self.title.setFont(title_font) self.title.setText(comic_info.title) self.title.setWordWrap(True) info_font = QtGui.QFont() info_font.setPointSize(14) # 作者 self.author = QLabel(self) self.author.setText("作者 : " + comic_info.author) self.author.setGeometry(220, 50, 150, 40) self.author.setWordWrap(True) self.author.setFont(info_font) # 状态 self.status = QLabel(self) self.status.setText("更新状态 : " + comic_info.status) self.status.setGeometry(220, 90, 150, 40) self.status.setFont(info_font) # 热度 self.heat = QLabel(self) self.heat.setText("热度 : " + str(comic_info.heat)) self.heat.setGeometry(220, 130, 150, 40) self.heat.setFont(info_font) # 类型 self.tip = QLabel(self) self.tip.setText("类型 : " + comic_info.tip) self.tip.setGeometry(220, 170, 150, 40) self.tip.setWordWrap(True) self.tip.setFont(info_font) # web self.domain = QLabel(self) self.domain.setText(f"查看原网页 : {comic_info.domain}") self.domain.setText(f'查看原网页 : <a href="{comic_info.url}">{comic_info.domain}</a>') self.domain.setGeometry(220, 210, 150, 40) self.domain.setOpenExternalLinks(True) self.domain.setFont(info_font) # 描述 self.describe = QLabel(self) self.describe.setText(" " + comic_info.describe) self.describe.setGeometry(10, 320, 350, 330) self.describe.setWordWrap(True) # 对齐方式 self.describe.setAlignment( QtCore.Qt.AlignmentFlag.AlignLeading | QtCore.Qt.AlignmentFlag.AlignLeft | QtCore.Qt.AlignmentFlag.AlignTop) # 章节列表,创建一个区域 self.searchHBoxLayout = QHBoxLayout() # self.searchHBoxLayout.addSpacing() self.searchGroupBox = QGroupBox() self.searchGroupBox.setLayout(self.searchHBoxLayout) self.searchScroll = QScrollArea(self) self.searchScroll.setGeometry(370, 10, 574, 590) self.searchScroll.setWidget(self.searchGroupBox) self.searchScroll.setWidgetResizable(True) # 全选 self.check_all = QCheckBox(self) self.check_all.setText("全选") self.check_all.setGeometry(700, 610, 100, 20) self.check_all.stateChanged.connect(self.check_all_fun) # 下载 self.down_button = QPushButton(self) self.down_button.setText("下载") self.down_button.setGeometry(780, 605, 50, 30) self.down_button.clicked.connect(self.download_button_click) self.load_chapter_list_signa.connect(self.load_chapter) self.load_download_task_signa.connect(self.download_callback) # 调用对应的service的接口,获取章节列表 constant.SERVICE.chapter(comic_info, self.load_chapter_list_signa.emit) i = 0 searchVBoxLayout: QVBoxLayout check_box_list: List[QCheckBox] = [] def check_all_fun(self): for check_box in self.check_box_list: check_box.setChecked(self.check_all.isChecked()) def download_callback(self, task: DownloadTask): widget = DownLoadTaskWidget(task) self.down_v_box_layout.addWidget(widget) def download_button_click(self): flag = False for check_box in self.check_box_list: if check_box.isChecked(): constant.SERVICE.parse_image(self.comic_info, check_box.property("chapter_info"), self.load_download_task_signa.emit) if not flag: QMessageBox.information(self, "下载通知", "正在解析选中章节", QMessageBox.StandardButton.Yes) flag = True def load_chapter(self, chapter_info: ChapterInfo): if self.i % 26 == 0: self.searchVBoxLayout = QVBoxLayout() self.searchVBoxLayout.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop) # 对齐方式,研究了3个小时 o(╥﹏╥)o self.searchHBoxLayout.addLayout(self.searchVBoxLayout) check_box = QCheckBox() self.check_box_list.append(check_box) check_box.setText(chapter_info.title) check_box.setProperty("chapter_info", chapter_info) task = constant.downloaded_task_map.get(chapter_info.url) if task and task.status == -1: check_box.setStyleSheet('color:red') check_box.setChecked(True) self.searchVBoxLayout.addWidget(check_box) self.i += 1
class CalibrateWizard(QWizard): def __init__(self, parent): super().__init__(parent) self.parent = parent self.setWizardStyle(QWizard.WizardStyle.ModernStyle) # CREATE PAGE 1, LINE EDIT, TITLES buttons_layout = [QWizard.WizardButton.NextButton] self.page1 = QWizardPage() self.page1.setTitle('Select the exercises you wish to do later') self.page1.setSubTitle( 'Below are listed all the available and selected exercises by you.' ) self.listSelection = TwoListSelection() # listSelection.addAvailableItems(["item-{}".format(i) for i in range(5)]) hLayout1 = QHBoxLayout(self.page1) hLayout1.addWidget(self.listSelection) # CREATE PAGE 2, LABEL, TITLES self.page2 = QWizardPage() self.page2.setFinalPage(True) self.setButtonLayout(buttons_layout) self.page2.setTitle('Calibrate every exercise') self.page2.setSubTitle( 'Do every exercise once, record after pressing button.') self.contentLayout = QVBoxLayout(self.page2) self.hLayout2 = QHBoxLayout() # Create progress bar, buttons self.actionsLayout = QHBoxLayout() self.finishButton = QPushButton('Ready') self.finishButton.setStyleSheet(CustomQStyles.buttonStyle) self.finishButton.setFixedSize(120, 35) self.progress = QProgressBar() self.progress.setRange(0, 1) self.actionsLayout.addWidget(self.progress) self.actionsLayout.setAlignment(self.progress, Qt.Alignment.AlignBottom) self.actionsLayout.addWidget(self.finishButton) self.actionsLayout.setAlignment(self.finishButton, Qt.Alignment.AlignBottom) self.contentLayout.addLayout(self.hLayout2) self.contentLayout.addLayout(self.actionsLayout) self.actionsLayout.setContentsMargins(15, 35, 15, 0) itemsTextList = [ str(self.listSelection.mInput.item(i).text()) for i in range(self.listSelection.mInput.count()) ] print("items:", itemsTextList) self.button(QWizard.WizardButton.NextButton).clicked.connect( self.onWizardNextButton) self.finishButton.clicked.connect(self.onWizardFinishButton) self.addPage(self.page1) self.addPage(self.page2) # Recording data self.buttons = [] self.images = [] self.labels = [] self.exerciseLayouts = [] self.recordReady = [] self.recordThread = RecordThread(self.parent.classifyExercises) # Training recorded data self.trained = False self.trainThread = TrainThread(self.parent.classifyExercises) self.trainThread.taskFinished.connect(self.onTrainFinished) # Send list to next page def onWizardNextButton(self): self.setPage(1, self.page1) self.trained = False itemsTextList = [ str(self.listSelection.mInput.item(i).text()) for i in range(self.listSelection.mInput.count()) ] # Update list if self.parent.classifyExercises is not None: self.parent.classifyExercises.UpdateExerciseList(itemsTextList) # Set elements on UI self.setMinimumWidth(len(itemsTextList) * 200) self.deleteItemsOfLayout(self.hLayout2) self.images.clear() self.labels.clear() self.buttons.clear() self.recordReady.clear() for x, i in zip(itemsTextList, range(len(itemsTextList))): self.exerciseLayouts.append(QVBoxLayout()) self.buttons.append(QPushButton('Record')) self.recordReady.append(False) image = QLabel() image.setPixmap( QPixmap(os.getcwd() + "/resources/images/" + itemsTextList[i] + ".png")) self.labels.append(QLabel(itemsTextList[i])) self.images.append(image) self.buttons[i].setFixedSize(100, 35) self.buttons[i].clicked.connect( functools.partial(self.onRecordExerciseButtonClicked, x, i)) self.buttons[i].setStyleSheet(CustomQStyles.outlineButtonStyle) self.exerciseLayouts[i].addWidget(self.labels[i]) self.exerciseLayouts[i].addWidget(self.images[i]) self.exerciseLayouts[i].addWidget(self.buttons[i]) self.exerciseLayouts[i].setAlignment(self.labels[i], Qt.Alignment.AlignCenter) self.exerciseLayouts[i].setAlignment(self.images[i], Qt.Alignment.AlignCenter) self.exerciseLayouts[i].setAlignment(self.buttons[i], Qt.Alignment.AlignCenter) self.hLayout2.addLayout(self.exerciseLayouts[i]) def onRecordExerciseButtonClicked(self, exercise, ind): print("Recording - ", exercise) if self.parent.classifyExercises is not None: self.recordThread.exercise = exercise self.recordThread.taskFinished.connect( functools.partial(self.recordFinished, exercise, ind), Qt.ConnectionType.SingleShotConnection) self.recordThread.start() self.recordReady[ind] = False self.buttons[ind].setStyleSheet(CustomQStyles.recordButtonStyle) self.images[ind].setPixmap( QPixmap(os.getcwd() + "/resources/images/" + exercise + ".png")) def recordFinished(self, exercise, index): imagePath = os.getcwd() + "/resources/images/" + exercise + ".png" if self.recordThread.result == 0: imagePath = os.getcwd( ) + "/resources/images/" + exercise + "-fail.png" elif self.recordThread.result == 1: imagePath = os.getcwd( ) + "/resources/images/" + exercise + "-success.png" self.recordReady[index] = True else: print("None.") self.images[index].setPixmap(QPixmap(imagePath)) self.buttons[index].setStyleSheet(CustomQStyles.outlineButtonStyle) print(self.recordReady) def onWizardFinishButton(self): if all(x == True for x in self.recordReady): print("All recorded!") if not self.trained: if self.parent.classifyExercises is not None: self.progress.setRange(0, 0) # indefinite progress bar self.parent.classifyExercises.SaveProcessedData() self.parent.classifyExercises.SavePatientData() self.parent.ui.loadPatientList() self.trainThread.start() else: self.close() else: print("Not all recorded!") def onTrainFinished(self): self.progress.setRange(0, 1) self.progress.setValue(1) self.trained = True CustomMessage.showDialog("Message", "Training model finished!", QMessageBox.StandardButtons.Ok) self.finishButton.setText('Finish') def deleteItemsOfLayout(self, layout): if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget.setParent(None) else: self.deleteItemsOfLayout(item.layout())
def questionBankPageUI(self): layout = QFormLayout() subLayout = QHBoxLayout() self.questionBankPage.questionList = QListWidget() self.questionBankPage.questionList.currentRowChanged.connect( self.displayQuestionOnQuestionBankPage) self.questionBankPage.questionTextDisplay = QLabel() self.questionBankPage.questionTextDisplay.setFixedSize(500, 100) self.questionBankPage.questionAnswersList = QListWidget() self.questionBankPage.definedCorrectAnswerDisplay = QLabel() self.questionBankPage.definedCorrectAnswerDisplay.setFixedSize(50, 10) self.questionBankPage.questionCodeParserDisplay = QLabel() self.questionBankPage.questionCodeParserDisplay.setFixedSize(100, 50) subLayout.addWidget(self.questionBankPage.questionList) subLayout.addWidget(self.questionBankPage.questionTextDisplay) subLayout.addWidget(self.questionBankPage.questionAnswersList) subLayout.addWidget(self.questionBankPage.definedCorrectAnswerDisplay) subLayout.addWidget(self.questionBankPage.questionCodeParserDisplay) layout.addRow(subLayout) self.questionBankPage.newQuestionTitle = QLineEdit() self.questionBankPage.newQuestionContent = QPlainTextEdit() layout.addRow(self.questionBankPage.newQuestionTitle, self.questionBankPage.newQuestionContent) self.questionBankPage.newQuestionAnswerInput = QLineEdit() self.questionBankPage.newQuestionAnswerList = QListWidget() layout.addRow(self.questionBankPage.newQuestionAnswerInput, self.questionBankPage.newQuestionAnswerList) colorLayout = QFormLayout() colorButtonGroup = QButtonGroup(self.questionBankPage) self.questionBankPage.yellowRadio = QRadioButton() self.questionBankPage.blueRadio = QRadioButton() self.questionBankPage.redRadio = QRadioButton() self.questionBankPage.yellowRadio.toggled.connect( self.colorRadioToggle) self.questionBankPage.blueRadio.toggled.connect(self.colorRadioToggle) self.questionBankPage.redRadio.toggled.connect(self.colorRadioToggle) colorButtonGroup.addButton(self.questionBankPage.yellowRadio) colorButtonGroup.addButton(self.questionBankPage.blueRadio) colorButtonGroup.addButton(self.questionBankPage.redRadio) colorLayout.addRow("Yellow", self.questionBankPage.yellowRadio) colorLayout.addRow("Blue", self.questionBankPage.blueRadio) colorLayout.addRow("Red", self.questionBankPage.redRadio) combLayout = QHBoxLayout() combLayout.addLayout(colorLayout) layout.addRow(combLayout) self.questionBankPage.definedNewCorrectAnswerDisplay = QLabel() layout.addRow(self.questionBankPage.definedNewCorrectAnswerDisplay) self.questionBankPage.defineCorrectAnswerButton = QPushButton( "&Define Correct Answer") self.questionBankPage.defineCorrectAnswerButton.clicked.connect( self.defineCorrectAnswer) self.questionBankPage.submitNewAnswerButton = QPushButton( "Submit &Answer") self.questionBankPage.submitNewAnswerButton.clicked.connect( self.submitNewAnswer) layout.addRow(self.questionBankPage.defineCorrectAnswerButton, self.questionBankPage.submitNewAnswerButton) self.questionBankPage.submitNewQuestionButton = QPushButton( "Submit New &Question") self.questionBankPage.submitNewQuestionButton.clicked.connect( self.submitNewQuestion) layout.addRow(self.questionBankPage.submitNewQuestionButton) self.questionBankPage.backButton = QPushButton("&Back") self.questionBankPage.backButton.clicked.connect( self.goTo_FacilStartPage) self.questionBankPage.refreshButton = QPushButton("&Refresh") self.questionBankPage.refreshButton.clicked.connect( self.goTo_QuestionBankPage) layout.addRow(self.questionBankPage.backButton, self.questionBankPage.refreshButton) self.questionBankPage.setLayout(layout)
def __init__(self): super().__init__() self.setWindowTitle("📸 Random Image Tools V1.2 🔨") self.image_list = [] # ToDo: Add a "rename?" flag. Like rename image files # to store the directory path for later use self.directory_path_name = "/" # Set up the layouts layer_one = QHBoxLayout() # Select a folder, selected directory layer_one_and_a_half = QHBoxLayout() # Selected directory contents layer_two = QHBoxLayout() # Second line of buttons layer_two_vertical_one = QVBoxLayout() # Store the first column w/checkbox and "Convert" layer_two_vertical_two = QVBoxLayout() # Store the second column w/checkbox and "Open in File Browser" layer_three = QHBoxLayout() # Conversion process state vertical_layout_parent = QVBoxLayout() # Parent widget widget = QWidget() # Displays selected directory self.directory_label = QLabel() self.directory_label.setText("Directory to be worked on will show here ") self.directory_label.show() # Displays "Select folder" button self.select_a_folder_button = QPushButton() self.select_a_folder_button.setText("Select a folder:") self.select_a_folder_button.clicked.connect(self.select_folder_prompt) self.select_a_folder_button.show() # Displays the image contents of the selected folder self.image_paths_list_widget = QListWidget() self.image_paths_list_widget.show() # Displays button to initiate image conversion self.convert_to_png_button = QPushButton() self.convert_to_png_button.setText("Convert to PNG") self.convert_to_png_button.clicked.connect(self.convert_folder_to_png) self.convert_to_png_button.show() # Check boxes for "Create new folder for PNGs" and "Delete original files after converting" self.create_new_folder_checkbox = QCheckBox() self.create_new_folder_checkbox.setText("Create new folder to store converted PNG's?") self.create_new_folder_checkbox.show() self.delete_original_files_checkbox = QCheckBox() self.delete_original_files_checkbox.setText("Delete original files after converting them to PNG?") self.create_new_folder_checkbox.show() # Displays button to open selected directory in the file browser self.show_folder_button = QPushButton() self.show_folder_button.setText("Open selected folder in file browser") self.show_folder_button.clicked.connect(self.open_folder) self.show_folder_button.show() # Displays label when conversion is finished, and the corresponding progress bar self.conversion_finished_or_error_label = QLabel() self.conversion_finished_or_error_label.setText("👀 waiting for you to press \"Convert to PNG\" ") # Put the find folder button and folder selected button together layer_one.addWidget(self.select_a_folder_button) layer_one.addWidget(self.directory_label) # Image paths of selected folder layer_one_and_a_half.addWidget(self.image_paths_list_widget) # Put the convert button and open-in-finder button together layer_two_vertical_one.addWidget(self.convert_to_png_button) layer_two_vertical_one.addWidget(self.delete_original_files_checkbox) layer_two.addLayout(layer_two_vertical_one) layer_two_vertical_two.addWidget(self.show_folder_button) layer_two_vertical_two.addWidget(self.create_new_folder_checkbox) layer_two.addLayout(layer_two_vertical_two) # Label and progress bar layer_three.addWidget(self.conversion_finished_or_error_label) layer_three.setAlignment(Qt.AlignmentFlag.AlignHCenter) # Put the "convert to png" button beneath vertical_layout_parent.addLayout(layer_one) vertical_layout_parent.addLayout(layer_one_and_a_half) vertical_layout_parent.addLayout(layer_two) vertical_layout_parent.addLayout(layer_three) widget.setLayout(vertical_layout_parent) self.setCentralWidget(widget)
class AgentVariablesGroupView(QWidget): onVariablesChange = pyqtSignal(dict) def __init__( self, variables: dict[str, tuple[type, Any]], parent: Optional[QWidget] = None, *args: Tuple[Any, Any], **kwargs: Tuple[Any, Any], ) -> None: """ The two vertical box layouts of the variable names and their respective values. """ super(AgentVariablesGroupView, self).__init__(parent=parent, *args, **kwargs) self.__variables = variables self.setContentsMargins(0, 0, 0, 0) # keep our name and value labels here so we can destroy them when we need to redraw with updated variables namesLabels = list[QLabel]() valuesLabels = list[QLabel]() self.__horizontalGroupBoxLayout = QHBoxLayout() self.__variableNamesBox = QVBoxLayout() self.__variableValuesBox = QVBoxLayout() # submethod to update the 'names' and 'values' vertical views properly def updateVariableViews(vars: dict[str, tuple[type, Any]]) -> None: # for each name label in the list of namelabel widgets, for nameLabel in namesLabels: # then clear the label so it doesn't redraw later… nameLabel.clear() # and remove it from the vertical box layout. self.__variableNamesBox.removeWidget(nameLabel) # for each value label in the list of valuelabel widgets, for valueLabel in valuesLabels: # then clear the label so it doesn't redraw later… valueLabel.clear() # and remove it from the vertical box layout. self.__variableValuesBox.removeWidget(valueLabel) self.__variables = vars # for each variable name, then… # make a copy of the KeysView (keys) so it won't unexpectedly change size during iteration currentKeys = list(self.__variables.keys()) for variableName in currentKeys: # add it to the list of label widgets as a QLabel namesLabels.append(QLabel(variableName)) # …also add it to the vertical labelNames labels box self.__variableNamesBox.addWidget(namesLabels[-1]) # for each variable value, then… for variableValue in self.__variables.values(): # add it to the list of label widgets as a QLabel valuesLabels.append(QLabel(str(variableValue))) # …also add it to the vertical labelValues labels box self.__variableValuesBox.addWidget(valuesLabels[-1]) # add the layouts to our main window layout self.__horizontalGroupBoxLayout.addLayout(self.__variableNamesBox) self.__horizontalGroupBoxLayout.addLayout(self.__variableValuesBox) # aaand finally update the window to reflect our changes. self.update() self.onVariablesChange.connect(updateVariableViews) updateVariableViews(self.__variables) self.setLayout(self.__horizontalGroupBoxLayout)