Ejemplo n.º 1
0
    def __init__(self, qpart, model):
        QListView.__init__(self, qpart.viewport())
        self.setItemDelegate(HTMLDelegate(self))
        
        self._qpart = qpart
        self.setFont(qpart.font())
        
        self.setCursor(QCursor(Qt.PointingHandCursor))
        self.setFocusPolicy(Qt.NoFocus)
        
        self.setModel(model)
        
        self._selectedIndex = -1
        
        # if cursor moved, we shall close widget, if its position (and model) hasn't been updated
        self._closeIfNotUpdatedTimer = QTimer()
        self._closeIfNotUpdatedTimer.setInterval(200)
        self._closeIfNotUpdatedTimer.setSingleShot(True)

        self._closeIfNotUpdatedTimer.timeout.connect(self._afterCursorPositionChanged)
        
        qpart.installEventFilter(self)
        
        qpart.cursorPositionChanged.connect(self._onCursorPositionChanged)
        
        self.clicked.connect(lambda index: self.itemSelected.emit(index.row()))
        
        self.updateGeometry()
        self.show()
        
        qpart.setFocus()
Ejemplo n.º 2
0
 def keyPressEvent(self, event):
     if event.key() in (Qt.Key_Up, Qt.Key_Down, Qt.Key_Control):
         QListView.keyPressEvent(self, event)
     else:
         self.parent().switch_tb_edit()
         self.parent().tb_text.setFocus()
         self.parent().tb_text.keyPressEvent(event)
Ejemplo n.º 3
0
 def keyPressEvent(self, event):
     if event.key() in (Qt.Key_Up, Qt.Key_Down, Qt.Key_Control):
         QListView.keyPressEvent(self, event)
     else:
         self.parent().switch_tb_edit()
         self.parent().tb_text.setFocus()
         self.parent().tb_text.keyPressEvent(event)
Ejemplo n.º 4
0
 def __init__(self, parent=None):
     QListView.__init__(self, parent)
     self.setWordWrap(True)
     self.refreshCustomDelegate()
     self.setEditTriggers(QAbstractItemView.SelectedClicked)
     self.setSpacing(0)
     self.setUniformItemSizes(False)
     self.setResizeMode(QListView.Adjust)
     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
Ejemplo n.º 5
0
 def __init__(self, parent=None):
     QListView.__init__(self, parent)
     self.setWordWrap(True)
     self.refreshCustomDelegate()
     self.setEditTriggers(QAbstractItemView.SelectedClicked)
     self.setSpacing(0)
     self.setUniformItemSizes(False)
     self.setResizeMode(QListView.Adjust)
     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
Ejemplo n.º 6
0
    def __init__(self, strategy):
        QListView.__init__(self)

        self.item_strat = strategy

        self.itemmodel = QStandardItemModel()
        self.proxymodel = QSortFilterProxyModel()
        self.proxymodel.setSourceModel(self.itemmodel)
        self.proxymodel.setDynamicSortFilter(True)
        self.setModel(self.proxymodel)
        self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
Ejemplo n.º 7
0
    def __init__(self, strategy):
        QListView.__init__(self)
        self.ctrl = None
        self.item_strat = strategy

        self.itemmodel = QStandardItemModel()
        self.proxymodel = LuneSortFilterProxyModel()
        self.proxymodel.setSourceModel(self.itemmodel)
        self.setModel(self.proxymodel)
        self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.proxymodel.setSortCaseSensitivity(QtCore.Qt.CaseSensitivity.CaseInsensitive)
        self.proxymodel.sort(0)
Ejemplo n.º 8
0
class MainWindow(QWidget):
    
    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout()
        self.setLayout(vbox)
        self.lst = QListView(self)
        self.lst.setModel(PersonModel([Person('HZG', 28), Person('ZRH', 21)]))
        self.lst.clicked.connect(self.printItem)
        vbox.addWidget(self.lst)
        
    def printItem(self, idx):
        print idx.model().persons[idx.row()]
Ejemplo n.º 9
0
def main():
    app = QApplication(sys.argv)
    window = QMainWindow()
    view = QListView(window)
    window.setCentralWidget(view)
    view.setViewMode(QListView.IconMode)
    view.setMovement(QListView.Static)
    view.setIconSize(QSize(64, 64))
    view.setModel(
        IconModel(
            [('System', QIcon.fromTheme('preferences-system')),
             ('Desktop', QIcon.fromTheme('preferences-desktop-personal'))],
            view))
    window.show()
    app.exec_()
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     self.view = QListView(self)
     self.view.setModel(CheckableFilesystemModel(self.view))
     self.view.activated.connect(self.openIndex)
     self.setCentralWidget(self.view)
     open_action = QAction(self.style().standardIcon(
         QStyle.SP_DialogOpenButton), 'Open', self)
     open_action.triggered.connect(self.askOpenDirectory)
     show_action = QAction('Show checked filenames', self)
     show_action.triggered.connect(self.showCheckedFiles)
     actions = self.addToolBar('Actions')
     actions.addAction(open_action)
     actions.addAction(show_action)
     self.openDirectory(os.path.expanduser('~'))
Ejemplo n.º 11
0
 def __init__(self):
     QWidget.__init__(self)
     vbox = QVBoxLayout()
     self.setLayout(vbox)
     self.lst = QListView(self)
     self.lst.setModel(PersonModel([Person('HZG', 28), Person('ZRH', 21)]))
     self.lst.clicked.connect(self.printItem)
     vbox.addWidget(self.lst)
Ejemplo n.º 12
0
    def get_frame(self):
        listvmd = QListView()
        listvmd.setMaximumWidth(150)
        listvmd.setModel(self.models_model)
        listvmd.doubleClicked.connect(self.edit_mdl)
        listvmd.setResizeMode(listvmd.ResizeMode.Adjust)
        self.listview = listvmd

        return listvmd
Ejemplo n.º 13
0
	def doLayout(self):
		central_window = QWidget(self)
		vlayout = QVBoxLayout(central_window)

		self.FileListView = QListView(self)
		self.SafeModeCheckbox = QCheckBox(self.tr('Safeモードで読み込み(エラーが出る場合に使用ください。改行やページ番号等崩れる場合があります。)'), self)
		convert_button = QPushButton(self.tr('変換'), central_window)

		vlayout.addWidget(QLabel(self.tr('ドラッグ&ドロップでファイルを読み込みます'), self))
		vlayout.addWidget(self.FileListView)
		vlayout.addWidget(self.SafeModeCheckbox)
		vlayout.addWidget(convert_button)
		convert_button.clicked.connect(self.onConvert)

		self.FileListModel = QStandardItemModel(self)
		self.FileListModel.setHorizontalHeaderLabels([self.tr('ファイル名')])
		self.FileListView.setModel(self.FileListModel)
		self.FileListView.setAcceptDrops(True)

		self.setCentralWidget(central_window)
