コード例 #1
0
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignCenter)

        self.file_selector = Path_selector('file')
        self.folder_selector = Path_selector('folder')
        self.file_selector.setFixedSize(500, 40)
        self.folder_selector.setFixedSize(500, 40)

        layout.addWidget(self.file_selector)
        layout.addWidget(self.folder_selector)

        button = QPushButton("Execute")
        button.clicked.connect(self.handleExecute)
        button.setFixedSize(100, 40)

        layout.addWidget(button, alignment=Qt.AlignCenter)

        button_rev = QPushButton("Backwards")
        button_rev.clicked.connect(self.handleBackwards)
        button_rev.setFixedSize(100, 40)

        layout.addWidget(button_rev, alignment=Qt.AlignCenter)
コード例 #2
0
    def PreviewWindow(self):

        self.statusBar().showMessage('Tablecloth preview generated.')
        self.statusBar().removeWidget(self.progress_bar)
        # Now you can go back to rigging
        self.ChangeAppStatus(True)

        self.preview_wid = QWidget()
        self.preview_wid.resize(600, 600)
        self.preview_wid.setWindowTitle("Tablecloth preview")

        tablecloth = QPixmap(tempfile.gettempdir()+"\\Table_Dif.jpg")

        tablecloth_preview_title = QLabel(self)
        tablecloth_preview_title.setText("Tablecloth preview (1/4 scale)")
        tablecloth_preview = QLabel(self)
        tablecloth_preview.setPixmap(tablecloth.scaled(512,512))
        confirm = QPushButton(self)
        confirm.setText("Confirm")
        confirm.clicked.connect(self.GenerateImage)
        confirm.clicked.connect(self.preview_wid.close)

        vbox = QVBoxLayout()
        vbox.setAlignment(QtCore.Qt.AlignCenter)
        vbox.addWidget(tablecloth_preview_title)
        vbox.addWidget(tablecloth_preview)
        vbox.addWidget(confirm)
        self.preview_wid.setLayout(vbox)

        self.preview_wid.setWindowModality(QtCore.Qt.ApplicationModal)
        self.preview_wid.activateWindow()
        self.preview_wid.raise_()
        self.preview_wid.show()
コード例 #3
0
class AboutDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.main_layout = None
        self.setWindowTitle("关于")
        self.setWindowIcon(GMakeIcon(GRes.app_icon_ico))
        self.setFixedSize(320, 240)
        self.setup_ui()

    def setup_ui(self):
        self.main_layout = QVBoxLayout()
        self.main_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
        self.setLayout(self.main_layout)

        name = '<a href="%s"><b><font size="4" color="#333">%s</font></b></a>' % (Globals.repo, Globals.app_name)
        version = '<b><font size="3" color="#333">版本:</font></b>%s' % Globals.version
        author = '<b><font size="3" color="#333">作者:</font></b>%s' % Globals.author
        tech = '<b><font size="3" color="#333">技术:</font></b>'
        name_lab = QLabel(name)
        name_lab.setOpenExternalLinks(True)
        self.main_layout.addWidget(name_lab)
        self.main_layout.addWidget(QLabel(version))
        self.main_layout.addWidget(QLabel(author))
        self.main_layout.addWidget(QLabel(tech))
        for t in Globals.tech.split('\n'):
            self.main_layout.addWidget(QLabel('<font color="#444">  %s</font>' % t))
コード例 #4
0
    def _add_widget_for_requirement_array(self, requirement: Requirement):
        self.grid_layout.setAlignment(Qt.AlignTop)

        parents: List[Tuple[QGroupBox,
                            QVBoxLayout]] = [(self.parent, self.grid_layout)]

        for depth, text in randovania.game_description.pretty_print.pretty_print_requirement(
                requirement):
            if "of the following" in text:
                parent = parents[depth]
                group_box = QGroupBox(parent[0])
                group_box.setContentsMargins(8, 0, 2, 6)
                group_box.setTitle(text)
                self._elements.append(group_box)
                vertical_layout = QVBoxLayout(group_box)
                vertical_layout.setAlignment(Qt.AlignTop)
                parent[1].addWidget(group_box)
                if len(parents) <= depth + 1:
                    parents.append(None)
                parents[depth + 1] = (group_box, vertical_layout)
            else:
                label = QLabel(parents[depth][0])

                # This is a comment!
                if text.startswith("# "):
                    text = re.sub(r"(https?://[^\s]+)", r'<a href="\1">\1</a>',
                                  text[2:])
                    label.setStyleSheet("font-weight: bold; color: green")
                    label.setOpenExternalLinks(True)

                label.setText(text)
                label.setWordWrap(True)
                self._elements.append(label)
                parents[depth][1].addWidget(label)
