def __init__(self, parent, database): """Initialize class""" super().__init__(parent) self.commit_msg = None self.setWindowTitle('Commit changes to {}'.format(database)) form = QVBoxLayout(self) form.setContentsMargins(0, 0, 0, 0) inner_layout = QVBoxLayout() inner_layout.setContentsMargins(4, 4, 4, 4) self.actionAccept = QAction(self) self.actionAccept.setShortcut( QApplication.translate("Dialog", "Ctrl+Return", None, -1)) self.actionAccept.triggered.connect(self.accept) self.actionAccept.setEnabled(False) self.commit_msg_edit = QPlainTextEdit(self) self.commit_msg_edit.setPlaceholderText( 'Commit message \t(press Ctrl+Enter to commit)') self.commit_msg_edit.addAction(self.actionAccept) button_box = QDialogButtonBox() button_box.addButton(QDialogButtonBox.Cancel) self.commit_button = button_box.addButton('Commit', QDialogButtonBox.AcceptRole) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) inner_layout.addWidget(self.commit_msg_edit) inner_layout.addWidget(button_box) # Add status bar to form form.addLayout(inner_layout) self.setAttribute(Qt.WA_DeleteOnClose) self.commit_msg_edit.textChanged.connect(self.receive_text_changed) self.receive_text_changed()
def __init__(self): """ The central hub for the application. Contains the tree views for compartments, buckets, and objects. Has buttons for uploading files and creating buckets """ super().__init__() self.setWindowTitle("OCI Object Storage: Not Connected") self.setMinimumSize(800, 600) self.profile = 'DEFAULT' self.oci_manager = oci_manager(profile=self.profile) try: self.compartment_tree = self.get_compartment_tree() except: print('Error: Failure to establish connection') self.compartment_tree = self.get_placeholder_tree( 'Compartments', 'Error: Failure to establish connection') else: self.setWindowTitle("OCI Object Storage: {}".format( self.oci_manager.get_namespace())) self.bucket_tree = self.get_placeholder_tree( 'Buckets', 'No compartment selected') self.obj_tree = self.get_placeholder_tree('Objects', 'No bucket selected') self.obj_tree.setHeaderLabels(['Objects', 'Size']) self.obj_tree.resizeColumnToContents(0) self.bucket_tree.itemClicked.connect(self.select_bucket) button = QPushButton('Upload Files') button.clicked.connect(self.select_files) button2 = QPushButton('New Bucket') button2.clicked.connect(self.create_bucket_prompt) button3 = QPushButton('Refresh') button3.clicked.connect(self.refresh) buttonBox = QDialogButtonBox() buttonBox.setOrientation(Qt.Vertical) buttonBox.addButton(button, QDialogButtonBox.ActionRole) buttonBox.addButton(button2, QDialogButtonBox.ActionRole) buttonBox.addButton(button3, QDialogButtonBox.ActionRole) self.layout = QHBoxLayout() self.layout.addWidget(buttonBox) self.layout.setAlignment(buttonBox, Qt.AlignHCenter) self.layout.addWidget(self.compartment_tree) self.layout.addWidget(self.bucket_tree) self.layout.addWidget(self.obj_tree) self.setLayout(self.layout) self.upload_threads = {} self.upload_thread_count = 0 self.progress_threads = {} self.progress_thread_count = 0
def __init__(self, parent=None): super(BlockingClient, self).__init__(parent) self.thread = FortuneThread() self.currentFortune = '' hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) ipAddress = ipAddress.toString() self.hostLineEdit = QLineEdit(ipAddress) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostLineEdit) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel( "This example requires that you run the Fortune Server example as well.") self.statusLabel.setWordWrap(True) self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.thread.newFortune.connect(self.showFortune) self.thread.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostLineEdit, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Blocking Fortune Client") self.portLineEdit.setFocus()
class UiMainWindow: def __init__(self, window: QMainWindow, vscreen: VScreen): self.window = window self.vscreen = vscreen window.setWindowFlags(Qt.Window | Qt.MSWindowsFixedSizeDialogHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint) self.centralWidget = QWidget() self.centralWidget.setLayout(QVBoxLayout()) self.centralWidget.layout().setContentsMargins(0, 0, 0, 0) window.setCentralWidget(self.centralWidget) self.monitor_overview_widget = VScreenOverview(vscreen, window) self.centralWidget.layout().addWidget(self.monitor_overview_widget) self.sub_widget = QWidget() self.sub_layout = QVBoxLayout() self.sub_widget.setLayout(self.sub_layout) self.centralWidget.layout().addWidget(self.sub_widget) self.monitor_info_group = QGroupBox() self.monitor_info_group.setLayout(QHBoxLayout()) for monitor in self.vscreen.monitor_order: info_box = QGroupBox("Monitor Information") info_box.ui = UiMonitorInfoBox(info_box, monitor) self.monitor_info_group.layout().addWidget(info_box) self.sub_layout.addWidget(self.monitor_info_group) self.button_group = QDialogButtonBox(Qt.Horizontal) self.button_group.setStyleSheet('* { button-layout: 2 }') self.close_button = self.button_group.addButton("Close", QDialogButtonBox.RejectRole) self.adjust_button = self.button_group.addButton("Adjust", QDialogButtonBox.ActionRole) self.about_button = self.button_group.addButton("About", QDialogButtonBox.HelpRole) self.sub_layout.addWidget(self.button_group) self.translate_ui() def translate_ui(self): self.window.setWindowTitle("HwMonitorAlignment") self.monitor_info_group.setTitle("Monitor Setup Information") self.close_button.setText("Close") self.adjust_button.setText("Adjust")
class BaseForm(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.main_layout = QVBoxLayout(self) self.setModal(True) def add_confirm_cancel_box(self): cancel_btn = QPushButton('取消') ok_btn = QPushButton('确定') self.ok_cancel_box = QDialogButtonBox() self.ok_cancel_box.addButton(ok_btn, QDialogButtonBox.AcceptRole) self.ok_cancel_box.addButton(cancel_btn, QDialogButtonBox.RejectRole) self.main_layout.addWidget(self.ok_cancel_box)
class RenameWindow(QDialog): new_name = Signal(str, str) def __init__(self, filename): super().__init__() self.title = 'Rename File' # self.left = 10 # self.top = 10 # self.width = 200 # self.height = 100 self.filename = filename self.initUI() def initUI(self): self.setWindowTitle(self.title) # self.setGeometry(self.left, self.top, self.width, self.height) self.textbox = QLineEdit(self) self.textbox.setText(self.filename) self.ok_button = QPushButton('Ok') self.ok_button.clicked.connect(self.on_click) self.cancel_button = QPushButton('Cancel') self.cancel_button.clicked.connect(self.reject) self.button_box = QDialogButtonBox() self.button_box.setOrientation(Qt.Horizontal) self.button_box.addButton(self.cancel_button, QDialogButtonBox.RejectRole) self.button_box.addButton(self.ok_button, QDialogButtonBox.AcceptRole) self.layout = QVBoxLayout() self.layout.addWidget(self.textbox) self.layout.addWidget(self.button_box) self.setLayout(self.layout) def on_click(self): self.new_name.emit(self.filename, self.textbox.text()) self.accept()
class SettingsTabDialog(QDialog): def __init__(self, node_set: NodeSet, parent=None): super().__init__(parent=parent) self.node_set = node_set self.tab_widget = QTabWidget() self.bitcoin_tab = BitcoinTab(self.node_set.bitcoin) self.tab_widget.addTab(self.bitcoin_tab, 'Bitcoin') self.lnd_tab = LndTab(self.node_set.lnd) self.tab_widget.addTab(self.lnd_tab, 'LND') self.button_box = QDialogButtonBox() self.button_box.addButton('Ok', QDialogButtonBox.AcceptRole) self.button_box.accepted.connect(self.accept) self.main_layout = QVBoxLayout() self.main_layout.addWidget(self.tab_widget) self.main_layout.addWidget(self.button_box) self.setLayout(self.main_layout) self.setWindowTitle('Settings')
class SettingsTabDialog(QDialog): def __init__(self, node_set: NodeSet, parent=None): super().__init__(parent=parent) self.node_set = node_set self.tab_widget = QTabWidget() self.litecoin_tab = LitecoinTab(self.node_set.litecoin) self.tab_widget.addTab(self.litecoin_tab, 'Litecoin') self.lnd_tab = LndTab(self.node_set.lnd) self.tab_widget.addTab(self.lnd_tab, 'LND') self.button_box = QDialogButtonBox() self.button_box.addButton('Ok', QDialogButtonBox.AcceptRole) self.button_box.accepted.connect(self.accept) self.main_layout = QVBoxLayout() self.main_layout.addWidget(self.tab_widget) self.main_layout.addWidget(self.button_box) self.setLayout(self.main_layout) self.setWindowTitle('Settings') def show(self): if self.node_set.lnd.file['alias'] is not None: self.lnd_tab.alias_layout.set_alias( self.node_set.lnd.file['alias']) self.litecoin_tab.data_directory_group_box.set_datadir( self.node_set.litecoin.file['datadir'], self.node_set.litecoin.file['prune']) super().show() self.raise_() self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) self.activateWindow()
def auto_label(self): all_labels = [] # Get current labels, we want unique for row in range(self.rowCount()): label = self.item(row, 1).text() all_labels.append(label) self.dialog = QDialog() lay = QVBoxLayout() self.dialog.setLayout(lay) self.line = QLineEdit() self.line.setText(self.store_re_text) bbox = QDialogButtonBox() bbox.addButton("Help", QDialogButtonBox.HelpRole) bbox.addButton("Apply", QDialogButtonBox.AcceptRole) bbox.addButton("Cancel", QDialogButtonBox.RejectRole) bbox.accepted.connect(self.apply_auto) bbox.rejected.connect(self.cancel_auto) bbox.helpRequested.connect(self.help_auto) lay.addWidget(self.line) lay.addWidget(bbox) self.dialog.resize(300, 100) ans = self.dialog.exec_() # This will block until the dialog closes if ans != 1: return re_text = self.line.text() self.store_re_text = re_text # Assign labels c = 0 for row in range(self.rowCount()): label = self.item(row, 1).text() file = self.item(row, 0).text() if label == '' and file != '': file_name = os.path.basename(file) search = re.search(re_text, file_name) if search is not None: c += 1 # idk how to check how many captured groups, so lets do this a hacky way for i in range(10,-1,-1): try: added_label = search.group(i) break except Exception as e: pass else: added_label = '' # Do not add label if you don't know what to add self.item(row, 1).setText(added_label) if c == 0: ERROR("No files matched the regex pattern") self.auto_label()
def __init__(self, number_moves): super(Exit_window, self).__init__() self.setWindowTitle("Bravo !") self.setWindowFlags(Qt.WindowStaysOnTopHint) self.end_msg = QLabel("Vous avez gagné en " + str(number_moves) + " coups ! Que voulez-vous faire ?") mainLayout = QVBoxLayout() replay_button = QPushButton("Rejouer cette partie") replay_button.clicked.connect(self.replay) new_game_button = QPushButton("Un nouveau jeu") new_game_button.clicked.connect(self.new_game) exit_button = QPushButton("Quitter") exit_button.clicked.connect(self.exit_game) buttonBox = QDialogButtonBox(Qt.Horizontal) buttonBox.addButton(replay_button, QDialogButtonBox.ActionRole) buttonBox.addButton(new_game_button, QDialogButtonBox.ActionRole) buttonBox.addButton(exit_button, QDialogButtonBox.ActionRole) mainLayout.addWidget(self.end_msg) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setGeometry(250, 250, 0, 50)
def init_ui(self): self.setWindowTitle(_('Result')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.setMaximumWidth(300) self.layout = QFormLayout(self) self.item_created_at = QTimeEdit() self.item_created_at.setDisplayFormat(self.time_format) self.item_created_at.setReadOnly(True) self.item_card_number = QSpinBox() self.item_card_number.setMaximum(9999999) self.item_bib = QSpinBox() self.item_bib.setMaximum(Limit.BIB) self.item_bib.valueChanged.connect(self.show_person_info) self.label_person_info = QLabel('') self.item_days = QSpinBox() self.item_days.setMaximum(365) self.item_finish = QTimeEdit() self.item_finish.setDisplayFormat(self.time_format) self.item_start = QTimeEdit() self.item_start.setDisplayFormat(self.time_format) self.item_result = QLineEdit() self.item_result.setEnabled(False) self.item_credit = QTimeEdit() self.item_credit.setDisplayFormat(self.time_format) self.item_penalty = QTimeEdit() self.item_penalty.setDisplayFormat(self.time_format) self.item_penalty_laps = QSpinBox() self.item_penalty_laps.setMaximum(1000000) self.item_status = QComboBox() self.item_status.addItems(ResultStatus.get_titles()) self.item_status_comment = AdvComboBox() self.item_status_comment.setMaximumWidth(300) self.item_status_comment.view().setMinimumWidth(600) self.item_status_comment.addItems(StatusComments().get_all()) for i, k in enumerate(StatusComments().get_all()): self.item_status_comment.setItemData(i, k, Qt.ToolTipRole) more24 = race().get_setting('time_format_24', 'less24') == 'more24' self.splits = SplitsText(more24=more24) self.layout.addRow(QLabel(_('Created at')), self.item_created_at) if self.current_object.is_punch(): self.layout.addRow(QLabel(_('Card')), self.item_card_number) self.layout.addRow(QLabel(_('Bib')), self.item_bib) self.layout.addRow(QLabel(''), self.label_person_info) if more24: self.layout.addRow(QLabel(_('Days')), self.item_days) self.layout.addRow(QLabel(_('Start')), self.item_start) self.layout.addRow(QLabel(_('Finish')), self.item_finish) self.layout.addRow(QLabel(_('Credit')), self.item_credit) self.layout.addRow(QLabel(_('Penalty')), self.item_penalty) self.layout.addRow(QLabel(_('Penalty legs')), self.item_penalty_laps) self.layout.addRow(QLabel(_('Result')), self.item_result) self.layout.addRow(QLabel(_('Status')), self.item_status) self.layout.addRow(QLabel(_('Comment')), self.item_status_comment) if self.current_object.is_punch(): start_source = race().get_setting('system_start_source', 'protocol') finish_source = race().get_setting('system_finish_source', 'station') if start_source == 'protocol' or start_source == 'cp': self.item_start.setDisabled(True) if finish_source == 'cp': self.item_finish.setDisabled(True) self.layout.addRow(self.splits.widget) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) if self.current_object.person: button_person = button_box.addButton(_('Entry properties'), QDialogButtonBox.ActionRole) button_person.clicked.connect(self.open_person) self.layout.addRow(button_box) self.show() self.item_bib.setFocus()
def __init__(self): super().__init__(GlobalAccess().get_main_window()) self.setWindowModality(QtCore.Qt.WindowModal) self.resize(319, 462) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QVBoxLayout(self) self.grid_layout = QtWidgets.QGridLayout() widget = QWidget(self) widget.setLayout(self.grid_layout) self.value_group_box = QtWidgets.QGroupBox(self) self.grid_layout_child = QtWidgets.QGridLayout(self.value_group_box) self.id_label = QtWidgets.QLabel(self.value_group_box) self.grid_layout_child.addWidget(self.id_label, 0, 0, 1, 1) self.id_layout = QtWidgets.QVBoxLayout() self.bib_radio_button = QtWidgets.QRadioButton(self.value_group_box) self.bib_radio_button.setChecked(True) self.id_layout.addWidget(self.bib_radio_button) self.name_radio_button = QtWidgets.QRadioButton(self.value_group_box) self.id_layout.addWidget(self.name_radio_button) self.grid_layout_child.addLayout(self.id_layout, 0, 1, 1, 1) self.value_label = QtWidgets.QLabel(self.value_group_box) self.grid_layout_child.addWidget(self.value_label, 1, 0, 1, 1) self.value_combo_box = QtWidgets.QComboBox(self.value_group_box) self.value_combo_box.addItems(get_value_options()) self.grid_layout_child.addWidget(self.value_combo_box, 1, 1, 1, 1) self.id_label.raise_() self.bib_radio_button.raise_() self.value_label.raise_() self.value_combo_box.raise_() self.grid_layout.addWidget(self.value_group_box, 0, 0, 1, 1) self.separator_group_box = QtWidgets.QGroupBox(self) self.separator_grid_layout = QtWidgets.QGridLayout( self.separator_group_box) self.space_radio_button = QtWidgets.QRadioButton( self.separator_group_box) self.separator_grid_layout.addWidget(self.space_radio_button, 0, 0, 1, 1) self.tab_radio_button = QtWidgets.QRadioButton( self.separator_group_box) self.tab_radio_button.setChecked(True) self.separator_grid_layout.addWidget(self.tab_radio_button, 1, 0, 1, 1) self.semicolon_radio_button = QtWidgets.QRadioButton( self.separator_group_box) self.separator_grid_layout.addWidget(self.semicolon_radio_button, 2, 0, 1, 1) self.custom_layout = QtWidgets.QHBoxLayout() self.custom_radio_button = QtWidgets.QRadioButton( self.separator_group_box) self.custom_layout.addWidget(self.custom_radio_button) self.custom_edit = QtWidgets.QLineEdit(self.separator_group_box) self.custom_layout.addWidget(self.custom_edit) self.separator_grid_layout.addLayout(self.custom_layout, 3, 0, 1, 1) self.grid_layout.addWidget(self.separator_group_box, 0, 1, 1, 1) self.options_group_box = QtWidgets.QGroupBox(self) self.options_grid_layout = QtWidgets.QGridLayout( self.options_group_box) self.option_creating_new_result_checkbox = QCheckBox( _("Create new result, if doesn't exist")) self.options_grid_layout.addWidget( self.option_creating_new_result_checkbox, 0, 0, 1, 1) self.grid_layout.addWidget(self.options_group_box, 1, 0, 1, 2) self.text_edit = QtWidgets.QPlainTextEdit(self) self.grid_layout.addWidget(self.text_edit, 2, 0, 1, 2) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(self.accept) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(self.reject) stf_button = button_box.addButton(_('Save to file'), QDialogButtonBox.ActionRole) stf_button.clicked.connect(self.save_to_file) stf_button.setDisabled(True) lff_button = button_box.addButton(_('Load from file'), QDialogButtonBox.ActionRole) lff_button.clicked.connect(self.load_from_file) lff_button.setDisabled(True) self.layout.addWidget(widget) self.layout.addWidget(button_box) self.retranslate_ui(self)
class AboutDialog(QDialog): SOFTWARE_HEADER_NAMES = ['Software', 'License'] def __init__(self, parent=None): super().__init__(parent) self.setFixedSize(500, 420) self.setWindowModality(Qt.ApplicationModal) self.setWindowTitle('About HwMonitorAlignment') self._layout = QGridLayout() self._read_libraries() self.header_label = QLabel(self) self.header_label.setPixmap( load_pixmap('icon.ico').scaled(125, 125, Qt.KeepAspectRatio)) # self.header_label.setPixmap(QPixmap('doc/hma_logo_left.png').scaledToWidth(480)) self._layout.addWidget(self.header_label, 0, 0) self.short_info = QLabel() self.short_info.setAlignment(Qt.AlignCenter) self.short_info.setText('<h2>{0} {1}</h2>' '<p>{2}</p>' '<a href="{3}">Project website</a>'.format( str(hwmonitor.__name__), str(hwmonitor.__version__), str(hwmonitor.__description__), str(hwmonitor.__website__))) self.short_info.setWordWrap(True) self.short_info.setOpenExternalLinks(True) self._layout.addWidget(self.short_info, 0, 1) # spacer self._layout.addWidget(QWidget(), 0, 2, 1, 1) # Info tabs self.tab_widget = QTabWidget(self) self._layout.addWidget(self.tab_widget, 2, 0, 1, 3) # Software Licenses Widget self.library_table = QTableWidget(len(self._libraries), 2, self.tab_widget) self.library_table.setHorizontalHeaderLabels( self.SOFTWARE_HEADER_NAMES) self.library_table.horizontalHeader().setStretchLastSection(True) self.library_table.setEditTriggers(QTableWidget.NoEditTriggers) self.library_table.setSelectionMode(QTableWidget.NoSelection) self.library_table.verticalHeader().hide() self.library_table.setColumnWidth(0, int(self.width() / 3 * 1.8)) self.library_table.setShowGrid(False) self.tab_widget.addTab(self.library_table, 'Third-party software components') # Buttons self.dialog_buttons = QDialogButtonBox(Qt.Horizontal, self) self.dialog_buttons.setStyleSheet('* { button-layout: 2 }') self.close_button = self.dialog_buttons.addButton( "Close", QDialogButtonBox.AcceptRole) self.about_button = self.dialog_buttons.addButton( "About Qt", QDialogButtonBox.HelpRole) self.close_button.clicked.connect(self.accept) self.about_button.clicked.connect(qApp.aboutQt) self._layout.addWidget(self.dialog_buttons, 3, 0, 1, 3) self._layout.setColumnStretch(0, 1) self._layout.setColumnStretch(1, 3) self._layout.setRowStretch(0, 6) self._layout.setRowStretch(1, 1) self._layout.setRowStretch(2, 16) self._layout.setRowStretch(3, 3) self.setLayout(self._layout) self._populate_library_tree() def _read_libraries(self): """Reads all libraries and licenses from included 'licenses' . +--library_name | +--version: 0.1 | +--license: MIT | +--library_url: http://library.org | +--license_url: http://license.com . . """ import sys import PySide2 self._libraries = { 'python': { 'version': '{0}.{1}.{2}-{3}'.format(*sys.version_info), 'license': 'PSF', 'library_url': 'http://www.python.org', 'license_url': 'http://docs.python.org/3/license.html' }, 'PySide2': { 'version': PySide2.__version__, 'license': 'GNU LGPL v3', 'library_url': 'http://www.qt.io/qt-for-python', 'license_url': 'https://doc.qt.io/qt-5/lgpl.html' }, 'Components of linux-show-player': { 'version': '', 'license': 'GNU GPL v3', 'library_url': 'https://github.com/FrancescoCeruti/linux-show-player', 'license_url': 'https://github.com/FrancescoCeruti/linux-show-player/blob/master/LICENSE' } } def _populate_library_tree(self): """Puts every library name and license into model for library view """ for i, library in enumerate(self._libraries): library_info = self._libraries[library] library_text = '<a href="{0}">{1}</a> <font color="#777">{2}</font>'.format( library_info['library_url'], library, library_info['version']) license_text = '<a href="{0}">{1}</a>'.format( library_info['license_url'], library_info['license']) name_label, license_label = self._library_item_widgets( library_text, license_text) self.library_table.setCellWidget(i, 0, name_label) self.library_table.setCellWidget(i, 1, license_label) @staticmethod def _library_item_widgets(library_text, license_text): name_label = QLabel() name_label.setText(library_text) name_label.setTextFormat(Qt.RichText) name_label.setTextInteractionFlags(Qt.TextBrowserInteraction) name_label.setOpenExternalLinks(True) name_label.setMargin(5) license_label = QLabel() license_label.setText(license_text) license_label.setTextFormat(Qt.RichText) license_label.setTextInteractionFlags(Qt.TextBrowserInteraction) license_label.setOpenExternalLinks(True) return name_label, license_label
class TornaSettingsDialog(QDialog): def __init__(self, parent=None, torna_id=None): super(TornaSettingsDialog, self).__init__(parent) self.parent = parent self.setModal(True) self.setWindowTitle("Verseny beállítások") self.torna_id = torna_id self.main_layout = QVBoxLayout() self.setLayout(self.main_layout) if self.torna_id is not None: self.create_torna_selection() self.set_layouts() self.add_variables() self.alapertekek() self.add_buttonbox() def set_layouts(self): self.tartalom_layout = QHBoxLayout() self.main_layout.addLayout(self.tartalom_layout) self.layout = QVBoxLayout() self.gomb_layout = QVBoxLayout() self.tartalom_layout.addLayout(self.layout) self.tartalom_layout.addLayout(self.gomb_layout) def add_variables(self): self.layout.addWidget(QLabel("A verseny megnevezése:")) self.torna_name = QLineEdit() self.torna_name.setPlaceholderText("A verseny megnevezése") self.layout.addWidget(self.torna_name) self.layout.addWidget(QLabel("Legyen csoportkör?")) self.is_roundrobin = QCheckBox() self.is_roundrobin.stateChanged.connect(self.roundrobin_changed) self.layout.addWidget(self.is_roundrobin) self.layout.addWidget(QLabel("Csoportok száma:")) self.csoport_number = CustomSpinBox(1, 16) self.layout.addWidget(self.csoport_number) self.layout.addWidget(QLabel("Játékosok száma csoportonként:")) self.jatekos_per_csoport = CustomSpinBox(3, 8) self.layout.addWidget(self.jatekos_per_csoport) self.layout.addWidget(QLabel("Játéknem:")) self.variant = CustomSpinBox(301, 1001) self.layout.addWidget(self.variant) self.layout.addWidget(QLabel("Set-ek?:")) self.is_sets = QCheckBox() self.is_sets.stateChanged.connect(self.is_sets_changed) self.layout.addWidget(self.is_sets) self.layout.addWidget(QLabel("Set-ek száma:")) self.sets_number = CustomSpinBox(1, 8) self.sets_number.setDisabled(True) self.layout.addWidget(self.sets_number) self.layout.addWidget(QLabel("Leg-ek száma:")) self.legs_number = CustomSpinBox(2, 30) self.layout.addWidget(self.legs_number) self.layout.addWidget(QLabel("Best of...")) self.is_best = QCheckBox() self.layout.addWidget(self.is_best) self.layout.addWidget(QLabel("Döntetlen")) self.is_draw = QCheckBox() self.is_draw.stateChanged.connect(self.is_draw_changed) self.layout.addWidget(self.is_draw) self.layout.addWidget(QLabel("Pont(Győzelem):")) self.pont_win = CustomSpinBox(2, 5) self.layout.addWidget(self.pont_win) self.layout.addWidget(QLabel("Pont(Döntetlen):")) self.pont_draw = CustomSpinBox(1, 3) self.pont_draw.setDisabled(True) self.layout.addWidget(self.pont_draw) self.layout.addWidget(QLabel("Pont(Vereség):")) self.pont_lost = CustomSpinBox(0, 2) self.layout.addWidget(self.pont_lost) self.layout.addWidget(QLabel("Főág")) self.is_single_elim = QCheckBox() self.is_single_elim.stateChanged.connect(self.is_single_changed) self.layout.addWidget(self.is_single_elim) self.layout.addWidget(QLabel("Főág száma:")) self.num_single = CustomSpinBox(4, 128) self.num_single.setDisabled(True) self.layout.addWidget(self.num_single) self.layout.addWidget(QLabel("Leg-ek száma a főágon:")) self.leg_num_single = CustomSpinBox(3, 20) self.leg_num_single.setDisabled(True) self.layout.addWidget(self.leg_num_single) self.layout.addWidget(QLabel("Leg-ek száma az elődöntőben:")) self.leg_num_semifinal = CustomSpinBox(4, 20) self.leg_num_semifinal.setDisabled(True) self.layout.addWidget(self.leg_num_semifinal) self.layout.addWidget(QLabel("Leg-ek száma a döntőben:")) self.leg_num_final = CustomSpinBox(5, 20) self.leg_num_final.setDisabled(True) self.layout.addWidget(self.leg_num_final) self.layout.addWidget(QLabel("3. hely kijátszva")) self.is_3place = QCheckBox() self.is_3place.stateChanged.connect(self.is_3place_changed) self.is_3place.setDisabled(True) self.layout.addWidget(self.is_3place) self.layout.addWidget(QLabel("Leg-ek száma a 3. helyért:")) self.leg_num_3place = CustomSpinBox(4, 20) self.leg_num_3place.setDisabled(True) self.layout.addWidget(self.leg_num_3place) def create_torna_selection(self): self.tournaments = QComboBox() self.tournaments.setModelColumn(0) self.tournaments.currentIndexChanged.connect(self.torna_valasztas) self.main_layout.addWidget(self.tournaments) self.load_torna() def load_torna(self): torna = QSqlQueryModel() query = QSqlQuery("select * from torna_settings where aktiv=2") torna.setQuery(query) if torna.record(0).value(0): for i in range(torna.rowCount()): self.tournaments.addItem( torna.record(i).value(1), torna.record(i).value(0)) # a value(0) a torna_id else: print("Nincs aktív torna") def torna_valasztas(self, i): self.torna_id = self.tournaments.itemData(i) self.alapertekek() def alapertekek(self): if not self.torna_id: self.torna_name.clear() self.is_roundrobin.setChecked(True) self.csoport_number.setValue(1) self.jatekos_per_csoport.setValue(4) self.variant.setValue(501) self.is_sets.setChecked(False) self.sets_number.setValue(1) self.legs_number.setValue(2) self.is_best.setChecked(False) self.is_draw.setChecked(False) self.pont_win.setValue(2) self.pont_draw.setValue(1) self.pont_lost.setValue(0) self.is_single_elim.setChecked(False) self.num_single.setValue(8) self.leg_num_single.setValue(3) self.leg_num_semifinal.setValue(4) self.leg_num_final.setValue(5) self.is_3place.setChecked(False) self.leg_num_3place.setValue(4) else: model = QSqlTableModel(db=db) model.setTable("torna_settings") model.setFilter(f"torna_id={self.torna_id}") model.select() # print(model.record(0)) self.torna_name.setText(model.record(0).value(1)) self.is_roundrobin.setChecked(model.record(0).value(2)) self.csoport_number.setValue(model.record(0).value(3)) self.jatekos_per_csoport.setValue(model.record(0).value(4)) self.variant.setValue(int(model.record(0).value(5))) self.is_sets.setChecked(model.record(0).value(6)) self.sets_number.setValue(model.record(0).value(7)) self.legs_number.setValue(model.record(0).value(8)) self.is_best.setChecked(model.record(0).value(9)) self.is_draw.setChecked(model.record(0).value(10)) self.pont_win.setValue(model.record(0).value(11)) self.pont_draw.setValue(model.record(0).value(12)) self.pont_lost.setValue(model.record(0).value(13)) self.is_single_elim.setChecked(model.record(0).value(14)) self.num_single.setValue(model.record(0).value(15)) self.leg_num_single.setValue(model.record(0).value(17)) self.leg_num_semifinal.setValue(model.record(0).value(18)) self.leg_num_final.setValue(model.record(0).value(20)) self.is_3place.setChecked(model.record(0).value(16)) self.leg_num_3place.setValue(model.record(0).value(19)) def add_buttonbox(self): self.buttonbox = QDialogButtonBox() self.buttonbox.setOrientation(Qt.Vertical) self.buttonbox.addButton("Mentés", QDialogButtonBox.ActionRole) self.buttonbox.addButton("Alaphelyzet", QDialogButtonBox.ActionRole) # self.gomb_members = QPushButton("Résztvevők") # self.gomb_members.setDisabled(True) # self.buttonbox.addButton(self.gomb_members, QDialogButtonBox.ActionRole) # self.gomb_tabella = QPushButton("Tabella") # self.gomb_tabella.setDisabled(True) # self.buttonbox.addButton(self.gomb_tabella, QDialogButtonBox.ActionRole) self.buttonbox.addButton("Mégsem", QDialogButtonBox.ActionRole) self.buttonbox.clicked.connect(self.buttonbox_click) self.gomb_layout.addWidget(self.buttonbox) def roundrobin_changed(self, state): if state == Qt.Checked: self.csoport_number.setDisabled(False) self.jatekos_per_csoport.setDisabled(False) else: self.csoport_number.setDisabled(True) self.jatekos_per_csoport.setDisabled(True) def is_sets_changed(self, state): if state == Qt.Checked: self.sets_number.setDisabled(False) else: self.sets_number.setDisabled(True) def is_draw_changed(self, state): if state == Qt.Checked: self.pont_draw.setDisabled(False) else: self.pont_draw.setDisabled(True) def is_single_changed(self, state): # a főághoz kapcsolódó paraméterek tiltása/engedélyezése if state == Qt.Checked: self.num_single.setDisabled(False) self.is_3place.setDisabled(False) self.leg_num_single.setDisabled(False) self.leg_num_semifinal.setDisabled(False) if self.is_3place.isChecked(): self.leg_num_3place.setDisabled(False) else: self.leg_num_3place.setDisabled(True) self.leg_num_final.setDisabled(False) else: self.num_single.setDisabled(True) self.is_3place.setDisabled(True) self.leg_num_single.setDisabled(True) self.leg_num_semifinal.setDisabled(True) self.leg_num_3place.setDisabled(True) self.leg_num_final.setDisabled(True) def is_3place_changed(self, state): if state == Qt.Checked: self.leg_num_3place.setDisabled(False) else: self.leg_num_3place.setDisabled(True) def buttonbox_click(self, b): if b.text() == "Mentés": self.save() elif b.text() == "Alaphelyzet": self.alapertekek() # elif b.text() == "Résztvevők": # self.members() # elif b.text() == "Tabella": # self.tabella() elif b.text() == "Mégsem": self.reject() else: pass def save(self): if not self.torna_id: self.insert_torna_settings() else: self.update_torna_settings() self.close() def insert_torna_settings(self): van_ilyen_nev = False if len(self.torna_name.text()) != 0: torna_id_model = QSqlQueryModel() query = QSqlQuery( "select torna_id, torna_name from torna_settings", db=db) torna_id_model.setQuery(query) for i in range(torna_id_model.rowCount()): if torna_id_model.record(i).value(1) == self.torna_name.text(): msg = QMessageBox(self) msg.setStyleSheet("fonz-size: 20px") msg.setWindowTitle("Név ütközés!") msg.setText( '<html style="font-size: 14px; color: red">Már van ilyen nevű verseny!<br></html>' + '<html style="font-size: 16px">Kérem adjon a versenynek egyedi nevet!</html>' ) msg.exec_() van_ilyen_nev = True if not van_ilyen_nev: torna_settings_model = QSqlTableModel( db=db ) # !!!!!!! Ha több db van, akkor itt konkrétan meg kell adni torna_settings_model.setTable("torna_settings") record = torna_settings_model.record() record.setValue(1, self.torna_name.text()) if self.is_roundrobin.isChecked(): record.setValue(2, 1) else: record.setValue(2, 0) record.setValue(3, self.csoport_number.value()) record.setValue(4, self.jatekos_per_csoport.value()) record.setValue(5, self.variant.value()) if self.is_sets.isChecked(): record.setValue(6, 1) else: record.setValue(6, 0) record.setValue(7, self.sets_number.value()) record.setValue(8, self.legs_number.value()) # print(record.value(2)) if self.is_best.isChecked(): record.setValue(9, 1) else: record.setValue(9, 0) if self.is_draw.isChecked(): record.setValue(10, 1) else: record.setValue(10, 0) record.setValue(11, self.pont_win.value()) record.setValue(12, self.pont_draw.value()) record.setValue(13, self.pont_lost.value()) if self.is_single_elim.isChecked(): record.setValue(14, 1) else: record.setValue(14, 0) record.setValue(15, self.num_single.value()) if self.is_3place.isChecked(): record.setValue(16, 1) else: record.setValue(16, 0) record.setValue(17, self.leg_num_single.value()) record.setValue(18, self.leg_num_semifinal.value()) record.setValue(19, self.leg_num_3place.value()) record.setValue(20, self.leg_num_final.value()) record.setValue(21, 2) # aktiv flag: 0: vége, 1: folyamatban, 2: szerkesztés alatt # print(record) if torna_settings_model.insertRecord(-1, record): torna_settings_model.submitAll() else: db.rollback() torna_id_model2 = QSqlQueryModel() query2 = QSqlQuery( f"select torna_id from torna_settings where torna_name='{self.torna_name.text()}'", db=db) torna_id_model2.setQuery(query2) self.torna_id = int(torna_id_model2.record(0).value(0)) self.gomb_members.setDisabled(False) else: msg = QMessageBox(self) msg.setStyleSheet("fonz-size: 20px") msg.setWindowTitle("Hiányzik a verseny neve!") msg.setText( '<html style="font-size: 14px; color: red">A létrehozott versenynek kell egy elnevezés!<br></html>' + '<html style="font-size: 16px">Kérem adja meg a verseny nevét!</html>' ) msg.exec_() def update_torna_settings(self): torna_settings_model = QSqlTableModel(db=db) torna_settings_model.setTable("torna_settings") record = torna_settings_model.record() torna_settings_model.select() # for x in range(torna_settings_model.rowCount()): # record.setGenerated(x, False) record.setValue(0, self.torna_id) record.setValue(1, self.torna_name.text()) if self.is_roundrobin.isChecked(): record.setValue(2, 1) else: record.setValue(2, 0) record.setValue(3, self.csoport_number.value()) record.setValue(4, self.jatekos_per_csoport.value()) record.setValue(5, self.variant.value()) if self.is_sets.isChecked(): record.setValue(6, 1) else: record.setValue(6, 0) record.setValue(7, self.sets_number.value()) record.setValue(8, self.legs_number.value()) if self.is_best.isChecked(): record.setValue(9, 1) else: record.setValue(9, 0) if self.is_draw.isChecked(): record.setValue(10, 1) else: record.setValue(10, 0) record.setValue(11, self.pont_win.value()) record.setValue(12, self.pont_draw.value()) record.setValue(13, self.pont_lost.value()) if self.is_single_elim.isChecked(): record.setValue(14, 1) else: record.setValue(14, 0) record.setValue(15, self.num_single.value()) if self.is_3place.isChecked(): record.setValue(16, 1) else: record.setValue(16, 0) record.setValue(17, self.leg_num_single.value()) record.setValue(18, self.leg_num_semifinal.value()) record.setValue(19, self.leg_num_3place.value()) record.setValue(20, self.leg_num_final.value()) record.setValue(21, 2) for i in range(torna_settings_model.rowCount()): if torna_settings_model.record(i).value(0) == self.torna_id: # print(torna_settings_model.record(i).value(0), ":", i) record_number = i # print(record) if torna_settings_model.setRecord(record_number, record): torna_settings_model.submitAll() else: db.rollback() # def members(self): # # todo Itt kell a verseny résztvevőit öszerakni # pass # # def tabella(self): # # todo Itt kell a sorsolást, tabella összeállítást megcsinálni # pass def accept(self): # todo Ez majd csak a bezáráshoz kell super().accept() def reject(self): print("CANCEL") super().reject()
def __init__(self, test_name: str, reference_image: QPixmap, generated_image: QPixmap): super(ApprovalDialog, self).__init__() self.setWindowTitle(test_name) main_layout = QVBoxLayout(self) ref_image = QLabel() ref_image.setPixmap(reference_image) gen_image = QLabel() gen_image.setPixmap(generated_image) scroll_area = QScrollArea() self.layout().addWidget(scroll_area) screen_width, screen_height = QGuiApplication.primaryScreen().size( ).toTuple() if reference_image.width() + gen_image.width() >= screen_width: self.image_layout = QVBoxLayout() else: self.image_layout = QHBoxLayout() self.image_layout.addStretch() self.image_layout.addWidget(ref_image) self.image_layout.addWidget(gen_image) self.image_layout.addStretch() scroll_area.setWidget(QWidget()) scroll_area.setWidgetResizable(True) scroll_area.widget().setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) scroll_area.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum) scroll_area.widget().setLayout(self.image_layout) def _sizeHint(): orig_size = scroll_area.widget().sizeHint() orig_size.setHeight(orig_size.height() + 20) orig_size.setWidth(orig_size.width() + 20) if orig_size.width() > screen_width - 20: orig_size.setWidth(screen_width - 20) if orig_size.height() > screen_height - 20: orig_size.setHeight(screen_height - 20) return orig_size scroll_area.sizeHint = _sizeHint button_box = QDialogButtonBox() button_box.addButton( "Reject", QDialogButtonBox.RejectRole).clicked.connect(self.reject) button_box.addButton(QDialogButtonBox.Ignore).clicked.connect( self._on_ignore) button_box.addButton("Accept as new Reference", QDialogButtonBox.ApplyRole).clicked.connect( self._on_overwrite) main_layout.addWidget(scroll_area) main_layout.addWidget(button_box, alignment=Qt.AlignCenter)
class ProgressWindow(QWidget): cancel_signal = Signal(int) def __init__(self, files, filesizes, thread_id, download=False): super().__init__() print(len(files[0]), len(filesizes)) print(files[0]) self.files_uploaded = 0 self.files_len = len(files[0]) self.files = files self.filesizes = filesizes self.divider = 1024**byte_type[self.filesizes[self.files_uploaded][1][1]] self.max = round(self.filesizes[self.files_uploaded][0]/self.divider) self.download = download self.thread_id = thread_id self.count = 0 self.initUI() def initUI(self): self.file_label = QLabel() # self.file_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) # self.file_label.setFrameShape(QFrame.Box) # self.file_label.setAlignment(Qt.AlignHCenter) # self.file_label.setStyleSheet("border-style: solid; border-width: 2px;") if self.download: self.setWindowTitle('Downloading Files ({}/{})'.format(self.files_uploaded, len(self.files[0]))) self.file_label.setText("Downloading {}".format(self.files[0][self.files_len - 1].split('/')[-1])) else: self.setWindowTitle('Uploading Files ({}/{})'.format(self.files_uploaded, len(self.files[0]))) self.file_label.setText("Uploading {}".format(self.files[0][self.files_len - 1].split('/')[-1])) self.size_label = QLabel(" ".join(self.filesizes[self.files_uploaded][1])) self.size_label.setAlignment(Qt.AlignRight) self.layout = QVBoxLayout() self.cancel = QPushButton() self.cancel.setText("Cancel") self.cancel.clicked.connect(self.cancel_handler) self.ok = QPushButton() self.ok.setText("OK") self.ok.setEnabled(False) self.ok.clicked.connect(self.hide) self.retry = QPushButton() self.retry.setText("Retry") self.retry.setEnabled(False) self.button_box = QDialogButtonBox() self.button_box.setOrientation(Qt.Horizontal) self.button_box.addButton(self.ok, QDialogButtonBox.ActionRole) self.button_box.addButton(self.cancel, QDialogButtonBox.ActionRole) self.button_box.addButton(self.retry, QDialogButtonBox.ActionRole) self.progress = QProgressBar(self) self.progress.setMaximum(self.max) self.progress.setValue(0) # print(self.file_label.textFormat(), self.file_label.lineWidth(), self.file_label.margin(), self.file_label.frameSize()) # self.file_label.show() # self.file_label.setBuddy(self.progress) self.layout.addWidget(self.file_label) self.layout.addWidget(self.progress) self.layout.addWidget(self.size_label) self.layout.addWidget(self.button_box) self.retry_label = QLabel() self.retry_label.setText("Connection failed") self.retry_label.setStyleSheet("QLabel {color: red; }") self.layout.addWidget(self.retry_label) self.retry_label.setVisible(False) self.setLayout(self.layout) def test(self): self.calc = TestProgress() self.calc.countChanged.connect(self.set_progress) self.calc.start() def next_file(self, *args): # print(self.files[0]) self.retry_label.setVisible(False) self.retry.setEnabled(False) if self.files_uploaded < self.files_len: self.files_uploaded += 1 if self.download: self.setWindowTitle("Downloading Files ({}/{})".format(self.files_uploaded, self.files_len)) else: self.setWindowTitle("Uploading Files ({}/{})".format(self.files_uploaded, self.files_len)) if self.files_uploaded < self.files_len: self.count = 0 self.progress.setValue(0) if self.download: self.file_label.setText("Downloading {}".format(self.files[0][(self.files_len - 1) - self.files_uploaded].split('/')[-1])) else: self.file_label.setText("Uploading {}".format(self.files[0][(self.files_len - 1) - self.files_uploaded].split('/')[-1])) self.size_label.setText(" ".join(self.filesizes[(self.files_len - 1) - self.files_uploaded][1])) self.divider = 1024**byte_type[self.filesizes[(self.files_len - 1) - self.files_uploaded][1][1]] self.max = round(self.filesizes[(self.files_len - 1) - self.files_uploaded][0]/self.divider) self.progress.setMaximum(self.max) else: if self.download: self.file_label.setText("All downloads complete") else: self.file_label.setText("All uploads complete") self.size_label.setText("") self.progress.setValue(self.max) self.ok.setEnabled(True) self.cancel.setEnabled(False) def set_progress(self, count): # print("{} bytes uploaded".format(count)) self.count += (count/self.divider) self.progress.setValue(self.count) def connection_failed(self): self.connection_failed_label = QLabel() self.connection_failed_label.setText("Connection failed") def cancel_handler(self): self.cancel_signal.emit(self.thread_id) self.hide() def retry_handler(self): print("Retry handler") self.retry_label.setVisible(True) self.retry.setEnabled(True) if self.download: self.count = 0 self.progress.setValue(self.count)
class ConfigWindow(QWidget): def __init__(self, current_profile): """ The ConfigWindow is a widget dedicated to reading and editing the OCI config file and provides functionality to create, edit, and switch profiles on the fly, updating the view of the main window. :param current_profile: The profile the ConfigWindow should be initialized with :type current_profile: string """ super().__init__() # self.main_window = None self.setWindowTitle("Profile Settings") self.setMinimumSize(600, 200) #Looks for the config file in '~/.oci/config' and reads it into config self.DEFAULT_LOCATION = os.path.expanduser( os.path.join('~', '.oci', 'config')) self.config = configparser.ConfigParser(interpolation=None) self.config.read(self.DEFAULT_LOCATION) self.current_profile = current_profile #Set up necessary dropdown and LineEdit widgets self.dropdown = self.get_profiles_dropdown() self.tenancy = QLineEdit() self.tenancy.setPlaceholderText("Tenancy OCID") self.region = QLineEdit() self.region.setPlaceholderText("Region") self.user = QLineEdit() self.user.setPlaceholderText("User OCID") self.fingerprint = QLineEdit() self.fingerprint.setPlaceholderText("Fingerprint") self.key_file = QLineEdit() self.key_file.setPlaceholderText("Key File Path") self.passphrase = QLineEdit() self.passphrase.setEchoMode(QLineEdit.Password) self.passphrase.setPlaceholderText("Passphrase") self.save_button = QPushButton('Save') self.save_button.clicked.connect(self.save_signal) #Set the profile to the current_profile passed in upon init self.change_profile(current_profile) self.dropdown.setCurrentText(current_profile) #Add all widgets to a vertical layout self.layout = QVBoxLayout() self.layout.addWidget(self.dropdown) self.layout.addWidget(self.tenancy) self.layout.addWidget(self.region) self.layout.addWidget(self.user) self.layout.addWidget(self.key_file) self.layout.addWidget(self.fingerprint) self.layout.addWidget(self.passphrase) self.layout.addWidget(self.save_button) self.setLayout(self.layout) def get_profiles_dropdown(self): """ :return: A dropdown menu widget that lists all profiles including the default profile from the OCI config file When index changes, it will call the change_profile signal function :rtype: :class: 'Qt.QtWidgets.QComboBox' """ dropdown = QComboBox() dropdown.addItems(['DEFAULT'] + self.config.sections()) dropdown.addItem("Add New Profile...") dropdown.currentIndexChanged.connect(self.change_profile_signal) return dropdown def change_profile_signal(self, item): """ Slot to change profile. If the item index is at 0, then it is the default profile. If it is the last index, then that means create a new profile :param item: The index of the item from the dropdown widget :type item: int """ if item > len(self.config.sections()): self.create_new_profile() elif item == 0: self.change_profile('DEFAULT') else: self.change_profile(self.config.sections()[item - 1]) def change_profile(self, profile_name): """ Changes the profile that the ConfigWindow is set for and also changes it for the MainWindow :param profile_name: the name of the profile to switch to :type profile_name: string TODO: Adhere to signal/slot convention """ self.current_profile = profile_name profile = self.config[profile_name] for line, key in zip([self.tenancy, self.region, self.user, self.fingerprint, self.key_file, self.passphrase],\ ['tenancy', 'region', 'user', 'fingerprint', 'key_file', 'pass_phrase']): if key in profile: line.setText(profile[key]) else: line.setText("") if self.main_window: self.main_window.change_profile(self.current_profile) def create_new_profile(self): """ Layout to create a new profile. Removes the dropdown widget and changes the buttons """ self.layout.removeItem(self.layout.itemAt(0)) self.dropdown.setParent(None) self.new_profile_name = QLineEdit() self.new_profile_name.setPlaceholderText("Profile Name") self.layout.insertWidget(0, self.new_profile_name) self.tenancy.setText("") self.region.setText("") self.user.setText("") self.fingerprint.setText("") self.key_file.setText("") self.passphrase.setText("") self.create_button = QPushButton('Create') self.create_button.clicked.connect(self.create_signal) self.cancel_button = QPushButton('Cancel') self.cancel_button.clicked.connect(self.cancel_signal) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.addButton(self.create_button, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.cancel_button, QDialogButtonBox.ActionRole) self.layout.removeItem(self.layout.itemAt(7)) self.save_button.setParent(None) self.layout.addWidget(self.buttonBox) def create_signal(self): """ Create a new profile with the given information in the LineEdit widgets. Saves to the OCI config file """ profile_name = self.new_profile_name.text() self.config[profile_name] = {} self.config[profile_name]['tenancy'] = self.tenancy.text() self.config[profile_name]['region'] = self.region.text() self.config[profile_name]['user'] = self.user.text() self.config[profile_name]['fingerprint'] = self.fingerprint.text() self.config[profile_name]['key_file'] = self.key_file.text() self.config[profile_name]['pass_phrase'] = self.passphrase.text() with open(self.DEFAULT_LOCATION, 'w') as configfile: self.config.write(configfile) self.current_profile = profile_name self.cancel_signal() def save_signal(self): """ Saves edits on a currently existing profile. Saves to the OCI config file """ self.config[self.current_profile]['tenancy'] = self.tenancy.text() self.config[self.current_profile]['region'] = self.region.text() self.config[self.current_profile]['user'] = self.user.text() self.config[ self.current_profile]['fingerprint'] = self.fingerprint.text() self.config[self.current_profile]['key_file'] = self.key_file.text() self.config[ self.current_profile]['pass_phrase'] = self.passphrase.text() with open(self.DEFAULT_LOCATION, 'w') as configfile: self.config.write(configfile) def cancel_signal(self): """ Cancels the creation a new profile and reverts layout to default layout """ self.layout.removeItem(self.layout.itemAt(0)) self.new_profile_name.setParent(None) self.dropdown = self.get_profiles_dropdown() self.layout.insertWidget(0, self.dropdown) self.layout.removeItem(self.layout.itemAt(7)) self.buttonBox.setParent(None) self.change_profile(self.current_profile) self.dropdown.setCurrentText(self.current_profile) self.layout.addWidget(self.save_button)
class TTVSetsImporterWidget(QWidget): ttv_updated = Signal(TTVSets) def __init__( self, format_to_widget, parent: "QWidget" = None, ): super().__init__(parent) # Components self._ttv = None # Maps a with its respective Widget self._format_to_widget = format_to_widget self._stacked_widgets = QStackedWidget() self._name_textbox = QLineEdit("Unnamed") self._formatter_selector = QComboBox() for (dataset_io_name, widget_factory) in self._format_to_widget.items(): self._formatter_selector.addItem( dataset_io_name, getattr(DatasetIORegistry, dataset_io_name)) self._stacked_widgets.addWidget( self._format_to_widget[dataset_io_name]()) def horizontal_line(): line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) line.setFixedHeight(2) line.setContentsMargins(0, 30, 0, 0) return line self._x_datatype_selector = DatatypeSelectorFactory( title="X (Input) Datatype") self._y_datatype_selector = DatatypeSelectorFactory( title="Y (Output) Datatype") datatypes_layout = QHBoxLayout() datatypes_layout.addWidget(self._x_datatype_selector) datatypes_layout.addWidget(self._y_datatype_selector) self._info_layout = QFormLayout() self._info_layout.addRow("Name", self._name_textbox) self._info_layout.addRow("Format", self._formatter_selector) self._main_layout = QVBoxLayout() self._main_layout.addLayout(self._info_layout) self._main_layout.addWidget(horizontal_line()) self._main_layout.addWidget(self._stacked_widgets) self._main_layout.addWidget(horizontal_line()) self._main_layout.addLayout(datatypes_layout) self._load_ttv_from_file_button = QPushButton("Load from file...") self._load_ttv_from_file_button.clicked.connect( self._load_ttv_from_file) self._update_ttv_button = QPushButton("Load TTV") self._update_ttv_button.clicked.connect(self._update_ttv) self._button_box = QDialogButtonBox() self._button_box.addButton(self._load_ttv_from_file_button, QDialogButtonBox.ResetRole) self._button_box.addButton(self._update_ttv_button, QDialogButtonBox.ApplyRole) self._main_layout.addWidget(self._button_box) self.setLayout(self._main_layout) self._formatter_selector.currentIndexChanged[int].connect( lambda i: self._stacked_widgets.setCurrentIndex(i)) def get_ttv(self) -> "TTVSets": return self._ttv def _update_ttv(self): self._ttv = self._stacked_widgets.currentWidget().load_ttv( self._name_textbox.text(), self._x_datatype_selector.selected_datatype, self._y_datatype_selector.selected_datatype, ) self.ttv_updated.emit(self._ttv) def _load_ttv_from_file(self): print("Loading from file...") description_file_path = QFileDialog.getOpenFileName( self, "Open TTV .json file")[0] if description_file_path: LOGGER.debug("Loading %s...", description_file_path) ttv_dir = os.path.dirname(description_file_path) ttv_description = TTVSetsIO.load_ttv_description( description_file_path) # Update name self._name_textbox.setText(ttv_description["name"]) # Pick the new formatter formatter_idx = self._formatter_selector.findText( ttv_description["format"]) if formatter_idx != -1: self._formatter_selector.setCurrentIndex(formatter_idx) self._selected_index_changed(formatter_idx) # TODO: Cover case when "train" is null self._x_datatype_selector.change_current_datatype( ttv_description["train"]["x_type"]) self._y_datatype_selector.change_current_datatype( ttv_description["train"]["y_type"]) self._stacked_widgets.currentWidget().update_widgets( ttv_dir, ttv_description) self._update_ttv() else: LOGGER.debug("Loading cancelled") def _selected_index_changed(self, index: int): self._stacked_widgets.setCurrentIndex(index) def sizeHint(self) -> "QSize": """Optimal size of the widget.""" return QSize(450, 150) def __reduce__(self): return ( TTVSetsImporterWidget, (self._ttv_sets_dialog, None), )
class PlainTextFindReplaceDialog(QDialog): """ Modeless, stay-above-parent dialog that supports find and replace. Allows for searching case (in)sensitively, and whole-word. Find triggered by Enter / Shift+Enter, or corresponding button (Next / Previous), or if Replace clicked before Next / Previous. Find wraps. Highlights all matches, operating on the closest-to-user's-cursor selection first, in the user-selected direction (Next / Previous). Highlighting / found cursors retained on navigation back to text editor, and cleared on re-find/replace if user modified the document. Presents an info label (e.g. "x of y", "No matches found", ...) While no members have a leading underscore, the only explicit public interface is the static method `find_all`. I couldn't find a reason to need to interface with anything in here, so I didn't differentiate everything as "private". """ def __init__(self, plain_text_edit: QPlainTextEdit, parent=None): """ Sets up the dialog. :param plain_text_edit: Text Editor to operate on. :param parent: QWidget parent """ super().__init__(parent=parent, f=Qt.Tool) self.plain_text_edit = plain_text_edit self.cursors_needed = True self.find_flags = QTextDocument.FindFlags() self.found_cursors: List[QTextCursor] = [] self.current_cursor = QTextCursor() # UI layout = QVBoxLayout() find_and_replace_layout = QGridLayout() layout.addLayout( find_and_replace_layout ) # if QGL is sub-layout, add to parent layout before doing stuff. self.find_line_edit = QLineEdit() find_label = QLabel("&Find") find_label.setBuddy(self.find_line_edit) options_layout = QHBoxLayout() self.match_case_check_box = QCheckBox("Match Case") self.whole_word_check_box = QCheckBox("Whole Word") options_layout.addWidget(self.match_case_check_box) options_layout.addWidget(self.whole_word_check_box) options_layout.addStretch() self.found_info_label = QLabel() self.replace_line_edit = QLineEdit() replace_label = QLabel("&Replace") replace_label.setBuddy(self.replace_line_edit) find_and_replace_layout.addWidget(find_label, 0, 0) find_and_replace_layout.addWidget(self.find_line_edit, 0, 1) find_and_replace_layout.addLayout(options_layout, 1, 1) find_and_replace_layout.setRowMinimumHeight(2, 20) find_and_replace_layout.addWidget(self.found_info_label, 2, 1) find_and_replace_layout.addWidget(replace_label, 3, 0) find_and_replace_layout.addWidget(self.replace_line_edit, 3, 1) self.btn_box = QDialogButtonBox(QDialogButtonBox.Close) self.find_next_btn = QPushButton("Next") self.find_next_btn.setEnabled(False) self.find_prev_btn = QPushButton("Previous") self.find_prev_btn.setEnabled(False) self.replace_btn = QPushButton("Replace") self.replace_btn.setEnabled(False) self.replace_all_btn = QPushButton("Replace All") self.replace_all_btn.setEnabled(False) self.btn_box.addButton(self.replace_btn, QDialogButtonBox.ActionRole) self.btn_box.addButton(self.replace_all_btn, QDialogButtonBox.ActionRole) self.btn_box.addButton(self.find_prev_btn, QDialogButtonBox.ActionRole) self.btn_box.addButton(self.find_next_btn, QDialogButtonBox.ActionRole) layout.addWidget(self.btn_box) self.setLayout(layout) # End UI self.btn_box.rejected.connect(self.reject) self.find_line_edit.textEdited.connect(self.handle_text_edited) self.find_next_btn.clicked.connect(self.next) self.find_prev_btn.clicked.connect(self.prev) self.replace_btn.clicked.connect(self.replace) self.replace_all_btn.clicked.connect(self.replace_all) self.plain_text_edit.document().contentsChanged.connect( self.set_cursors_needed_true) self.whole_word_check_box.stateChanged.connect( self.toggle_whole_word_flag) self.match_case_check_box.stateChanged.connect( self.toggle_match_case_flag) # SLOTS def next(self): """ Finds all matches to the user's search. First highlight after cursor. Consecutive calls advance through matches. If there are matches or not, it says so. The user's cursor advances along with the current selection. Loops back to start after the last match. :return: Side effect: Highlights all matches, differentiating (maybe moving fwd) the current selection. """ if self.cursors_needed: self.init_find() if not self.found_cursors: self.found_info_label.setText("No matches found") self.found_info_label.repaint() return if self.current_cursor >= self.found_cursors[ -1]: # loop back to start. cursor equality based on position. self.current_cursor = self.found_cursors[0] else: for cur in self.found_cursors: if cur > self.current_cursor: # next in order self.current_cursor = cur break self.update_visuals() def prev(self): """ Finds all matches to user's search. First highlight before cursor. Consecutive calls retreat through matches. If there are matches or not, it says so. The user's cursor moves along with the current selection. Loops back to end after the last (first in doc) match. :return: Side effect: Highlights all matches, differentiating (maybe moving back) the current selection. """ if self.cursors_needed: self.init_find() if not self.found_cursors: self.found_info_label.setText("No matches found") self.found_info_label.repaint() return if self.current_cursor <= self.found_cursors[0]: # loop back to end. self.current_cursor = self.found_cursors[-1] else: for cur in reversed(self.found_cursors): if cur < self.current_cursor: # prev in order self.current_cursor = cur break self.update_visuals() def replace(self): """ Replaces the word under focus by `next`. Replaces with the Replace line edit's text, and advances to next word. If no word under focus via this dialog, calls `next`. :return: Side effect: replaces word in text edit """ if self.cursors_needed: self.next() return if not self.found_cursors: return self.plain_text_edit.document().contentsChanged.disconnect( self.set_cursors_needed_true) # don't dup work. self.current_cursor.insertText(self.replace_line_edit.text()) self.plain_text_edit.document().contentsChanged.connect( self.set_cursors_needed_true) self.found_cursors.remove(self.current_cursor) self.next() def replace_all(self): """ Replaces all instances of Find's text with Replace's text. :return: Side effect: replaces words in text edit. Indicates success to user via info label on dialog. """ if self.cursors_needed: self.init_find() for cur in self.found_cursors: cur.insertText(self.replace_line_edit.text()) self.found_info_label.setText("Made {} replacements".format( len(self.found_cursors))) self.found_info_label.repaint() def handle_text_edited(self, text): """ Modifies button states, clears info text, and sets self.cursors_needed to True. :param text: The find_line_edit's text. :return: Side effect: btn enabled / default """ self.found_info_label.clear() self.cursors_needed = True find_enabled = text != "" self.find_next_btn.setEnabled(find_enabled) self.find_prev_btn.setEnabled(find_enabled) self.replace_btn.setEnabled(find_enabled) self.replace_all_btn.setEnabled(find_enabled) self.find_next_btn.setDefault(find_enabled) self.btn_box.button( QDialogButtonBox.Close).setDefault(not find_enabled) def set_cursors_needed_true(self): self.cursors_needed = True def toggle_match_case_flag(self, state: int): self.found_info_label.clear( ) # User will be performing a new search upon toggle, so want this reset. self.cursors_needed = True if state == Qt.Unchecked: self.find_flags &= ~QTextDocument.FindCaseSensitively elif state == Qt.Checked: self.find_flags |= QTextDocument.FindCaseSensitively def toggle_whole_word_flag(self, state: int): self.found_info_label.clear( ) # User will be performing a new search upon toggle, so want this reset. self.cursors_needed = True if state == Qt.Unchecked: self.find_flags &= ~QTextDocument.FindWholeWords elif state == Qt.Checked: self.find_flags |= QTextDocument.FindWholeWords # END SLOTS def init_find(self): """Sets up internal state for the case when cursors are needed (e.g. first find, user modifies doc...)""" self.found_cursors = self.find_all(self.find_line_edit.text(), self.plain_text_edit.document(), self.find_flags) self.cursors_needed = False self.current_cursor = self.plain_text_edit.textCursor( ) # returns copy of self.plain_text_edit.setExtraSelections([]) def update_visuals(self): """ Moves text editor's cursor to match currently highlighted `find` word, performs `find` highlighting, indicates index on dialog. """ # x of y words indicator idx = self.found_cursors.index(self.current_cursor) + 1 self.found_info_label.setText("{} of {} matches".format( idx, len(self.found_cursors))) self.found_info_label.repaint() # move along text editor's viewport next_pte_cursor = QTextCursor(self.current_cursor) next_pte_cursor.clearSelection() self.plain_text_edit.setTextCursor(next_pte_cursor) #highlighting normal_color = QColor(Qt.yellow).lighter() current_color = QColor(Qt.magenta).lighter() extra_selections: List[QTextEdit.ExtraSelection] = [] for cur in self.found_cursors: selection = QTextEdit.ExtraSelection() selection.cursor = cur if cur == self.current_cursor: selection.format.setBackground(current_color) else: selection.format.setBackground(normal_color) extra_selections.append(selection) self.plain_text_edit.setExtraSelections(extra_selections) @staticmethod def find_all( text: str, document: QTextDocument, flags=QTextDocument.FindFlags() ) -> List[QTextCursor]: """ Finds all occurrences of `text` in `document`, in order. :param text: Text to find. :param document: Document to search. :param flags: Conditions to set on the search: none or (whole word and/or match case) :return: Ordered list of all found instances. """ cursor = QTextCursor(document) # default pos == 0 found: List[QTextCursor] = [] while True: cursor = document.find(text, cursor, flags) if cursor.isNull(): return found else: found.append(cursor) def done(self, arg__1: int): self.plain_text_edit.setExtraSelections([]) super().done(arg__1) def keyPressEvent(self, arg__1: QKeyEvent): # Shift+Enter triggers find previous, if the corresponding btn is enabled. if (arg__1.key() in [Qt.Key_Return, Qt.Key_Enter] and arg__1.modifiers() == Qt.ShiftModifier and self.find_prev_btn.isEnabled()): self.prev() else: super().keyPressEvent(arg__1)
class Dialog(QDialog): def __init__(self): super(Dialog, self).__init__() self.rotableWidgets = [] self.createRotableGroupBox() self.createOptionsGroupBox() self.createButtonBox() mainLayout = QGridLayout() mainLayout.addWidget(self.rotableGroupBox, 0, 0) mainLayout.addWidget(self.optionsGroupBox, 1, 0) mainLayout.addWidget(self.buttonBox, 2, 0) mainLayout.setSizeConstraint(QLayout.SetMinimumSize) self.mainLayout = mainLayout self.setLayout(self.mainLayout) self.setWindowTitle("Dynamic Layouts") def rotateWidgets(self): count = len(self.rotableWidgets) if count % 2 == 1: raise AssertionError("Number of widgets must be even") for widget in self.rotableWidgets: self.rotableLayout.removeWidget(widget) self.rotableWidgets.append(self.rotableWidgets.pop(0)) for i in range(count//2): self.rotableLayout.addWidget(self.rotableWidgets[count - i - 1], 0, i) self.rotableLayout.addWidget(self.rotableWidgets[i], 1, i) def buttonsOrientationChanged(self, index): self.mainLayout.setSizeConstraint(QLayout.SetNoConstraint) self.setMinimumSize(0, 0) orientation = Qt.Orientation(int(self.buttonsOrientationComboBox.itemData(index))) if orientation == self.buttonBox.orientation(): return self.mainLayout.removeWidget(self.buttonBox) spacing = self.mainLayout.spacing() oldSizeHint = self.buttonBox.sizeHint() + QSize(spacing, spacing) self.buttonBox.setOrientation(orientation) newSizeHint = self.buttonBox.sizeHint() + QSize(spacing, spacing) if orientation == Qt.Horizontal: self.mainLayout.addWidget(self.buttonBox, 2, 0) self.resize(self.size() + QSize(-oldSizeHint.width(), newSizeHint.height())) else: self.mainLayout.addWidget(self.buttonBox, 0, 3, 2, 1) self.resize(self.size() + QSize(newSizeHint.width(), -oldSizeHint.height())) self.mainLayout.setSizeConstraint(QLayout.SetDefaultConstraint) def show_help(self): QMessageBox.information(self, "Dynamic Layouts Help", "This example shows how to change layouts " "dynamically.") def createRotableGroupBox(self): self.rotableGroupBox = QGroupBox("Rotable Widgets") self.rotableWidgets.append(QSpinBox()) self.rotableWidgets.append(QSlider()) self.rotableWidgets.append(QDial()) self.rotableWidgets.append(QProgressBar()) count = len(self.rotableWidgets) for i in range(count): self.rotableWidgets[i].valueChanged[int].\ connect(self.rotableWidgets[(i+1) % count].setValue) self.rotableLayout = QGridLayout() self.rotableGroupBox.setLayout(self.rotableLayout) self.rotateWidgets() def createOptionsGroupBox(self): self.optionsGroupBox = QGroupBox("Options") buttonsOrientationLabel = QLabel("Orientation of buttons:") buttonsOrientationComboBox = QComboBox() buttonsOrientationComboBox.addItem("Horizontal", Qt.Horizontal) buttonsOrientationComboBox.addItem("Vertical", Qt.Vertical) buttonsOrientationComboBox.currentIndexChanged[int].connect(self.buttonsOrientationChanged) self.buttonsOrientationComboBox = buttonsOrientationComboBox optionsLayout = QGridLayout() optionsLayout.addWidget(buttonsOrientationLabel, 0, 0) optionsLayout.addWidget(self.buttonsOrientationComboBox, 0, 1) optionsLayout.setColumnStretch(2, 1) self.optionsGroupBox.setLayout(optionsLayout) def createButtonBox(self): self.buttonBox = QDialogButtonBox() closeButton = self.buttonBox.addButton(QDialogButtonBox.Close) helpButton = self.buttonBox.addButton(QDialogButtonBox.Help) rotateWidgetsButton = self.buttonBox.addButton("Rotate &Widgets", QDialogButtonBox.ActionRole) rotateWidgetsButton.clicked.connect(self.rotateWidgets) closeButton.clicked.connect(self.close) helpButton.clicked.connect(self.show_help)