Ejemplo n.º 14
0
    def setup_ui(self):
        main_layout = QHBoxLayout(self)

        edt = QLineEdit(self)
        edt.setPlaceholderText("Wildcard filter")
        btn = QToolButton(self)
        btn.clicked.connect(self.set_icon)

        layout = QHBoxLayout(self)
        layout.addWidget(edt)
        layout.addWidget(btn)

        layout2 = QVBoxLayout()
        layout2.addLayout(layout)

        model = TListModel(self)
        proxy = QSortFilterProxyModel(self)
        proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        proxy.setSourceModel(model)
        edt.textChanged.connect(proxy.setFilterWildcard)

        list = QListView()
        list.setModel(proxy)
        selection_model = list.selectionModel()
        selection_model.currentChanged.connect(self.currentChanged)
        layout2.addWidget(list)

        main_layout.addLayout(layout2)

        image = QLabel("Select icon", self)
        image.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        image.setMinimumWidth(256)
        main_layout.addWidget(image)

        self.btn = btn
        self.edt = edt
        self.image = image
        self.list = list
        self.proxy = proxy
        self.model = model
        self.selection_model = selection_model
Ejemplo n.º 15
0
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()
Ejemplo n.º 16
0
def main():
    app = QApplication(sys.argv)
    window = QMainWindow()
    view = QListView(window)
    window.setCentralWidget(view)
    view.setViewMode(QListView.IconMode)
    view.setMovement(QListView.Static)
    view.setIconSize(QSize(64, 64))
    view.setModel(
        IconModel(
            [
                ("System", QIcon.fromTheme("preferences-system")),
                ("Desktop", QIcon.fromTheme("preferences-desktop-personal")),
            ],
            view,
        )
    )
    window.show()
    app.exec_()
    def createEditorReaction(self, parent, option, index):
        '''
        Creates the editor if a Reaction is shown.
        '''
        if index.column() == sbml_entitytablemodel.REACTION_ROW.REACTANTS:
            list = QListView(parent)
            list.setSelectionMode(QAbstractItemView.MultiSelection)

#            combobox = QComboBox(parent)
            speciesIDs = []
            for speciesWrapper in index.model().mainModel.SbmlSpecies:
                speciesIDs.append(speciesWrapper.getId())

            #list. #adding the species...
#

#            combobox.addItems(sorted(speciesIDs))
#            #combobox.setEditable(True)
#            return combobox

        else:
            return QStyledItemDelegate.createEditor(self, parent, option,
                                                    index)
Ejemplo n.º 18
0
    def createEditorReaction(self, parent, option, index):
        '''
        Creates the editor if a Reaction is shown.
        '''
        if index.column() == sbml_entitytablemodel.REACTION_ROW.REACTANTS:
            list = QListView(parent)
            list.setSelectionMode(QAbstractItemView.MultiSelection)

            #            combobox = QComboBox(parent)
            speciesIDs = []
            for speciesWrapper in index.model().mainModel.SbmlSpecies:
                speciesIDs.append(speciesWrapper.getId())

            #list. #adding the species...
#

#            combobox.addItems(sorted(speciesIDs))
#            #combobox.setEditable(True)
#            return combobox

        else:
            return QStyledItemDelegate.createEditor(self, parent, option,
                                                    index)
Ejemplo n.º 19
0
    def buildFilterListView(self):
        """Creates the QListView that contains all of the basic Clause
           objects.
        """
        groupBox = QGroupBox("Clauses")
        layout = QVBoxLayout(groupBox)

        self.list_view = QListView(groupBox)
        self.list_view.setModel(self.clause_model)
        layout.addWidget(self.list_view)

        layout.addItem(QSpacerItem(5,5))
        self.delButton = QPushButton("Remove Selected Clause")
        self.delButton.clicked.connect(self.deleteClause)
        layout.addWidget(self.delButton)

        groupBox.setLayout(layout)
        return groupBox
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.view = QListView(self)
        self.view.setModel(CheckableFilesystemModel(self.view))
        self.view.activated.connect(self.openIndex)
        self.setCentralWidget(self.view)
        open_action = QAction(self.style().standardIcon(
            QStyle.SP_DialogOpenButton), 'Open', self)
        open_action.triggered.connect(self.askOpenDirectory)
        show_action = QAction('Show checked filenames', self)
        show_action.triggered.connect(self.showCheckedFiles)
        actions = self.addToolBar('Actions')
        actions.addAction(open_action)
        actions.addAction(show_action)
        self.openDirectory(os.path.expanduser('~'))

    def askOpenDirectory(self):
        directory = QFileDialog.getExistingDirectory(
            self, 'Open directory ...', os.path.expanduser('~'))
        if directory:
            self.openDirectory(directory)

    def openDirectory(self, directory):
        if os.path.isdir(directory):
            root = self.view.model().setRootPath(directory)
            self.view.setRootIndex(root)

    def openIndex(self, index):
        model = self.view.model()
        directory = model.data(index, QFileSystemModel.FilePathRole)
        self.openDirectory(directory)

    def showCheckedFiles(self):
        checked_files = self.view.model().checked_files
        if checked_files:
            print('\n'.join(checked_files))
            filelist = ''.join('<li>{0}</li>'.format(escape(fn))
                               for fn in checked_files)
            QMessageBox.information(self, 'Checked files',
                                    '<ul>{0}</ul>'.format(filelist),)
        else:
            print('no files checked')
            QMessageBox.information(self, 'No files checked',
                                    'No files checked')
Ejemplo n.º 21
0
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()
Ejemplo n.º 22
0
    def init_UI(self):
        maingrp = QGroupBox(self.geo.classname)
        grplay = QGridLayout()

        vertices = QListView()
        vertices.setModel(self.vmodel)
        vertices.doubleClicked.connect(self.edit_vertex)
        self.v = vertices

        faces = QListView()
        faces.setModel(self.fmodel)

        grplay.addWidget(vertices, 0, 0, 2, 2)
        grplay.addWidget(faces, 0, 2, 2, 2)

        maingrp.setLayout(grplay)

        mainlay = QHBoxLayout()
        mainlay.addWidget(maingrp)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 400, 500)
        self.setWindowTitle('MSH Suite - Geometry Editor')
        self.show()