コード例 #5
0
ファイル: poc.py プロジェクト: PentheusLennuye/jp2
class Card(QDialog):
    def __init__(self, title, instructions, questions, answers, parent=None):
        super().__init__(parent)
        self.questions = questions
        self.answers = answers
        self.index = 0
        self.mode = POSING_QUESTION
        self.button_labels = ['答え', '次の質問']
        self.last_question = len(self.questions) - 1
        self.setWindowTitle('日本語の練習')

        self.title = Title(title, self)
        self.instructions = Instructions(instructions, self)
        self.playfield = Playfield(self.questions[self.index],
                                   self.answers[self.index], self)
        self.playfield.hide_answer()
        self.controls = Controls(self, self.button_labels[self.mode],
                                 self.move_forward, self.quit_me)
        self.layout = QVBoxLayout()
        self.set_layout()

    def set_layout(self):

        self.layout.takeAt(0)
        self.layout.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.title)
        self.layout.addWidget(self.instructions)
        self.layout.addWidget(self.playfield)
        self.layout.addWidget(self.controls)
        self.setLayout(self.layout)

    @Slot()
    def move_forward(self):
        if self.mode == POSING_QUESTION:
            self.mode = SHOWING_ANSWER
            self.show_answer()
        else:
            self.mode = POSING_QUESTION
            self.pose_next_question()

    def pose_next_question(self):
        self.index += 1
        self.playfield.setParent(None)
        self.playfield = Playfield(self.questions[self.index],
                                   self.answers[self.index], self)
        self.playfield.hide_answer()
        self.controls.set_button(self.button_labels[self.mode])
        self.set_layout()

    def show_answer(self):
        self.playfield.show_answer()
        if self.index < self.last_question:
            self.controls.set_button(self.button_labels[self.mode])
        else:
            self.controls.hide_button()

    @Slot()
    def quit_me(self):
        QCoreApplication.instance().quit()
コード例 #6
0
ファイル: card.py プロジェクト: PentheusLennuye/jp2
    def __init__(self, question, answer, parent):
        super().__init__(parent)
        self.qwidget = PlayfieldSection(question, self)
        self.awidget = PlayfieldSection(answer, self)

        playfield_layout = QVBoxLayout()
        playfield_layout.setAlignment(Qt.AlignCenter)
        playfield_layout.addWidget(self.qwidget)
        playfield_layout.addWidget(self.awidget)
        self.setLayout(playfield_layout)
コード例 #7
0
class SyncWidget(QWidget):

    Sg_view_changed = Signal()

    def __init__(self, model: SyncModel, parent=None):
        super(SyncWidget, self).__init__(parent)

        self._model = model

        self.watch_label = QLabel(self)
        self.watch_label.setAlignment(Qt.AlignCenter)
        self.watch_label.setText("SYNC")
        self.watch_label.setAccessibleName("Title")

        self.running_label = QLabel(self)
        self.running_label.setAlignment(Qt.AlignCenter)
        self.running_label.setText("Disattivata")
        self.running_label.setAccessibleName("Subtitle")

        self.sync_button = QPushButton(self)
        self.sync_button.setIcon(QIcon(resource_path('icons/reload.png')))
        self.sync_button.setIconSize(QSize(50, 50))
        self.sync_button.setCheckable(True)
        self.sync_button.setAccessibleName('HighlightButton')

        self.menu_label = QLabel(self)
        self.menu_label.setAlignment(Qt.AlignCenter)
        self.menu_label.setText("• • •")

        # create layout
        self.layout = QVBoxLayout()
        self.layout.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.watch_label)
        self.layout.addWidget(self.running_label)
        self.layout.addWidget(self.sync_button)
        self.layout.addWidget(self.menu_label)
        self.setLayout(self.layout)

        self.sync_button.clicked.connect(self.Sl_button_clicked)
        self.Sl_model_changed()

    @Slot()
    def Sl_button_clicked(self):
        self.Sg_view_changed.emit()

    @Slot()
    def Sl_model_changed(self):
        self.sync_button.setChecked(self._model.get_state())
        if self._model.get_state():
            self.running_label.setText("Attivata")
        else:
            self.running_label.setText("Disattivata")