Ejemplo n.º 23
0
class RunnerDialog(QDialog):

    options_added = Signal(Options)
    options_running = Signal(Options)
    options_simulated = Signal(Options)
    options_error = Signal(Options, Exception)
    results_saved = Signal(Results, str)
    results_error = Signal(Results, Exception)

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle('Runner')
        self.setMinimumWidth(750)

        # Runner
        self._runner = None

        self._running_timer = QTimer()
        self._running_timer.setInterval(500)

        # Widgets
        self._dlg_progress = QProgressDialog()
        self._dlg_progress.setRange(0, 100)
        self._dlg_progress.setModal(True)
        self._dlg_progress.hide()

        lbl_outputdir = QLabel("Output directory")
        self._txt_outputdir = DirBrowseWidget()

        max_workers = cpu_count() #@UndefinedVariable
        lbl_workers = QLabel('Number of workers')
        self._spn_workers = QSpinBox()
        self._spn_workers.setRange(1, max_workers)
        self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        lbl_max_workers = QLabel('(max: %i)' % max_workers)

        self._chk_overwrite = QCheckBox("Overwrite existing results in output directory")
        self._chk_overwrite.setChecked(True)

        self._lbl_available = QLabel('Available')
        self._lst_available = QListView()
        self._lst_available.setModel(_AvailableOptionsListModel())
        self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection)

        tlb_available = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_available.addWidget(spacer)
        act_open = tlb_available.addAction(getIcon("document-open"), "Open")
        act_open.setShortcut(QKeySequence.Open)
        tlb_available.addSeparator()
        act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove")
        act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear")

        self._btn_addtoqueue = QPushButton(getIcon("go-next"), "")
        self._btn_addtoqueue.setToolTip("Add to queue")
        self._btn_addtoqueue.setEnabled(False)

        self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "")
        self._btn_addalltoqueue.setToolTip("Add all to queue")
        self._btn_addalltoqueue.setEnabled(False)

        self._lbl_options = QLabel('Queued/Running/Completed')
        self._tbl_options = QTableView()
        self._tbl_options.setModel(_StateOptionsTableModel())
        self._tbl_options.setItemDelegate(_StateOptionsItemDelegate())
        self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection)
        self._tbl_options.setColumnWidth(1, 60)
        self._tbl_options.setColumnWidth(2, 80)
        header = self._tbl_options.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Interactive)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.setResizeMode(2, QHeaderView.Fixed)
        header.setResizeMode(3, QHeaderView.Stretch)

        self._btn_start = QPushButton(getIcon("media-playback-start"), "Start")

        self._btn_cancel = QPushButton("Cancel")
        self._btn_cancel.setEnabled(False)

        self._btn_close = QPushButton("Close")

        self._btn_import = QPushButton("Import")
        self._btn_import.setEnabled(False)

        # Layouts
        layout = QVBoxLayout()

        sublayout = QGridLayout()
        sublayout.addWidget(lbl_outputdir, 0, 0)
        sublayout.addWidget(self._txt_outputdir, 0, 1)
        sublayout.addWidget(lbl_workers, 1, 0)

        subsublayout = QHBoxLayout()
        subsublayout.addWidget(self._spn_workers)
        subsublayout.addWidget(lbl_max_workers)
        sublayout.addLayout(subsublayout, 1, 1)
        layout.addLayout(sublayout)

        sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3)

        sublayout = QGridLayout()
        sublayout.setColumnStretch(0, 1)
        sublayout.setColumnStretch(2, 3)
        sublayout.addWidget(self._lbl_available, 0, 0)
        sublayout.addWidget(self._lst_available, 1, 0)
        sublayout.addWidget(tlb_available, 2, 0)

        subsublayout = QVBoxLayout()
        subsublayout.addStretch()
        subsublayout.addWidget(self._btn_addtoqueue)
        subsublayout.addWidget(self._btn_addalltoqueue)
        subsublayout.addStretch()
        sublayout.addLayout(subsublayout, 1, 1)

        sublayout.addWidget(self._lbl_options, 0, 2)
        sublayout.addWidget(self._tbl_options, 1, 2)
        layout.addLayout(sublayout)

        sublayout = QHBoxLayout()
        sublayout.addStretch()
        sublayout.addWidget(self._btn_import)
        sublayout.addWidget(self._btn_start)
        sublayout.addWidget(self._btn_cancel)
        sublayout.addWidget(self._btn_close)
        layout.addLayout(sublayout)

        self.setLayout(layout)

        # Signal
        self._running_timer.timeout.connect(self._onRunningTimer)

        act_open.triggered.connect(self._onOpen)
        act_remove.triggered.connect(self._onRemove)
        act_clear.triggered.connect(self._onClear)

        self._btn_addtoqueue.released.connect(self._onAddToQueue)
        self._btn_addalltoqueue.released.connect(self._onAddAllToQueue)
        self._btn_start.released.connect(self._onStart)
        self._btn_cancel.released.connect(self._onCancel)
        self._btn_close.released.connect(self._onClose)
        self._btn_import.released.connect(self._onImport)

        self.options_added.connect(self._onOptionsAdded)
        self.options_running.connect(self._onOptionsRunning)
        self.options_simulated.connect(self._onOptionsSimulated)
        self.options_error.connect(self._onOptionsError)
        self.results_error.connect(self._onResultsError)

        # Defaults
        settings = get_settings()
        section = settings.add_section('gui')
        if hasattr(section, 'outputdir'):
            self._txt_outputdir.setPath(section.outputdir)
        if hasattr(section, 'maxworkers'):
            self._spn_workers.setValue(int(section.maxworkers))
        if hasattr(section, 'overwrite'):
            state = True if section.overwrite.lower() == 'true' else False
            self._chk_overwrite.setChecked(state)

    def _onDialogProgressProgress(self, progress, status):
        self._dlg_progress.setValue(progress * 100)
        self._dlg_progress.setLabelText(status)

    def _onDialogProgressCancel(self):
        self._dlg_progress.hide()
        if self._options_reader_thread is None:
            return
        self._options_reader_thread.cancel()
        self._options_reader_thread.quit()
        self._options_reader_thread.wait()

    def _onDialogProgressException(self, ex):
        self._dlg_progress.hide()
        self._options_reader_thread.quit()
        self._options_reader_thread.wait()
        messagebox.exception(self, ex)

    def _onRunningTimer(self):
        self._tbl_options.model().reset()

    def _onOpen(self):
        settings = get_settings()
        curdir = getattr(settings.gui, 'opendir', os.getcwd())

        filepath, namefilter = \
            QFileDialog.getOpenFileName(self, "Open", curdir,
                                        'Options [*.xml] (*.xml)')

        if not filepath or not namefilter:
            return
        settings.gui.opendir = os.path.dirname(filepath)

        if not filepath.endswith('.xml'):
            filepath += '.xml'

        self._options_reader_thread = _OptionsReaderWrapperThread(filepath)
        self._dlg_progress.canceled.connect(self._onDialogProgressCancel)
        self._options_reader_thread.resultReady.connect(self._onOpened)
        self._options_reader_thread.progressUpdated.connect(self._onDialogProgressProgress)
        self._options_reader_thread.exceptionRaised.connect(self._onDialogProgressException)
        self._options_reader_thread.start()

        self._dlg_progress.reset()
        self._dlg_progress.show()

    def _onOpened(self, options):
        self._dlg_progress.hide()
        self._options_reader_thread.quit()
        self._options_reader_thread.wait()
        self._options_reader_thread = None

        try:
            self._lst_available.model().addOptions(options)
        except Exception as ex:
            messagebox.exception(self, ex)

    def _onRemove(self):
        selection = self._lst_available.selectionModel().selection().indexes()
        if len(selection) == 0:
            QMessageBox.warning(self, "Queue", "Select an options")
            return

        model = self._lst_available.model()
        for row in sorted(map(methodcaller('row'), selection), reverse=True):
            model.popOptions(row)

    def _onClear(self):
        self._lst_available.model().clearOptions()

    def _onAddToQueue(self):
        selection = self._lst_available.selectionModel().selection().indexes()
        if len(selection) == 0:
            QMessageBox.warning(self, "Queue", "Select an options")
            return

        model = self._lst_available.model()
        for row in sorted(map(methodcaller('row'), selection), reverse=True):
            options = model.options(row)
            try:
                self._runner.put(options)
            except Exception as ex:
                messagebox.exception(self, ex)
                return

    def _onAddAllToQueue(self):
        model = self._lst_available.model()
        for row in reversed(range(0, model.rowCount())):
            options = model.options(row)
            try:
                self._runner.put(options)
            except Exception as ex:
                messagebox.exception(self, ex)
                return

    def _onStart(self):
        outputdir = self._txt_outputdir.path()
        if not outputdir:
            QMessageBox.critical(self, 'Start', 'Missing output directory')
            return
        max_workers = self._spn_workers.value()
        overwrite = self._chk_overwrite.isChecked()
        self.start(outputdir, overwrite, max_workers)

    def _onCancel(self):
        self.cancel()

    def _onClose(self):
        if self._runner is not None:
            self._runner.close()
        self._running_timer.stop()
        self.close()

    def _onImport(self):
        list_options = self._lst_available.model().listOptions()
        if not list_options:
            return

        # Select options
        dialog = _OptionsSelector(list_options)
        if not dialog.exec_():
            return
        options = dialog.options()

        # Start importer
        outputdir = self._runner.outputdir
        max_workers = self._runner.max_workers
        importer = LocalImporter(outputdir, max_workers)

        importer.start()
        importer.put(options)

        self._dlg_progress.show()
        try:
            while importer.is_alive():
                if self._dlg_progress.wasCanceled():
                    importer.cancel()
                    break
                self._dlg_progress.setValue(importer.progress * 100)
        finally:
            self._dlg_progress.hide()

    def _onOptionsAdded(self, options):
        logging.debug('runner: optionsAdded')
        self._tbl_options.model().addOptions(options)

    def _onOptionsRunning(self, options):
        logging.debug('runner: optionsRunning')
        self._tbl_options.model().resetOptions(options)

    def _onOptionsSimulated(self, options):
        logging.debug('runner: optionsSimulated')
        self._tbl_options.model().resetOptions(options)

    def _onOptionsError(self, options, ex):
        logging.debug('runner: optionsError')
        self._tbl_options.model().resetOptions(options)

    def _onResultsError(self, results, ex):
        logging.debug('runner: resultsError')
        self._tbl_options.model().reset()

    def closeEvent(self, event):
        if self.is_running():
            message = 'Runner is running. Do you want to continue?'
            answer = QMessageBox.question(self, 'Runner', message,
                                          QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                event.ignore()
                return

        self.cancel()
        self._dlg_progress.close()

        settings = get_settings()
        section = settings.add_section('gui')

        path = self._txt_outputdir.path()
        if path:
            section.outputdir = path
        section.maxworkers = str(self._spn_workers.value())
        section.overwrite = str(self._chk_overwrite.isChecked())

        settings.write()

        event.accept()

    def addAvailableOptions(self, options):
        self._lst_available.model().addOptions(options)

    def removeAvailableOptions(self, options):
        self._lst_available.model().removeOptions(options)

    def clearAvailableOptions(self):
        self._lbl_available.model().clearOptions()

    def start(self, outputdir, overwrite, max_workers):
        self._runner = LocalRunner(outputdir=outputdir,
                                   overwrite=overwrite,
                                   max_workers=max_workers)

        self._tbl_options.setModel(_StateOptionsTableModel(self._runner))

        self._spn_workers.setEnabled(False)
        self._txt_outputdir.setEnabled(False)
        self._chk_overwrite.setEnabled(False)
        self._btn_addtoqueue.setEnabled(True)
        self._btn_addalltoqueue.setEnabled(True)
        self._btn_start.setEnabled(False)
        self._btn_cancel.setEnabled(True)
        self._btn_close.setEnabled(False)
        self._btn_import.setEnabled(True)

        self._runner.options_added.connect(self.options_added.emit)
        self._runner.options_running.connect(self.options_running.emit)
        self._runner.options_simulated.connect(self.options_simulated.emit)
        self._runner.options_error.connect(self.options_error.emit)
        self._runner.results_saved.connect(self.results_saved.emit)
        self._runner.results_error.connect(self.results_error.emit)

        self._running_timer.start()
        self._runner.start()

    def cancel(self):
        if self._runner is None:
            return
        self._runner.cancel()
        self._running_timer.stop()

        self._runner.options_added.disconnect(self.options_added.emit)
        self._runner.options_running.disconnect(self.options_running.emit)
        self._runner.options_simulated.disconnect(self.options_simulated.emit)
        self._runner.options_error.disconnect(self.options_error.emit)
        self._runner.results_saved.disconnect(self.results_saved.emit)
        self._runner.results_error.disconnect(self.results_error.emit)

        self._runner = None

        self._spn_workers.setEnabled(True)
        self._txt_outputdir.setEnabled(True)
        self._chk_overwrite.setEnabled(True)
        self._btn_addtoqueue.setEnabled(False)
        self._btn_addalltoqueue.setEnabled(False)
        self._btn_start.setEnabled(True)
        self._btn_cancel.setEnabled(False)
        self._btn_close.setEnabled(True)
        self._btn_import.setEnabled(False)

    def is_running(self):
        return self._runner is not None and self._runner.is_alive()
Ejemplo n.º 24
0
class FilterTab(QWidget):
    """This class is the GUI for creating filters for the FilterBox
       module. This GUI will be added as a tab to the ModuleFrame
       tab dialog.
    """

    applySignal = Signal(Clause)

    def __init__(self, parent, mframe, existing_filters):
        """Create a FilterTab with the given parent TabDialog, logical
           parent ModuleFrame mframe, and existing_filters list of Clause
           objects.
        """
        super(FilterTab, self).__init__(parent)

        self.mframe = mframe
        self.parent = parent
        self.attributes = self.mframe.agent.datatree.generateAttributeList()

        self.clause_list = list()
        self.clause_dict = dict()
        # Right now we only look at the first passed in filter.
        # TODO: At GUI to switch between existing filters
        if existing_filters is not None and len(existing_filters) > 0:
            for clause in existing_filters[0].conditions.clauses:
                self.clause_list.append(str(clause))
                self.clause_dict[str(clause)] = clause

        self.clause_model = QStringListModel(self.clause_list)

        layout = QVBoxLayout(self)
        self.sidesplitter = QSplitter(Qt.Horizontal)

        # You can only select one attribute at a time to build the 
        # filter clauses
        self.data_view = QTreeView(self)
        self.data_view.setModel(self.mframe.agent.datatree)
        self.data_view.setDragEnabled(True)
        self.data_view.setDropIndicatorShown(True)
        self.data_view.expandAll()
        self.sidesplitter.addWidget(self.data_view)
        self.sidesplitter.setStretchFactor(1,1)

        self.filter_widget = self.buildFilterWidget()
        self.sidesplitter.addWidget(self.filter_widget)
        self.sidesplitter.setStretchFactor(1,0)

        layout.addWidget(self.sidesplitter)

        # Apply buttons
        buttonWidget = QWidget()
        buttonLayout = QHBoxLayout(buttonWidget)
        self.applyButton = QPushButton("Apply")
        self.applyButton.clicked.connect(self.applyFilter)
        self.closeButton = QPushButton("Apply & Close")
        self.closeButton.clicked.connect(self.applyCloseFilter)
        buttonLayout.addWidget(self.applyButton)
        buttonLayout.addWidget(self.closeButton)
        buttonWidget.setLayout(buttonLayout)

        layout.addWidget(buttonWidget)
        self.setLayout(layout)

    def applyFilter(self):
        """Emits the applySignal with the Clause object currently
           represented by this FilterTab.
        """
        num_clauses = len(self.clause_list)
        if num_clauses == 0:
            self.applySignal.emit(None)
        else:
            self.applySignal.emit(Clause("and", *self.clause_dict.values()))

    def applyCloseFilter(self):
        """Calls applyFilter and then closes the containing TabDialog."""
        self.applyFilter()
        self.parent.close()

    def buildFilterWidget(self):
        """Creates the filter portion of the widget by laying out
           the subwidgets for relations, workspace and existing
           clauses.
        """
        filter_widget = QWidget()
        filter_layout = QVBoxLayout(filter_widget)

        filter_layout.addWidget(self.buildRelationsWidget())
        filter_layout.addItem(QSpacerItem(5,5))
        filter_layout.addWidget(self.buildWorkFrame())
        filter_layout.addItem(QSpacerItem(5,5))
        filter_layout.addWidget(self.buildFilterListView())

        filter_widget.setLayout(filter_layout)
        return filter_widget

    def buildFilterListView(self):
        """Creates the QListView that contains all of the basic Clause
           objects.
        """
        groupBox = QGroupBox("Clauses")
        layout = QVBoxLayout(groupBox)

        self.list_view = QListView(groupBox)
        self.list_view.setModel(self.clause_model)
        layout.addWidget(self.list_view)

        layout.addItem(QSpacerItem(5,5))
        self.delButton = QPushButton("Remove Selected Clause")
        self.delButton.clicked.connect(self.deleteClause)
        layout.addWidget(self.delButton)

        groupBox.setLayout(layout)
        return groupBox

    def buildWorkFrame(self):
        """Creates the grouped set of widgets that allow users to build
           basic Clause objects.
        """
        groupBox = QGroupBox("Clause Workspace")
        layout = QHBoxLayout(groupBox)

        attributeCompleter = QCompleter(self.attributes)
        attributeCompleter.setCompletionMode(QCompleter.InlineCompletion)
        self.dropAttribute = DropLineEdit(self, self.mframe.agent.datatree, "",
            attributeCompleter)
        self.dropRelation = DropTextLabel("__")
        self.dropValue = FilterValueLineEdit(groupBox,
            self.mframe.agent.datatree, self.dropAttribute)

        # Clear dropValue when dropAttribute changes
        self.dropAttribute.textChanged.connect(self.dropValue.clear)

        # Enter in dropValue works like addButton
        self.dropValue.returnPressed.connect(self.addClause)

        self.addButton = QPushButton("Add", groupBox)
        self.addButton.clicked.connect(self.addClause)
        layout.addWidget(self.dropAttribute)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.dropRelation)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.dropValue)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.addButton)

        groupBox.setLayout(layout)
        return groupBox

    def buildRelationsWidget(self):
        """Creates the set of draggable relations. These relations are
           whatever is available in the relations dict of Table.
        """
        relations_widget = QWidget()
        layout = QHBoxLayout(relations_widget)

        for relation in Table.relations:
            layout.addWidget(DragTextLabel(relation))

        relations_widget.setLayout(layout)
        return relations_widget

    def addClause(self):
        """Adds a basic Clause to the current filter."""
        if self.dropRelation.text() in Table.relations \
            and len(self.dropValue.text()) > 0 \
            and len(self.dropAttribute.text()) > 0:

            clause = Clause(self.dropRelation.text(),
                TableAttribute(self.dropAttribute.text()),
                self.dropValue.text())

            # Guard double add
            if str(clause) not in self.clause_dict:
                self.clause_list.append(str(clause))
                self.clause_dict[str(clause)] = clause
                self.clause_model.setStringList(self.clause_list)

    def deleteClause(self):
        """Removes the selected basic Clause objects from the current
           filter.
        """
        clause = self.clause_model.data(
            self.list_view.selectedIndexes()[0], Qt.DisplayRole)
        if clause is not None and clause in self.clause_list:
            self.clause_list.remove(clause)
            del self.clause_dict[clause]
            self.clause_model.setStringList(self.clause_list)
Ejemplo n.º 25
0
 def resizeEvent(self, event):
     QListView.resizeEvent(self, event)
     self.reload()
Ejemplo n.º 26
0
    def __init__(self):

        QListView.__init__(self)
Ejemplo n.º 27
0
class _SummaryOptionsToolItem(_ResultsToolItem):

    def _initUI(self):
        # Variables
        self._parameter_getters = {}

        def _program_getter(options):
            programs = list(options.programs)
            if len(programs) == 1:
                return programs[0]
            else:
                return list(programs)
        self._parameter_getters['program'] = _program_getter

        options = self.options()
        for name, getter in iter_getters(options):
            values = np.array(getter(options), ndmin=1)
            if len(values) < 2:
                continue
            self._parameter_getters[name] = getter

        # Actions
        act_add_series = QAction(getIcon("list-add"), "Add series", self)
        act_remove_series = QAction(getIcon("list-remove"), "Remove series", self)
        act_clear_series = QAction(getIcon("edit-clear"), "Clear", self)

        # Widgets
        self._cb_result_key = QComboBox()

        self._cb_x_parameter = QComboBox()
        self._cb_x_parameter.addItems(list(self._parameter_getters.keys()))

        self._lst_series = QListView()
        self._lst_series.setModel(_SeriesModel())

        tlb_series = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_series.addWidget(spacer)
        tlb_series.addAction(act_add_series)
        tlb_series.addAction(act_remove_series)
        tlb_series.addAction(act_clear_series)

        self._chk_normalize = QCheckBox('Normalize series')

        # Layouts
        layout = _ResultsToolItem._initUI(self)
        layout.addRow("Result", self._cb_result_key)
        layout.addRow("X parameter", self._cb_x_parameter)
        layout.addRow("Series", self._lst_series)
        layout.addRow(tlb_series)
        layout.addRow(self._chk_normalize)

        # Signals
        act_add_series.triggered.connect(self._onAddSeries)
        act_remove_series.triggered.connect(self._onRemoveSeries)
        act_clear_series.triggered.connect(self._onClearSeries)
        self._lst_series.doubleClicked.connect(self._onSeriesDoubleClicked)
        self._cb_result_key.currentIndexChanged.connect(self._onResultKeyChanged)
        self._chk_normalize.stateChanged.connect(self.stateChanged)

        # Defaults
        keys = set()
        for container in self.results():
            for key, result in container.items():
                if not isinstance(result, _SummarizableResult):
                    continue
                keys.add(key)
        self._cb_result_key.addItems(sorted(keys))

        return layout

    def _onResultKeyChanged(self):
        ndim = self._getResultDimensions()
        self._cb_x_parameter.setEnabled(ndim == 1)

    def _onAddSeries(self):
        # Dialog
        result_key = self._cb_result_key.currentText()

        if self._getResultDimensions() > 1:
            x_parameter_name = None
        else:
            x_parameter_name = self._cb_x_parameter.currentText()

        dialog = _SeriesDialog(self.results(), result_key,
                               self._parameter_getters, x_parameter_name)
        if not dialog.exec_():
            return

        # Create series
        series_name = dialog.name()
        parameter_value = dialog.parameterValue()
        summary_key = dialog.summaryKey()

        conditions = []
        for name, value in parameter_value.items():
            conditions.append((name, self._parameter_getters[name], value))

        model = self._lst_series.model()
        model.addSeries(_Series(series_name, conditions, summary_key))

        # Update widgets
        self._cb_result_key.setEnabled(False)
        self._cb_x_parameter.setEnabled(False)

        self.stateChanged.emit()

    def _onRemoveSeries(self):
        selection = self._lst_series.selectionModel().selection().indexes()
        if len(selection) == 0:
            QMessageBox.warning(self, "Series", "Select a row")
            return

        model = self._lst_series.model()
        for row in sorted(map(methodcaller('row'), selection), reverse=True):
            model.removeSeries(row)

        enabled = model.rowCount() == 0
        self._cb_result_key.setEnabled(enabled)
        self._cb_x_parameter.setEnabled(enabled)

        self.stateChanged.emit()

    def _onClearSeries(self):
        model = self._lst_series.model()
        model.clearSeries()

        self._cb_result_key.setEnabled(True)
        self._cb_x_parameter.setEnabled(True)

        self.stateChanged.emit()

    def _onSeriesDoubleClicked(self, index):
        series = self._lst_series.model().series(index.row())

        # Dialog
        result_key = self._cb_result_key.currentText()

        if self._getResultDimensions() > 1:
            x_parameter_name = None
        else:
            x_parameter_name = self._cb_x_parameter.currentText()

        dialog = _SeriesDialog(self.results(), result_key,
                               self._parameter_getters, x_parameter_name,
                               series)
        if not dialog.exec_():
            return

        # Create series
        series_name = dialog.name()
        parameter_value = dialog.parameterValue()
        summary_key = dialog.summaryKey()

        conditions = []
        for name, value in parameter_value.items():
            conditions.append((name, self._parameter_getters[name], value))

        model = self._lst_series.model()
        model.updateSeries(index.row(),
                           _Series(series_name, conditions, summary_key))

        self.stateChanged.emit()

    def _getResultDimensions(self):
        result_key = self._cb_result_key.currentText()

        for container in self.results():
            try:
                result = container[result_key]
            except KeyError:
                continue
            ndim = result.get_dimensions()

        return ndim

    def resultKey(self):
        return self._cb_result_key.currentText() or None

    def xParameterName(self):
        if self._getResultDimensions() > 1:
            return None
        return self._cb_x_parameter.currentText() or None

    def xParameterGetter(self):
        if self._getResultDimensions() > 1:
            return None
        text = self._cb_x_parameter.currentText()
        return self._parameter_getters.get(text)

    def listSeries(self):
        return self._lst_series.model().listSeries()

    def isNormalize(self):
        return self._chk_normalize.isChecked()