コード例 #8
0
    def __init__(self, parent: QWidget, model: Model) -> None:
        super().__init__(parent)

        logger.add(self.log)

        settings = QSettings()
        self.mainlayout = QVBoxLayout()
        self.mainlayout.setContentsMargins(5, 5, 5, 5)
        self.setLayout(self.mainlayout)

        # summary

        summarylayout = FlowLayout()
        summarylayout.setContentsMargins(0, 0, 0, 0)
        self.summary = QWidget()
        self.summary.setLayout(summarylayout)
        self.mainlayout.addWidget(self.summary)
        self.summary.setVisible(
            settings.value('showSummary', 'True') == 'True')

        detailslayout = QHBoxLayout()
        detailslayout.setContentsMargins(1, 0, 0, 0)
        detailslayout.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        detailslayout.setSpacing(15)
        details = QWidget()
        details.setLayout(detailslayout)
        summarylayout.addWidget(details)

        self.modstotal = QLabel()
        detailslayout.addWidget(self.modstotal)
        self.modsenabled = QLabel()
        detailslayout.addWidget(self.modsenabled)
        self.overridden = QLabel()
        detailslayout.addWidget(self.overridden)
        self.conflicts = QLabel()
        detailslayout.addWidget(self.conflicts)

        buttonslayout = QHBoxLayout()
        buttonslayout.setContentsMargins(0, 0, 0, 0)
        buttonslayout.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        buttons = QWidget()
        buttons.setLayout(buttonslayout)
        summarylayout.addWidget(buttons)

        self.startscriptmerger = QPushButton('Start Script Merger')
        self.startscriptmerger.setContentsMargins(0, 0, 0, 0)
        self.startscriptmerger.setMinimumWidth(140)
        self.startscriptmerger.setIcon(
            QIcon(str(getRuntimePath('resources/icons/script.ico'))))
        self.startscriptmerger.clicked.connect(lambda: [
            openExecutable(Path(str(settings.value('scriptMergerPath'))), True)
        ])
        self.startscriptmerger.setEnabled(
            verifyScriptMergerPath(
                Path(str(settings.value('scriptMergerPath')))) is not None)
        buttonslayout.addWidget(self.startscriptmerger)

        self.startgame = QPushButton('Start Game')
        self.startgame.setContentsMargins(0, 0, 0, 0)
        self.startgame.setMinimumWidth(100)
        self.startgame.setIcon(
            QIcon(str(getRuntimePath('resources/icons/w3b.ico'))))
        buttonslayout.addWidget(self.startgame)

        # splitter

        self.splitter = QSplitter(Qt.Vertical)

        self.stack = QStackedWidget()
        self.splitter.addWidget(self.stack)

        # mod list widget

        self.modlistwidget = QWidget()
        self.modlistlayout = QVBoxLayout()
        self.modlistlayout.setContentsMargins(0, 0, 0, 0)
        self.modlistwidget.setLayout(self.modlistlayout)
        self.stack.addWidget(self.modlistwidget)

        # search bar

        self.searchbar = QLineEdit()
        self.searchbar.setPlaceholderText('Search...')
        self.modlistlayout.addWidget(self.searchbar)

        # mod list

        self.modlist = ModList(self, model)
        self.modlistlayout.addWidget(self.modlist)

        self.searchbar.textChanged.connect(lambda e: self.modlist.setFilter(e))

        # welcome message

        welcomelayout = QVBoxLayout()
        welcomelayout.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        welcomewidget = QWidget()
        welcomewidget.setLayout(welcomelayout)
        welcomewidget.dragEnterEvent = self.modlist.dragEnterEvent  # type: ignore
        welcomewidget.dragMoveEvent = self.modlist.dragMoveEvent  # type: ignore
        welcomewidget.dragLeaveEvent = self.modlist.dragLeaveEvent  # type: ignore
        welcomewidget.dropEvent = self.modlist.dropEvent  # type: ignore
        welcomewidget.setAcceptDrops(True)

        icon = QIcon(str(getRuntimePath('resources/icons/open-folder.ico')))
        iconpixmap = icon.pixmap(32, 32)
        icon = QLabel()
        icon.setPixmap(iconpixmap)
        icon.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        icon.setContentsMargins(4, 4, 4, 4)
        welcomelayout.addWidget(icon)

        welcome = QLabel('''<p><font>
            No mod installed yet.
            Drag a mod into this area to get started!
            </font></p>''')
        welcome.setAttribute(Qt.WA_TransparentForMouseEvents)
        welcome.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        welcomelayout.addWidget(welcome)

        self.stack.addWidget(welcomewidget)

        # output log

        self.output = QTextEdit(self)
        self.output.setTextInteractionFlags(Qt.NoTextInteraction)
        self.output.setReadOnly(True)
        self.output.setContextMenuPolicy(Qt.NoContextMenu)
        self.output.setPlaceholderText('Program output...')
        self.splitter.addWidget(self.output)

        # TODO: enhancement: show indicator if scripts have to be merged

        self.splitter.setStretchFactor(0, 1)
        self.splitter.setStretchFactor(1, 0)
        self.mainlayout.addWidget(self.splitter)

        # TODO: incomplete: make start game button functional

        if len(model):
            self.stack.setCurrentIndex(0)
            self.splitter.setSizes([self.splitter.size().height(), 50])
        else:
            self.stack.setCurrentIndex(1)
            self.splitter.setSizes([self.splitter.size().height(), 0])
        model.updateCallbacks.append(self.modelUpdateEvent)

        asyncio.create_task(model.loadInstalled())
コード例 #9
0
class ArrayRequirementEditor:
    def __init__(self, parent: QWidget, parent_layout: QVBoxLayout,
                 line_layout: QHBoxLayout, resource_database: ResourceDatabase,
                 requirement: RequirementArrayBase):
        self._editors = []
        self.resource_database = resource_database
        self._array_type = type(requirement)

        # the parent is added to a layout which is added to parent_layout, so we
        index = parent_layout.indexOf(line_layout) + 1

        self.group_box = QGroupBox(parent)
        self.group_box.setStyleSheet("QGroupBox { margin-top: 2px; }")
        parent_layout.insertWidget(index, self.group_box)
        self.item_layout = QVBoxLayout(self.group_box)
        self.item_layout.setContentsMargins(8, 2, 2, 6)
        self.item_layout.setAlignment(Qt.AlignTop)

        self.new_item_button = QPushButton(self.group_box)
        self.new_item_button.setMaximumWidth(75)
        self.new_item_button.setText("New Row")
        self.new_item_button.clicked.connect(self.new_item)

        self.comment_text_box = QLineEdit(parent)
        self.comment_text_box.setText(requirement.comment or "")
        self.comment_text_box.setPlaceholderText("Comment")
        line_layout.addWidget(self.comment_text_box)

        for item in requirement.items:
            self._create_item(item)

        self.item_layout.addWidget(self.new_item_button)

    def _create_item(self, item: Requirement):
        def on_remove():
            self._editors.remove(nested_editor)
            nested_editor.deleteLater()

        nested_editor = RequirementEditor(self.group_box,
                                          self.item_layout,
                                          self.resource_database,
                                          on_remove=on_remove)
        nested_editor.create_specialized_editor(item)
        self._editors.append(nested_editor)

    def new_item(self):
        self._create_item(
            _create_default_resource_requirement(self.resource_database))

        self.item_layout.removeWidget(self.new_item_button)
        self.item_layout.addWidget(self.new_item_button)

    def deleteLater(self):
        self.group_box.deleteLater()
        self.comment_text_box.deleteLater()
        for editor in self._editors:
            editor.deleteLater()
        self.new_item_button.deleteLater()

    @property
    def current_requirement(self) -> RequirementArrayBase:
        comment = self.comment_text_box.text().strip()
        if comment == "":
            comment = None

        return self._array_type(
            [editor.current_requirement for editor in self._editors],
            comment=comment,
        )
コード例 #10
0
class SelectRTSSPopUp(QDialog):
    signal_rtss_selected = QtCore.Signal(Series)

    def __init__(self, existing_rtss, parent=None):
        QDialog.__init__(self, parent=parent)

        if platform.system() == 'Darwin':
            self.stylesheet_path = "res/stylesheet.qss"
        else:
            self.stylesheet_path = "res/stylesheet-win-linux.qss"
        stylesheet = open(resource_path(self.stylesheet_path)).read()
        self.setStyleSheet(stylesheet)

        self.setWindowTitle("Multiple RTSTRUCTs detected!")
        self.setMinimumSize(350, 180)

        self.icon = QtGui.QIcon()
        self.icon.addPixmap(
            QtGui.QPixmap(resource_path("res/images/icon.ico")),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(self.icon)

        self.explanation_text = QLabel("Multiple RTSTRUCTs attached to the "
                                       "selected image set have been "
                                       "identified."
                                       "\nPlease select 1 "
                                       "RTSTRUCTs to continue!")

        # Create scrolling area widget to contain the content.
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)

        self.scroll_area_content = QWidget(self.scroll_area)
        self.scroll_area.ensureWidgetVisible(self.scroll_area_content)

        # Create layout for checkboxes
        self.layout_content = QVBoxLayout(self.scroll_area_content)
        self.layout_content.setContentsMargins(5, 5, 5, 5)
        self.layout_content.setSpacing(0)
        self.layout_content.setAlignment(QtCore.Qt.AlignTop
                                         | QtCore.Qt.AlignTop)

        # Add all the attached RTSSs as checkboxes
        self.checkbox_group = QButtonGroup()
        self.checkbox_group.setExclusive(True)
        for i in range(len(existing_rtss)):
            checkbox = QCheckBox()
            checkbox.rtss = existing_rtss[i]
            rtss = dcmread(checkbox.rtss.get_files()[0])
            checkbox.setFocusPolicy(QtCore.Qt.NoFocus)
            checkbox.setText("Series: %s (%s, %s %s)" % (
                checkbox.rtss.series_description,
                checkbox.rtss.get_series_type(),
                len(rtss.StructureSetROISequence),
                "ROIs" if len(rtss.StructureSetROISequence) > 1 else "ROI"
            ))
            self.checkbox_group.addButton(checkbox)
            self.layout_content.addWidget(checkbox)
        self.checkbox_group.buttonClicked.connect(self.on_checkbox_clicked)

        # Create a cancel button
        self.cancel_button = QPushButton("Cancel")
        self.cancel_button.clicked.connect(self.on_cancel_clicked)

        # Create a continue button
        self.continue_button = QPushButton("Continue Process")
        self.continue_button.setDisabled(True)
        self.continue_button.clicked.connect(self.on_continue_clicked)

        # Create a widget to contain cancel and continue buttons
        self.button_area = QWidget()
        self.button_layout = QHBoxLayout()
        self.button_layout.addWidget(self.cancel_button)
        self.button_layout.addWidget(self.continue_button)
        self.button_area.setLayout(self.button_layout)

        # Add all components to a vertical layout
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.explanation_text)
        self.layout.addWidget(self.scroll_area)
        self.layout.addWidget(self.button_area)
        self.setLayout(self.layout)

    def on_checkbox_clicked(self, checkbox):
        """
        function to set a rtss as the selected rtss
        :param checkbox: the selected QCheckbox that contains a rtss
        """
        self.continue_button.setDisabled(False)
        self.selected_rtss = checkbox.rtss

    def on_continue_clicked(self):
        """
        function to continue the process
        """
        # Emit the selected RTSS
        self.signal_rtss_selected.emit(self.selected_rtss)
        self.close()

    def on_cancel_clicked(self):
        """
        function to cancel the operation
        """
        self.close()