Ejemplo n.º 28
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle('Runner')
        self.setMinimumWidth(750)

        # Runner
        self._runner = None

        self._running_timer = QTimer()
        self._running_timer.setInterval(500)

        # Widgets
        self._dlg_progress = QProgressDialog()
        self._dlg_progress.setRange(0, 100)
        self._dlg_progress.setModal(True)
        self._dlg_progress.hide()

        lbl_outputdir = QLabel("Output directory")
        self._txt_outputdir = DirBrowseWidget()

        max_workers = cpu_count() #@UndefinedVariable
        lbl_workers = QLabel('Number of workers')
        self._spn_workers = QSpinBox()
        self._spn_workers.setRange(1, max_workers)
        self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        lbl_max_workers = QLabel('(max: %i)' % max_workers)

        self._chk_overwrite = QCheckBox("Overwrite existing results in output directory")
        self._chk_overwrite.setChecked(True)

        self._lbl_available = QLabel('Available')
        self._lst_available = QListView()
        self._lst_available.setModel(_AvailableOptionsListModel())
        self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection)

        tlb_available = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_available.addWidget(spacer)
        act_open = tlb_available.addAction(getIcon("document-open"), "Open")
        act_open.setShortcut(QKeySequence.Open)
        tlb_available.addSeparator()
        act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove")
        act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear")

        self._btn_addtoqueue = QPushButton(getIcon("go-next"), "")
        self._btn_addtoqueue.setToolTip("Add to queue")
        self._btn_addtoqueue.setEnabled(False)

        self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "")
        self._btn_addalltoqueue.setToolTip("Add all to queue")
        self._btn_addalltoqueue.setEnabled(False)

        self._lbl_options = QLabel('Queued/Running/Completed')
        self._tbl_options = QTableView()
        self._tbl_options.setModel(_StateOptionsTableModel())
        self._tbl_options.setItemDelegate(_StateOptionsItemDelegate())
        self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection)
        self._tbl_options.setColumnWidth(1, 60)
        self._tbl_options.setColumnWidth(2, 80)
        header = self._tbl_options.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Interactive)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.setResizeMode(2, QHeaderView.Fixed)
        header.setResizeMode(3, QHeaderView.Stretch)

        self._btn_start = QPushButton(getIcon("media-playback-start"), "Start")

        self._btn_cancel = QPushButton("Cancel")
        self._btn_cancel.setEnabled(False)

        self._btn_close = QPushButton("Close")

        self._btn_import = QPushButton("Import")
        self._btn_import.setEnabled(False)

        # Layouts
        layout = QVBoxLayout()

        sublayout = QGridLayout()
        sublayout.addWidget(lbl_outputdir, 0, 0)
        sublayout.addWidget(self._txt_outputdir, 0, 1)
        sublayout.addWidget(lbl_workers, 1, 0)

        subsublayout = QHBoxLayout()
        subsublayout.addWidget(self._spn_workers)
        subsublayout.addWidget(lbl_max_workers)
        sublayout.addLayout(subsublayout, 1, 1)
        layout.addLayout(sublayout)

        sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3)

        sublayout = QGridLayout()
        sublayout.setColumnStretch(0, 1)
        sublayout.setColumnStretch(2, 3)
        sublayout.addWidget(self._lbl_available, 0, 0)
        sublayout.addWidget(self._lst_available, 1, 0)
        sublayout.addWidget(tlb_available, 2, 0)

        subsublayout = QVBoxLayout()
        subsublayout.addStretch()
        subsublayout.addWidget(self._btn_addtoqueue)
        subsublayout.addWidget(self._btn_addalltoqueue)
        subsublayout.addStretch()
        sublayout.addLayout(subsublayout, 1, 1)

        sublayout.addWidget(self._lbl_options, 0, 2)
        sublayout.addWidget(self._tbl_options, 1, 2)
        layout.addLayout(sublayout)

        sublayout = QHBoxLayout()
        sublayout.addStretch()
        sublayout.addWidget(self._btn_import)
        sublayout.addWidget(self._btn_start)
        sublayout.addWidget(self._btn_cancel)
        sublayout.addWidget(self._btn_close)
        layout.addLayout(sublayout)

        self.setLayout(layout)

        # Signal
        self._running_timer.timeout.connect(self._onRunningTimer)

        act_open.triggered.connect(self._onOpen)
        act_remove.triggered.connect(self._onRemove)
        act_clear.triggered.connect(self._onClear)

        self._btn_addtoqueue.released.connect(self._onAddToQueue)
        self._btn_addalltoqueue.released.connect(self._onAddAllToQueue)
        self._btn_start.released.connect(self._onStart)
        self._btn_cancel.released.connect(self._onCancel)
        self._btn_close.released.connect(self._onClose)
        self._btn_import.released.connect(self._onImport)

        self.options_added.connect(self._onOptionsAdded)
        self.options_running.connect(self._onOptionsRunning)
        self.options_simulated.connect(self._onOptionsSimulated)
        self.options_error.connect(self._onOptionsError)
        self.results_error.connect(self._onResultsError)

        # Defaults
        settings = get_settings()
        section = settings.add_section('gui')
        if hasattr(section, 'outputdir'):
            self._txt_outputdir.setPath(section.outputdir)
        if hasattr(section, 'maxworkers'):
            self._spn_workers.setValue(int(section.maxworkers))
        if hasattr(section, 'overwrite'):
            state = True if section.overwrite.lower() == 'true' else False
            self._chk_overwrite.setChecked(state)