コード例 #11
0
ファイル: TodoList.py プロジェクト: dingzx97/DoItTomorrow
class TodoList(QWidget):
    def __init__(self):
        super().__init__()
        self.items = []
        self.layout = QVBoxLayout()
        self.indent_step = 20

        self.layout.setAlignment(Qt.AlignTop)
        self.setLayout(self.layout)
        self.setWindowTitle("Do it tomorrow !!")
        self.setFocusPolicy(Qt.ClickFocus)

        self.load()
        self.refresh()

    def item_finished_slot(self, index):
        del self.items[index]
        self.update_item_index(index)

    def item_commit_slot(self, index):
        self.add_item(index + 1, self.items[index].level)
        self.update_item_index(index)
        self.refresh()
        self.items[index].clearFocus()
        self.items[index + 1].lineedit.setFocus()
        self.save()

    def item_tab_pressed_slot(self, index):
        if index > 0 and self.items[index].level - self.items[index -
                                                              1].level < 1:
            self.items[index].level += 1
            self.items[index].setContentsMargins(
                self.indent_step * self.items[index].level, 0, 0, 0)

    def load(self):
        try:
            with open('todolist.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
            i = 0
            for one in data:
                if one['text']:
                    self.add_item(i, one['level'], one['text'])
                    i += 1
        except:
            self.add_item(0)
        self.refresh()

    def save(self):
        data = []
        for item in self.items:
            data.append({'level': item.level, 'text': item.lineedit.text()})
        with open('todolist.json', 'w', encoding='utf-8') as f:
            json.dump(data, f)

    def add_item(self, index, level=0, text=None):
        item = Item(index, level, text)
        item.item_finished_signal.connect(self.item_finished_slot)
        item.item_commit_signal.connect(self.item_commit_slot)
        item.item_tab_pressed_signal.connect(self.item_tab_pressed_slot)
        self.items.insert(index, item)

    def update_item_index(self, begin=0):
        for i in range(begin, len(self.items)):
            self.items[i].index = i

    def refresh(self):
        for item in self.items:
            self.layout.addWidget(item)
            if item.level:
                item.setContentsMargins(self.indent_step * item.level, 0, 0, 0)
コード例 #12
0
class ParameterEditor(QWidget):
    onParametersChanged = Signal()

    def __init__(self, program: Program):
        super().__init__()
        self._program = program

        parametersLabel = QLabel("Parameters")
        newParameterButton = QPushButton("Add Parameter")
        newParameterButton.clicked.connect(self.AddParameter)

        layout = QVBoxLayout()
        titleLayout = QHBoxLayout()
        titleLayout.addWidget(parametersLabel)
        titleLayout.addWidget(newParameterButton)
        layout.addLayout(titleLayout)

        self._listArea = QScrollArea()
        self._listArea.setWidgetResizable(True)
        self._listArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self._listArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        layout.addWidget(self._listArea, stretch=1)
        listWidget = QWidget()
        self._itemLayout = QVBoxLayout()
        self._itemLayout.setAlignment(Qt.AlignTop)
        listWidget.setLayout(self._itemLayout)
        self.setLayout(layout)
        self._listArea.setWidget(listWidget)

        self.items: List[ParameterEditorItem] = []

        self._temporaryParameters = program.parameters.copy()

        self.Populate()

    def AddParameter(self):
        newParameter = Parameter()
        self._temporaryParameters.append(newParameter)
        self.onParametersChanged.emit()
        self.AddToList(newParameter)

    def Populate(self):
        for parameter in self._temporaryParameters:
            self.AddToList(parameter)
        self._listArea.updateGeometry()

    def AddToList(self, parameter: Parameter):
        newItem = ParameterEditorItem(parameter)
        newItem.onRemoveParameter.connect(self.RemoveParameter)
        newItem.onMoveParameterUp.connect(self.MoveParameterUp)
        newItem.onMoveParameterDown.connect(self.MoveParameterDown)
        newItem.onChanged.connect(self.onParametersChanged.emit)
        self._itemLayout.addWidget(newItem)
        self.items.append(newItem)

    def RemoveFromList(self, parameter: Parameter):
        item = [item for item in self.items if item.parameter is parameter]
        item[0].deleteLater()
        self.items.remove(item[0])

    def RemoveParameter(self, parameter: Parameter):
        self._temporaryParameters.remove(parameter)
        self.onParametersChanged.emit()
        self.RemoveFromList(parameter)

    def Reorder(self, parameter: Parameter, newPosition: int):
        item = [item for item in self.items if item.parameter is parameter][0]
        self._itemLayout.removeWidget(item)
        self._itemLayout.insertWidget(newPosition, item)
        self.items.remove(item)
        self.items.insert(newPosition, item)
        self._temporaryParameters.remove(parameter)
        self._temporaryParameters.insert(newPosition, parameter)
        self.onParametersChanged.emit()

    def MoveParameterUp(self, parameter: Parameter):
        index = self._temporaryParameters.index(parameter)
        self.Reorder(parameter, index - 1)

    def MoveParameterDown(self, parameter: Parameter):
        index = self._temporaryParameters.index(parameter)
        self.Reorder(parameter, index + 1)

    def Save(self):
        self._program.parameters = self._temporaryParameters
        self._temporaryParameters = self._program.parameters.copy()
        for item in self.items:
            item.UpdateParameter()
コード例 #13
0
class LoginScreen(QDialog):

    Sg_login_success = Signal()
    Sg_login_failure = Signal()

    def __init__(self, model: NetworkModel, parent=None):
        super(LoginScreen, self).__init__(parent)

        # gestione modello
        self.model = model

        # inizializzazione layout
        self.layout = QVBoxLayout()

        # label e field
        self.login_title = QLabel(self)
        self.login_title.setText("Effettua l'accesso")
        self.login_title.setAccessibleName('LoginTitle')

        self.login_label = QLabel(self)
        self.login_label.setText('Username')
        self.login_label.setAccessibleName('LoginLabel')

        self.user_field = QLineEdit(self)

        self.psw_label = QLabel(self)
        self.psw_label.setText('Password')
        self.psw_label.setAccessibleName('LoginLabel')

        self.psw_field = QLineEdit(self)
        self.psw_field.setEchoMode(QLineEdit.Password)

        self.user_field.setText(self.model.get_username())

        # pulsante invio form
        self.login_button = QPushButton(self)
        self.login_button.setText('Login')

        # gestione layout
        self.layout.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.login_title)
        self.layout.addWidget(self.login_label)
        self.layout.addWidget(self.user_field)
        self.layout.addWidget(self.psw_label)
        self.layout.addWidget(self.psw_field)
        self.layout.addWidget(self.login_button)

        self.setLayout(self.layout)
        setQss("style.qss", self)

    @Slot()
    def Sl_model_changed(self):
        is_logged = self.model.is_logged()
        if is_logged:
            self.Sg_login_success.emit()

    def get_user(self) -> str:
        return self.user_field.text()

    def get_psw(self) -> str:
        return self.psw_field.text()

    @Slot()
    def Sl_login_fail(self):
        self.Sg_login_failure.emit()
コード例 #14
0
class MainWidget(TritonWidget):
    def __init__(self, base):
        TritonWidget.__init__(self, base)
        self.addOTP = None
        self.closeEvent = self.widgetDeleted

        self.setWindowTitle('TritonAuth')
        self.setBackgroundColor(self, Qt.white)

        self.menu = QMenuBar()
        self.addMenu = self.menu.addMenu('Add')
        self.authAction = QAction('Authenticator', self)
        self.authAction.triggered.connect(self.openAddOTP)
        self.steamAction = QAction('Steam', self)
        self.steamAction.triggered.connect(self.openAddSteam)

        self.addMenu.addAction(self.authAction)
        self.addMenu.addAction(self.steamAction)

        self.sortMenu = self.menu.addMenu('Sort')
        self.nameAction = QAction('Sort by name', self)
        self.nameAction.triggered.connect(self.sortByName)

        self.sortMenu.addAction(self.nameAction)

        self.exportMenu = self.menu.addMenu('Export')
        self.andOTPAction = QAction('Export to andOTP', self)
        self.andOTPAction.triggered.connect(self.exportToAndOTP)

        self.exportMenu.addAction(self.andOTPAction)

        self.widget = QWidget()
        self.widget.setContentsMargins(10, 10, 10, 10)

        self.scrollArea = QScrollArea()
        self.scrollArea.setFixedSize(400, 495)
        self.scrollArea.setWidgetResizable(True)
        self.scrollWidget = QWidget()
        self.scrollLayout = QVBoxLayout(self.scrollWidget)
        self.scrollLayout.setAlignment(Qt.AlignTop)

        self.createAccounts()

        self.scrollArea.setWidget(self.scrollWidget)

        self.widgetLayout = QVBoxLayout(self.widget)
        self.widgetLayout.addWidget(self.scrollArea)

        self.boxLayout = QVBoxLayout(self)
        self.boxLayout.setContentsMargins(0, 5, 0, 0)
        self.boxLayout.addWidget(self.menu)
        self.boxLayout.addWidget(self.widget)

        self.setFixedSize(self.sizeHint())
        self.center()
        self.show()

    def keyPressEvent(self, event):
        if type(event) != QKeyEvent:
            return

        letter = event.text().strip().lower()

        for i in range(self.scrollLayout.count()):
            widget = self.scrollLayout.itemAt(i).widget()

            if widget is not None and widget.name[0].lower() == letter:
                self.scrollArea.verticalScrollBar().setValue(
                    widget.geometry().top())
                return

    def widgetDeleted(self, arg):
        self.closeAddOTP()

    def closeAddOTP(self):
        if self.addOTP:
            self.addOTP.close()
            self.addOTP = None

    def addAccount(self, account):
        entry = EntryWidget(self.base, account)
        self.scrollLayout.addWidget(entry)

    def deleteAccount(self, account):
        for i in range(self.scrollLayout.count()):
            widget = self.scrollLayout.itemAt(i).widget()

            if widget.account == account:
                widget.close()

    def clearAccounts(self):
        for i in range(self.scrollLayout.count()):
            self.scrollLayout.itemAt(i).widget().close()

    def createAccounts(self):
        for account in self.base.getAccounts():
            self.addAccount(account)

    def openAddOTP(self):
        self.closeAddOTP()
        self.addOTP = AddOTPWidget(self.base)

    def openAddSteam(self):
        self.closeAddOTP()
        self.addOTP = AddSteamWidget(self.base)

    def sortByName(self):
        self.base.sortAccountsByName()
        self.clearAccounts()
        self.createAccounts()

    def exportToAndOTP(self):
        accounts = []

        for account in self.base.getAccounts():
            type = account['type']

            if type == Globals.OTPAuth:
                accounts.append({
                    'secret': account['key'],
                    'digits': 6,
                    'period': 30,
                    'label': account['name'],
                    'type': 'TOTP',
                    'algorithm': 'SHA1',
                    'thumbnail': 'Default',
                    'last_used': 0,
                    'tags': []
                })
            elif type == Globals.SteamAuth:
                accounts.append({
                    'secret':
                    base64.b32encode(base64.b64decode(
                        account['sharedSecret'])).decode('utf-8'),
                    'digits':
                    5,
                    'period':
                    30,
                    'label':
                    account['name'],
                    'type':
                    'STEAM',
                    'algorithm':
                    'SHA1',
                    'thumbnail':
                    'Default',
                    'last_used':
                    0,
                    'tags': []
                })

        accounts = json.dumps(accounts)
        filename, _ = QFileDialog.getSaveFileName(
            self, 'Export to andOTP JSON file', '', 'All Files (*)')

        if filename:
            with open(filename, 'w') as file:
                file.write(accounts)