Ejemplo n.º 29
0
class FileBrowser(QMainWindow):
    """Example file browsing widget. Based of the C++ example."""
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()

    def activated(self, index):
        fileInfo = self.fileSystemModel.fileInfo(index)

        if fileInfo.isDir() and fileInfo.fileName() != '.':
            if fileInfo.fileName() == '..':
                parent = self.view.rootIndex().parent()

                fileInfo = self.fileSystemModel.fileInfo(parent)

                if fileInfo.absoluteFilePath() == self.rootPath:
                    self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)

                self.view.setRootIndex(parent)

            else:
                self.fileSystemModel.setFilter(QDir.AllEntries | QDir.AllDirs)
                self.view.setRootIndex(index)

            self.setWindowTitle(fileInfo.fileName())
        else:
            if fileInfo.fileName() == '.':
                fileInfo = self.fileSystemModel.fileInfo(self.view.rootIndex())

            widget = DocumentPropertiesWidget(fileInfo, self.gallery, self)
            widget.setWindowFlags(self.window().windowFlags() | Qt.Dialog)
            widget.setAttribute(Qt.WA_DeleteOnClose)
            widget.setWindowModality(Qt.WindowModal)
            widget.show()

    def browseAudio(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.MusicLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Audio"))

    def browseDocuments(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Documents"))

    def browseImages(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.PicturesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Images"))

    def browseVideos(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Videos"))
Ejemplo n.º 30
0
class FileBrowser(QMainWindow):
    """Example file browsing widget. Based of the C++ example."""
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()

    def activated(self, index):
        fileInfo = self.fileSystemModel.fileInfo(index)

        if fileInfo.isDir() and fileInfo.fileName() != '.':
            if fileInfo.fileName() == '..':
                parent = self.view.rootIndex().parent()

                fileInfo = self.fileSystemModel.fileInfo(parent)

                if fileInfo.absoluteFilePath() == self.rootPath:
                    self.fileSystemModel.setFilter(QDir.AllEntries
                                                   | QDir.NoDotAndDotDot
                                                   | QDir.AllDirs)

                self.view.setRootIndex(parent)

            else:
                self.fileSystemModel.setFilter(QDir.AllEntries | QDir.AllDirs)
                self.view.setRootIndex(index)

            self.setWindowTitle(fileInfo.fileName())
        else:
            if fileInfo.fileName() == '.':
                fileInfo = self.fileSystemModel.fileInfo(self.view.rootIndex())

            widget = DocumentPropertiesWidget(fileInfo, self.gallery, self)
            widget.setWindowFlags(self.window().windowFlags() | Qt.Dialog)
            widget.setAttribute(Qt.WA_DeleteOnClose)
            widget.setWindowModality(Qt.WindowModal)
            widget.show()

    def browseAudio(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.MusicLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Audio"))

    def browseDocuments(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.DocumentsLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Documents"))

    def browseImages(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.PicturesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Images"))

    def browseVideos(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.MoviesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Videos"))
Ejemplo n.º 31
0
class MainWindow(QMainWindow):
	def __init__(self, parent = None):
		super().__init__(parent)
		
		self.Logger = private_logger.create('MainWindow.py')
		
		self.Logger.debug('Create MainWindow.')
		self.setAcceptDrops(True)
		self.doLayout()
		self.Logger.debug('Created MainWindow.')

	def dropEvent(self, event):
		self.Logger.debug('Drop down files')
		self.FileListModel.clear()
		source = event.mimeData()
		filepaths = source.urls()
		self.Logger.debug('Drop on %s', filepaths)
		self.FileListModel.appendRow( [QStandardItem(path.toLocalFile()) for path in filepaths] )

	def dragEnterEvent(self, event):
		self.Logger.debug('Came to drop down.')
		mime = event.mimeData()
		if mime.hasUrls():
			self.Logger.debug('Accepted drop down items.')
			event.accept()
		else:
			self.Logger.debug('Rejected drop down items.')
			event.ignore()
		pass

	@Slot()
	def onConvert(self):
		error_files = list()
		index = 0
		while(True):
			item = self.FileListModel.item(index)
			if type(item) is QStandardItem:
				filepath = item.text()
				print(filepath)
				if(filepath == ''):
					continue
				try:
					self.convert(filepath)
				except Exception as e:
					error_files.append(filepath)
					break

			elif item is None or item == 0:
				break

			index += 1
		if(len(error_files) == 0):
			QMessageBox.information(self, self.tr('完了'),	 self.tr('変換が完了しました'))
		else:
			QMessageBox.critical(self, self.tr('エラー'), self.tr('下記のファイルでエラーが発生しました。Safeモードをお試しください。\n' + '\n'.join(error_files)))

	def convert(self, filepath):
		self.Logger.info('Processing {0}.'.format(filepath))

		ppt = None
		if self.SafeModeCheckbox.checkState():
			ppt = gpt.SafePresentation.SafePresentation(filepath)
		else:
			ppt = gpt.Presentation.Presentation(filepath)

		notes = ppt.getNoteTexts()
		filename, ext = os.path.splitext(filepath)
		with open(filename + '.txt', 'w+') as fp:
			for note in notes:
				fp.write('P.{0}\n'.format(note.Page))
				fp.write(note.Text)
				fp.write('\n')

	def doLayout(self):
		central_window = QWidget(self)
		vlayout = QVBoxLayout(central_window)

		self.FileListView = QListView(self)
		self.SafeModeCheckbox = QCheckBox(self.tr('Safeモードで読み込み(エラーが出る場合に使用ください。改行やページ番号等崩れる場合があります。)'), self)
		convert_button = QPushButton(self.tr('変換'), central_window)

		vlayout.addWidget(QLabel(self.tr('ドラッグ&ドロップでファイルを読み込みます'), self))
		vlayout.addWidget(self.FileListView)
		vlayout.addWidget(self.SafeModeCheckbox)
		vlayout.addWidget(convert_button)
		convert_button.clicked.connect(self.onConvert)

		self.FileListModel = QStandardItemModel(self)
		self.FileListModel.setHorizontalHeaderLabels([self.tr('ファイル名')])
		self.FileListView.setModel(self.FileListModel)
		self.FileListView.setAcceptDrops(True)

		self.setCentralWidget(central_window)
Ejemplo n.º 32
0
    def _initUI(self):
        # Variables
        self._parameter_getters = {}

        def _program_getter(options):
            programs = list(options.programs)
            if len(programs) == 1:
                return programs[0]
            else:
                return list(programs)
        self._parameter_getters['program'] = _program_getter

        options = self.options()
        for name, getter in iter_getters(options):
            values = np.array(getter(options), ndmin=1)
            if len(values) < 2:
                continue
            self._parameter_getters[name] = getter

        # Actions
        act_add_series = QAction(getIcon("list-add"), "Add series", self)
        act_remove_series = QAction(getIcon("list-remove"), "Remove series", self)
        act_clear_series = QAction(getIcon("edit-clear"), "Clear", self)

        # Widgets
        self._cb_result_key = QComboBox()

        self._cb_x_parameter = QComboBox()
        self._cb_x_parameter.addItems(list(self._parameter_getters.keys()))

        self._lst_series = QListView()
        self._lst_series.setModel(_SeriesModel())

        tlb_series = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_series.addWidget(spacer)
        tlb_series.addAction(act_add_series)
        tlb_series.addAction(act_remove_series)
        tlb_series.addAction(act_clear_series)

        self._chk_normalize = QCheckBox('Normalize series')

        # Layouts
        layout = _ResultsToolItem._initUI(self)
        layout.addRow("Result", self._cb_result_key)
        layout.addRow("X parameter", self._cb_x_parameter)
        layout.addRow("Series", self._lst_series)
        layout.addRow(tlb_series)
        layout.addRow(self._chk_normalize)

        # Signals
        act_add_series.triggered.connect(self._onAddSeries)
        act_remove_series.triggered.connect(self._onRemoveSeries)
        act_clear_series.triggered.connect(self._onClearSeries)
        self._lst_series.doubleClicked.connect(self._onSeriesDoubleClicked)
        self._cb_result_key.currentIndexChanged.connect(self._onResultKeyChanged)
        self._chk_normalize.stateChanged.connect(self.stateChanged)

        # Defaults
        keys = set()
        for container in self.results():
            for key, result in container.items():
                if not isinstance(result, _SummarizableResult):
                    continue
                keys.add(key)
        self._cb_result_key.addItems(sorted(keys))

        return layout