コード例 #15
0
    def __init__(self, parameter: Parameter):
        super().__init__()

        self.parameter = parameter

        deleteButton = QToolButton()
        deleteButton.setText("X")
        deleteButton.clicked.connect(
            lambda: self.onRemoveParameter.emit(self.parameter))
        upButton = QToolButton()
        upButton.setText("\u2191")
        upButton.clicked.connect(
            lambda: self.onMoveParameterUp.emit(self.parameter))
        downButton = QToolButton()
        downButton.setText("\u2193")
        downButton.clicked.connect(
            lambda: self.onMoveParameterDown.emit(self.parameter))

        buttonsLayout = QVBoxLayout()
        buttonsLayout.setAlignment(Qt.AlignTop)
        buttonsLayout.addWidget(deleteButton)
        buttonsLayout.addWidget(upButton)
        buttonsLayout.addWidget(downButton)

        self._nameLabel = QLabel("Name")
        self._nameField = QLineEdit()
        self._nameField.textChanged.connect(self.OnChanged)

        self._dataTypeLabel = QLabel("Data Type")
        self._dataTypeField = QComboBox()
        for dataType in DataType:
            self._dataTypeField.addItem(dataType.ToString(), userData=dataType)
        self._dataTypeField.currentIndexChanged.connect(self.OnChanged)

        self._defaultValueLabel = QLabel("Default Value")
        self._defaultInteger = QSpinBox()
        self._defaultInteger.valueChanged.connect(self.OnChanged)

        self._defaultFloat = QDoubleSpinBox()
        self._defaultFloat.valueChanged.connect(self.OnChanged)

        self._defaultBoolean = QComboBox()
        self._defaultBoolean.addItem("True", True)
        self._defaultBoolean.addItem("False", False)
        self._defaultBoolean.currentIndexChanged.connect(self.OnChanged)

        self._defaultString = QLineEdit()
        self._defaultString.textChanged.connect(self.OnChanged)

        self._minimumLabel = QLabel("Minimum")
        self._minimumFloat = QDoubleSpinBox()
        self._minimumFloat.valueChanged.connect(self.OnChanged)
        self._minimumInteger = QSpinBox()
        self._minimumInteger.valueChanged.connect(self.OnChanged)

        self._maximumLabel = QLabel("Maximum")
        self._maximumFloat = QDoubleSpinBox()
        self._maximumFloat.valueChanged.connect(self.OnChanged)
        self._maximumInteger = QSpinBox()
        self._maximumInteger.valueChanged.connect(self.OnChanged)

        gridLayout = QGridLayout()
        gridLayout.setAlignment(Qt.AlignTop)
        gridLayout.addWidget(self._nameLabel, 0, 0)
        gridLayout.addWidget(self._nameField, 0, 1)
        gridLayout.addWidget(self._dataTypeLabel, 1, 0)
        gridLayout.addWidget(self._dataTypeField, 1, 1)
        gridLayout.addWidget(self._defaultValueLabel, 2, 0)

        for defaultField in [
                self._defaultInteger, self._defaultFloat, self._defaultBoolean,
                self._defaultString
        ]:
            gridLayout.addWidget(defaultField, 2, 1)

        gridLayout.addWidget(self._minimumLabel, 3, 0)
        gridLayout.addWidget(self._minimumInteger, 3, 1)
        gridLayout.addWidget(self._minimumFloat, 3, 1)
        gridLayout.addWidget(self._maximumLabel, 4, 0)
        gridLayout.addWidget(self._maximumInteger, 4, 1)
        gridLayout.addWidget(self._maximumFloat, 4, 1)

        layout = QHBoxLayout()
        layout.addLayout(buttonsLayout)
        layout.addLayout(gridLayout)
        self.setLayout(layout)

        self.SetFieldsFromParameter()
コード例 #16
0
ファイル: card.py プロジェクト: PentheusLennuye/jp2
class Card(QMainWindow):
    def __init__(self, title, instructions, questions, answers, parent=None):
        super().__init__(parent)
        self.questions = questions
        self.answers = answers
        self.index = 0
        self.mode = POSING_QUESTION
        self.button_labels = ['答え', '次の質問']
        self.last_question = len(self.questions) - 1
        self.setWindowTitle('日本語の練習')

        self.title = Title(title, self)
        self.instructions = Instructions(instructions, self)
        self.playfield = Playfield(self.questions[self.index],
                                   self.answers[self.index], self)
        self.controls = Controls(self, self.button_labels[self.mode],
                                 self.move_forward, self.quit_me)
        self.statusbar = self.statusBar()

        # Layout and hide the initial answer

        self.layout = QVBoxLayout()
        self.central_widget = QWidget()
        self.playfield.hide_answer()
        self.set_layout()
        self.setCentralWidget(self.central_widget)
        self.card_count = QLabel(f"{self.get_card_count()} cards")
        self.statusbar.addPermanentWidget(self.card_count)

    def set_layout(self):

        self.layout.takeAt(0)
        self.layout.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.title)
        self.layout.addWidget(self.instructions)
        self.layout.addWidget(self.playfield)
        self.layout.addWidget(self.controls)
        self.central_widget.setLayout(self.layout)

    def update_statusbar(self):
        self.card_count.setText(f"{self.get_card_count()} cards")

    @Slot()
    def move_forward(self):
        if self.mode == POSING_QUESTION:
            self.mode = SHOWING_ANSWER
            self.show_answer()
        else:
            self.mode = POSING_QUESTION
            self.pose_next_question()

    def pose_next_question(self):
        self.index += 1
        self.playfield.setParent(None)
        self.playfield = Playfield(self.questions[self.index],
                                   self.answers[self.index], self)
        self.playfield.hide_answer()
        self.controls.set_button(self.button_labels[self.mode])
        self.set_layout()
        self.update_statusbar()

    def show_answer(self):
        self.playfield.show_answer()
        if self.index < self.last_question:
            self.controls.set_button(self.button_labels[self.mode])
        else:
            self.controls.hide_button()

    @Slot()
    def quit_me(self):
        QCoreApplication.instance().quit()

    def get_card_count(self):
        return f"{self.index + 1}/{self.last_question + 1}"
コード例 #17
0
class OrderableListWidget(QScrollArea):
    """All available items in this list"""
    _item_list: list[OrderableListItem]
    """This lists actual widget"""
    _widget: QWidget
    """The widgets layout"""
    _layout: QLayout
    """Decides which way this list is ordered; 1 for ascending, -1 for descending"""
    _order_factor: int

    def __init__(self, order_asc=True, orientation_horizontal=False):
        """Init gui
        :type order_asc: bool
        :param order_asc: Whether to order the list ascending
        :type orientation_horizontal: bool
        :param orientation_horizontal: Should the list orientation be horizontal?
        """
        super().__init__()
        if order_asc:
            self._order_factor = 1
        else:
            self._order_factor = -1
        self._widget = QWidget()
        self.setWidget(self._widget)
        self.setWidgetResizable(True)
        # Set layout
        if orientation_horizontal:
            self._layout = QHBoxLayout()
        else:
            self._layout = QVBoxLayout()
        self._widget.setLayout(self._layout)
        self._layout.setAlignment(Qt.AlignTop)
        self._item_list = []

    def _get_order(self, list_item_a, list_item_b):
        """Defines this lists widget order
        :type list_item_a: OrderableListItem
        :param list_item_a: The first item to compare
        :type list_item_b: OrderableListItem
        :param list_item_b: The second item to compare
        :returns -1|0|1: list_item_a is: before, same, after list_item_b"""
        str_a: str = list_item_a.get_order_string()
        str_b: str = list_item_b.get_order_string()

        if str_a == str_b:
            return 0
        elif str_a < str_b:
            return -1 * self._order_factor
        else:
            return 1 * self._order_factor

    def add(self, list_item):
        """Add a new item to the list
        :type list_item: OrderableListItem
        :param list_item: The item to add
        """
        # Subscribe to changes
        list_item.subscribe(OrderableListItem.DELETED, self._item_deleted)
        list_item.subscribe(OrderableListItem.UPDATED, self._item_updated)
        # Make sure to add the item only once
        if list_item not in self._item_list:
            list_item_inserted = False
            self._item_list.append(list_item)

            # Walk all existing items
            for i in range(self._layout.count()):
                existing_item: OrderableListItem = self._layout.itemAt(i).widget()

                if 1 == self._get_order(existing_item, list_item):
                    self._layout.insertWidget(i, list_item)
                    list_item_inserted = True
                    break
            if not list_item_inserted:
                self._layout.addWidget(list_item)

    def _item_deleted(self, item):
        """Delete an item from the list
        :type item: OrderableListItem
        :param item: The item to delete
        """
        # See if the item exists in this list
        try:
            i: int = self._item_list.index(item)
        except ValueError:
            return
        # Delete the item
        self._item_list.pop(i)

    def _item_updated(self, item):
        """Update the list with the items new information
        :type item: OrderableListItem
        :param item: The item that was updated
        """
        pass
コード例 #18
0
    def __init__(self, model: SettingsModel, parent=None):
        super(SetQuotaDiskWidget, self).__init__(parent)

        self._model = model

        self.setAccessibleName("InfoBox")

        self.title = QLabel()
        self.title.setText("Spazio di archiviazione")
        self.title.setAccessibleName("Title2")

        self.sottotitolo = QLabel()
        self.sottotitolo.setAccessibleName('Sottotitolo')
        self.sottotitolo.setText(
            "Cambia lo spazio di archiviazione destinato alla cartella sincronizzata"
        )

        # Barra riempimento disco
        self.progress_label = QLabel()
        self.progress_label.setText("Spazio occupato:")

        self.disk_progress = QProgressBar()
        self.disk_progress.setFormat("")

        self.disk_quota = QLabel()

        # Modifica spazio dedicato
        self.spaceLabel = QLabel(" ")

        self.dedicated_space = QLineEdit()
        self.dedicated_space.setValidator(QDoubleValidator())

        self.sizes_box = QComboBox()
        self.sizes_box.wheelEvent = lambda event: None
        _path_size = bitmath.parse_string(model.convert_size(model.get_size()))
        _disk_free = bitmath.parse_string(
            model.convert_size(model.get_free_disk()))

        self.populate_size_box(_path_size, _disk_free)

        self.change_quota_button = QPushButton("Cambia quota disco")
        self.change_quota_button.setMaximumWidth(150)

        self.change_quota_button.clicked.connect(
            self.Sl_dedicated_space_changed)
        self.dedicated_space.returnPressed.connect(
            self.Sl_dedicated_space_changed)

        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addWidget(self.spaceLabel)
        self.buttonLayout.addWidget(self.change_quota_button)
        self.buttonLayout.addWidget(self.spaceLabel)

        set_space_layout = QHBoxLayout()
        set_space_layout.addWidget(self.dedicated_space)
        set_space_layout.addWidget(self.sizes_box)

        quota_layout = QHBoxLayout()
        quota_layout.setAlignment(Qt.AlignLeft)
        quota_layout.addWidget(self.progress_label)
        quota_layout.addWidget(self.disk_quota)

        # layout
        disk_layout = QVBoxLayout()
        disk_layout.setAlignment(Qt.AlignLeft)
        disk_layout.addWidget(self.title)
        disk_layout.addWidget(self.sottotitolo)
        disk_layout.addWidget(self.spaceLabel)
        disk_layout.addLayout(quota_layout)
        disk_layout.addWidget(self.disk_progress)
        disk_layout.addWidget(self.spaceLabel)
        disk_layout.addLayout(set_space_layout)
        disk_layout.addLayout(self.buttonLayout)

        self.setLayout(disk_layout)
        self.Sl_model_changed()