Exemplo n.º 1
0
class FileSystemView(QWidget):
    def __init__(self, dir_path):
        super().__init__()

        appWidth = 800
        appHeight = 300

        self.setWindowTitle('File System Viewer')
        self.setGeometry(300, 300, appWidth, appHeight)

        self.model = QFileSystemModel()
        self.model.setRootPath(dir_path)

        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setRootIndex(self.model.index(dirPath))
        self.tree.setColumnWidth(200, 250)
        self.tree.setAlternatingRowColors(True)

        layout = QVBoxLayout()
        layout.addWidget(self.tree)
        btnSelect = QPushButton("SELECT")
        layout.addWidget(btnSelect)

        self.setLayout(layout)
Exemplo n.º 2
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.resize(600,400)
        self.setWindowTitle("Treeview Example")

        self.treeview = QTreeView(self)

        self.treeview.model = QFileSystemModel()
        self.treeview.model.setRootPath(QDir.currentPath() )
        self.treeview.setModel(self.treeview.model)
        self.treeview.setColumnWidth(0, 200)

        self.setCentralWidget(self.treeview)

        self.treeview.clicked.connect(self.on_treeview_clicked)

# ---------------------------------------------------------------------

    @QtCore.pyqtSlot(QModelIndex)
    def on_treeview_clicked(self, index):
        indexItem = self.treeview.model.index(index.row(), 0, index.parent())

        # path or filename selected
        fileName = self.treeview.model.fileName(indexItem)
        # full path/filename selected
        filePath = self.treeview.model.filePath(indexItem)

        print(fileName)
        print(filePath)
def directory(app):
    #app = QApplication(sys.argv)

    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("File Directory")
    parser.addHelpOption()
    parser.addVersionOption()

    dontUseCustomDirectoryIconsOption = QCommandLineOption(
        'C', "Set QFileIconProvider.DontUseCustomDirectoryIcons")
    parser.addOption(dontUseCustomDirectoryIconsOption)
    parser.addPositionalArgument('', "The directory to start in.")
    parser.process(app)
    try:
        rootPath = parser.positionalArguments().pop(0)
    except IndexError:
        rootPath = None

    model = QFileSystemModel()
    model.setRootPath('')
    filter = ['*.db']  #filtering out just by db
    model.setNameFilters(filter)
    model.setNameFilterDisables(0)  #Only show the filtered .db paths
    #filename = model.filePath()
    #print(filename)

    if parser.isSet(dontUseCustomDirectoryIconsOption):
        model.iconProvider().setOptions(
            QFileIconProvider.DontUseCustomDirectoryIcons)
    tree = QTreeView()
    tree.setModel(model)
    if rootPath is not None:
        rootIndex = model.index(QDir.cleanPath(rootPath))
        if rootIndex.isValid():
            tree.setRootIndex(rootIndex)

    # Demonstrating look and feel features.
    tree.setAnimated(False)
    tree.setIndentation(20)
    tree.setSortingEnabled(True)

    availableSize = QApplication.desktop().availableGeometry(tree).size()
    tree.resize(availableSize / 2)
    tree.setColumnWidth(0, tree.width() / 3)

    tree.setWindowTitle("Directory View")
    tree.show()

    sys.exit(app.exec_())
Exemplo n.º 4
0
    def __init__(self):
        QMainWindow.__init__(self)

        items = []
        items.append(TreeNode("Root"))
        items[0].addChild(TreeNode(["Leaf A", "a", "b"]))
        items[0].addChild(TreeNode(["Leaf B", "c", "d"]))
        items[0].child(1).addChild(TreeNode(["Sub Leaf", "e", "f"]))

        self.setWindowTitle("Qt Demo")
        tree = QTreeView()
        tree.setModel(TreeModel(items))
        tree.setHeaderHidden(True)
        tree.setColumnWidth(0, 150)
        self.setCentralWidget(tree)
Exemplo n.º 5
0
class FileBrowser(QWidget):
    def __init__(self, dirPath):
        super(FileBrowser, self).__init__()
        appWidth = 800
        appHeight = 800
        self.setWindowTitle('File Browser')
        self.setGeometry(300, 300, appWidth, appHeight)
        self.model = QFileSystemModel()
        self.model.setRootPath(dirPath)
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setRootIndex(self.model.index(dirPath))
        self.tree.setColumnWidth(0, 250)
        self.tree.setAlternatingRowColors(True)
        layout = QVBoxLayout()
        layout.addWidget(self.tree)
        self.setLayout(layout)
Exemplo n.º 6
0
class FileSystemView(QWidget):
    def __init__(self, dir_path):
        super().__init__()
        self.setWindowTitle("Todos los archivos")
        self.setGeometry(300, 300, 800, 300)

        self.model = QFileSystemModel()
        self.model.setRootPath(dir_path)
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setRootIndex(self.model.index(dir_path))
        self.tree.setColumnWidth(300, 300)
        self.tree.setAlternatingRowColors(True)

        layout = QVBoxLayout()
        layout.addWidget(self.tree)

        self.setLayout(layout)
Exemplo n.º 7
0
class FileView(QWidget):
    def __init__(self, dir_path):
        super().__init__()
        # Setup Window
        self.setFixedSize(700, 300)
        self.setWindowTitle('File Viewer')
        self.setGeometry(640, 360, 700, 300)
        self.model = QFileSystemModel()
        self.model.setRootPath(dir_path)
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setRootIndex(self.model.index(dirPath))
        self.tree.setColumnWidth(0, 250)
        self.tree.setAlternatingRowColors(True)

        # Layout
        layout = QVBoxLayout()
        layout.addWidget(self.tree)
        self.setLayout(layout)
Exemplo n.º 8
0
class MyApp(QWidget):
    def __init__(self):
        super().__init__()

        self.path = "C:"
        self.index = None
        self.tv = QTreeView(self)
        self.model = QFileSystemModel()
        self.layout = QVBoxLayout()
        self.setUi()
        self.show()

    def setUi(self):
        self.setGeometry(300, 300, 700, 350)
        self.setWindowTitle("QFileSystemModel")
        self.model.setRootPath(self.path)
        self.tv.setModel(self.model)
        self.tv.setColumnWidth(0, 250)
        self.layout.addWidget(self.tv)
        self.setLayout(self.layout)

    def setIndex(self, index):
        self.index = index
Exemplo n.º 9
0
class FileSystemView(QWidget):
    def __init__(self, dir_path):
        super().__init__()
        appWidth = 800
        appHeight = 300
        self.setWindowTitle('File System Viewer')
        self.setGeometry(300, 300, appWidth, appHeight)

        self.model = QFileSystemModel()
        self.model.setRootPath(dir_path)
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setRootIndex(self.model.index(dirPath))
        self.tree.setColumnWidth(0, 250)
        self.tree.setAlternatingRowColors(True)

        layout = QVBoxLayout()
        self.photo = QLabel('Hola' + chr(10) + 'Caracola')
        layout.addWidget(self.tree)
        layout.addWidget(self.photo)
        self.setLayout(layout)
        self.tree.selectionModel().selectionChanged.connect(self.select)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space or event.key() == Qt.Key_Return:
            index = self.tree.selectedIndexes()[0]
            crawler = index.model().filePath(index)
            print(crawler)
        #self.tree.keyPressEvent(self, event)

    def select(self, index1):
        index = self.tree.selectedIndexes()[0]
        file_sel = index.model().filePath(index)
        if os.path.isfile(file_sel) and file_sel[-3:].upper() in 'JPG PNG':
            pixmap = QPixmap(file_sel)
            self.photo.setPixmap(pixmap)
            print(file_sel)
Exemplo n.º 10
0
class FileSystemView(QWidget):
   def __init__(self, dir_path):
      super().__init__()

      #TITULO Y DIMENSIONES DE LA VENTANA.
      self.setWindowTitle('File System Viewer')
      self.setGeometry(300, 300, 800, 300)

      #DEFINIR DIRECTORIO.
      self.model = QFileSystemModel()
      self.model.setRootPath(dir_path)

      #GENERAR VISTA DE ARCHIVOS Y CARPETAS.
      self.tree = QTreeView()
      self.tree.setModel(self.model)
      self.tree.setRootIndex(self.model.index(dirPath))
      self.tree.setColumnWidth(200,250)
      self.tree.setAlternatingRowColors(True)

      #MOSTRAR VENTANA CON LAS VISTA.
      layout = QVBoxLayout()
      layout.addWidget(self.tree)

      self.setLayout(layout)
Exemplo n.º 11
0
class KerningWindow(QWidget):

    def __init__(self, font, parent=None):
        super().__init__(parent, Qt.Window)
        self._font = font
        self._font.kerning.addObserver(
            self, "_kerningChanged", "Kerning.Changed")
        self._font.info.addObserver(self, "_fontInfoChanged", "Info.Changed")
        self.kerningView = QTreeView(self)
        self.kerningView.setModel(
            KerningDictModel(font.kerning, self.kerningView))
        self.kerningView.expandAll()
        metrics = self.kerningView.fontMetrics()
        self.kerningView.setColumnWidth(1, 8 * metrics.width("0"))
        hdr = self.kerningView.header()
        hdr.setStretchLastSection(False)
        hdr.setSectionResizeMode(0, hdr.Stretch)
        hdr.hide()

        layout = QVBoxLayout(self)
        layout.addWidget(self.kerningView)
        layout.setContentsMargins(0, 0, 0, 0)

        self.updateWindowTitle(font=font)
        self.readSettings()

    def readSettings(self):
        geometry = settings.kerningWindowGeometry()
        if geometry:
            self.restoreGeometry(geometry)

    def writeSettings(self):
        settings.setKerningWindowGeometry(self.saveGeometry())

    def updateWindowTitle(self, title=None, font=None):
        if title is None:
            title = self.tr("Kerning")
        if font is not None:
            title = "%s – %s %s" % (
                title, font.info.familyName, font.info.styleName)
        self.setWindowTitle(title)

    # -------------
    # Notifications
    # -------------

    def _kerningChanged(self, notification):
        model = self.kerningView.model()
        model.setupModelData(self._font.kerning)

    def _fontInfoChanged(self, notification):
        self.updateWindowTitle(font=self._font)

    # ----------
    # Qt methods
    # ----------

    def sizeHint(self):
        return QSize(280, 460)

    def moveEvent(self, event):
        self.writeSettings()

    resizeEvent = moveEvent

    def closeEvent(self, event):
        super().closeEvent(event)
        if event.isAccepted():
            self._font.kerning.removeObserver(self, "Kerning.Changed")
            self._font.info.removeObserver(self, "Info.Changed")
Exemplo n.º 12
0
class _LocatorDialog(QDialog):
    """Locator widget and implementation
    """

    def __init__(self, parent, commandClasses):
        QDialog.__init__(self, parent)
        self._terminated = False
        self._commandClasses = commandClasses

        self._createUi()

        self._loadingTimer = QTimer(self)
        self._loadingTimer.setSingleShot(True)
        self._loadingTimer.setInterval(200)
        self._loadingTimer.timeout.connect(self._applyLoadingCompleter)

        self._completerLoaderThread = _CompleterLoaderThread(self)

        self.finished.connect(self._terminate)

        self._command = None
        self._updateCurrentCommand()

    def _createUi(self):
        self.setWindowTitle(core.project().path().replace(os.sep, '/') or 'Locator')

        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(1)

        biggerFont = self.font()
        biggerFont.setPointSizeF(biggerFont.pointSizeF() * 2)
        self.setFont(biggerFont)

        self._edit = _CompletableLineEdit(self)
        self._edit.updateCurrentCommand.connect(self._updateCurrentCommand)
        self._edit.enterPressed.connect(self._onEnterPressed)
        self._edit.installEventFilter(self)  # catch Up, Down
        self._edit.setFont(biggerFont)
        self.layout().addWidget(self._edit)
        self.setFocusProxy(self._edit)

        self._table = QTreeView(self)
        self._table.setFont(biggerFont)
        self._model = _CompleterModel()
        self._table.setModel(self._model)
        self._table.setItemDelegate(HTMLDelegate(self._table))
        self._table.setRootIsDecorated(False)
        self._table.setHeaderHidden(True)
        self._table.clicked.connect(self._onItemClicked)
        self._table.setAlternatingRowColors(True)
        self._table.installEventFilter(self)  # catch focus and give to the edit
        self.layout().addWidget(self._table)

        width = QFontMetrics(self.font()).width('x' * 64)  # width of 64 'x' letters
        self.resize(width, width * 0.62)

    def _terminate(self):
        if not self._terminated:
            if self._command is not None:
                self._command.terminate()
                self._command = None

            self._edit.terminate()

            self._completerLoaderThread.terminate()
            if self._model:
                self._model.terminate()
            core.workspace().focusCurrentDocument()
            self._terminated = True

    def _updateCurrentCommand(self):
        """Try to parse line edit text and set current command
        """
        if self._terminated:
            return

        newCommand = self._parseCurrentCommand()

        if newCommand is not self._command:
            if self._command is not None:
                self._command.updateCompleter.disconnect(self._updateCompletion)
                self._command.terminate()

            self._command = newCommand
            if self._command is not None:
                self._command.updateCompleter.connect(self._updateCompletion)

        self._updateCompletion()

    def _updateCompletion(self):
        """User edited text or moved cursor. Update inline and TreeView completion
        """
        if self._command is not None:
            completer = self._command.completer()

            if completer is not None and completer.mustBeLoaded:
                self._loadingTimer.start()
                self._completerLoaderThread.loadCompleter(self._command, completer)
            else:
                self._applyCompleter(self._command, completer)
        else:
            self._applyCompleter(None, _HelpCompleter(self._commandClasses))

    def _applyLoadingCompleter(self):
        """Set 'Loading...' message
        """
        self._applyCompleter(None, StatusCompleter('<i>Loading...</i>'))

    def onCompleterLoaded(self, command, completer):
        """The method called from _CompleterLoaderThread when the completer is ready
        This code works in the GUI thread
        """
        self._applyCompleter(command, completer)

    def _applyCompleter(self, command, completer):
        """Apply completer. Called by _updateCompletion or by thread function when Completer is constructed
        """
        self._loadingTimer.stop()

        if command is not None:
            command.onCompleterLoaded(completer)

        if completer is None:
            completer = _HelpCompleter([command])

        if self._edit.cursorPosition() == len(self._edit.text()):  # if cursor at the end of text
            self._edit.setInlineCompletion(completer.inline())

        self._model.setCompleter(completer)
        if completer.columnCount() > 1:
            self._table.resizeColumnToContents(0)
            self._table.setColumnWidth(0, self._table.columnWidth(0) + 20)  # 20 px spacing between columns

        selItem = completer.autoSelectItem()
        if selItem:
            index = self._model.createIndex(selItem[0],
                                            selItem[1])
            self._table.setCurrentIndex(index)

    def _onItemClicked(self, index):
        """Item in the TreeView has been clicked.
        Open file, if user selected it
        """
        if self._command is not None:
            fullText = self._model.completer.getFullText(index.row())
            if fullText is not None:
                self._command.onItemClicked(fullText)
                if self._tryExecCurrentCommand():
                    self.accept()
                    return
                else:
                    self._edit.setText(self._command.lineEditText())
                    self._updateCurrentCommand()

        self._edit.setFocus()

    def _onEnterPressed(self):
        """User pressed Enter or clicked item. Execute command, if possible
        """
        if self._table.currentIndex().isValid():
            self._onItemClicked(self._table.currentIndex())
        else:
            self._tryExecCurrentCommand()

    def _tryExecCurrentCommand(self):
        if self._command is not None and self._command.isReadyToExecute():
            self._command.execute()
            self.accept()
            return True
        else:
            return False

    def _chooseCommand(self, words):
        for cmd in self._commandClasses:
            if cmd.command == words[0]:
                return cmd, words[1:]

        isPath = words and (words[0].startswith('/') or
                            words[0].startswith('./') or
                            words[0].startswith('../') or
                            words[0].startswith('~/') or
                            words[0][1:3] == ':\\' or
                            words[0][1:3] == ':/'
                            )
        isNumber = len(words) == 1 and all([c.isdigit() for c in words[0]])

        def matches(cmd):
            if isPath:
                return cmd.isDefaultPathCommand
            elif isNumber:
                return cmd.isDefaultNumericCommand
            else:
                return cmd.isDefaultCommand

        for cmd in self._commandClasses:
            if matches(cmd):
                return cmd, words

    def _parseCurrentCommand(self):
        """ Parse text and try to get (command, completable word index)
        Return None if failed to parse
        """
        # Split line
        text = self._edit.commandText()
        words = splitLine(text)
        if not words:
            return None

        # Find command
        cmdClass, args = self._chooseCommand(words)

        if isinstance(self._command, cmdClass):
            command = self._command
        else:
            command = cmdClass()

        # Try to make command object
        try:
            command.setArgs(args)
        except InvalidCmdArgs:
            return None
        else:
            return command

    def eventFilter(self, obj, event):
        if obj is self._edit:
            if event.type() == QEvent.KeyPress and \
               event.key() in (Qt.Key_Up, Qt.Key_Down, Qt.Key_PageUp, Qt.Key_PageDown):
                return self._table.event(event)
        elif obj is self._table:
            if event.type() == QEvent.FocusIn:
                self._edit.setFocus()
                return True

        return False
Exemplo n.º 13
0
class FileSelect(QMainWindow, QWidget):
    def __init__(self):
        super(FileSelect, self).__init__()
        self.setWindowTitle("Printing Booth Systems")
        global file, pagecount, total, enabler, copies, colormode, page
        file = ""
        pagecount = 0
        total = 0.0
        copies = "1"
        colormode = ""
        page = ""

        widget = QWidget()
        layout = QVBoxLayout()
        self.index = QModelIndex()
        self.model = QFileSystemModel()
        self.tree = QTreeView()
        self.model.setRootPath(QDir.currentPath())  #ignore
        self.model.setNameFilters(["*.pdf"])

        idx = self.model.index("/media/pi/")

        self.tree.setModel(self.model)
        self.tree.setRootIndex(idx)
        self.tree.setColumnWidth(0, 250)
        self.tree.setAlternatingRowColors(True)

        layout.addWidget(self.tree)
        widget.setLayout(layout)
        self.setCentralWidget(widget)
        widget.setFixedWidth(600)
        self.tree.setFont(QFont('Arial', 30))
        self.tree.hideColumn(1)
        self.tree.hideColumn(2)
        self.tree.hideColumn(3)
        self.tree.clicked.connect(self.on_treeView_clicked)

        self.btn1 = QPushButton('Select', self)
        self.btn1.setGeometry(620, 120, 150, 90)
        self.btn1.clicked.connect(self.slot_btn1_function)

        self.btn2 = QPushButton('Cancel', self)
        self.btn2.setGeometry(620, 300, 150, 90)
        self.btn2.clicked.connect(self.slot_btn2_function)

    def slot_btn1_function(self):
        if file.lower().endswith('.pdf'):
            self.p = Preview()
            self.p.showFullScreen()
            self.hide()
        else:
            pass

    def slot_btn2_function(self):
        self.mw = MainWindow()
        self.mw.showFullScreen()
        self.hide()

    def on_treeView_clicked(self, index):
        global file
        indexItem = self.model.index(index.row(), 0, index.parent())
        filePath = self.model.filePath(indexItem)
        file = filePath
Exemplo n.º 14
0
    class App(QWidget):
        def __init__(self):
            super().__init__()
            self.left = 100
            self.top = 100
            self.width = 1200
            self.height = 720
            self.setWindowTitle('Mammogram Prediction')
            self.setGeometry(self.left, self.top, self.width, self.height)

            self.initUI()

        def initUI(self):
            # Widget for showing picture. The QLabel gets a Pixmap added to it to show picture
            self.picture_name_label = QLabel(currently_selected_picture)
            self.picture_label = QLabel()
            self.prediction_text = QTextEdit()
            self.prediction_text.setReadOnly(True)
            self.model_label = QLabel()

            self.init_picture_and_predictions()

            self.resized_picture = self.picture.scaled(299, 299,
                                                       Qt.KeepAspectRatio,
                                                       Qt.FastTransformation)
            self.picture_label.setPixmap(self.resized_picture)
            self.picture_label.setMinimumWidth(299)
            self.picture_label.setMinimumHeight(299)
            self.picture_label.setContentsMargins(0, 19, 0, 0)

            # Tree and List view for file directory overview of pictures
            self.picture_directory_label = QLabel('Select a Picture:')
            picture_dir_path = 'pictures\\'
            picture_file_path = 'pictures\\'
            self.treeview_picture = QTreeView()
            self.listview_picture = QListView()

            self.dirModel_picture = QFileSystemModel()
            self.dirModel_picture.setRootPath(picture_dir_path)
            self.dirModel_picture.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)

            self.fileModel_picture = QFileSystemModel()
            self.fileModel_picture.setRootPath(picture_file_path)  #
            self.fileModel_picture.setFilter(QDir.NoDotAndDotDot | QDir.Files)

            self.treeview_picture.setModel(self.dirModel_picture)
            self.listview_picture.setModel(self.fileModel_picture)

            self.treeview_picture.setRootIndex(
                self.dirModel_picture.index(picture_dir_path))
            self.listview_picture.setRootIndex(
                self.fileModel_picture.index(picture_file_path))  #
            self.treeview_picture.setCurrentIndex(
                self.dirModel_picture.index(0, 0))

            self.treeview_picture.clicked.connect(
                self.on_picture_treeview_clicked)
            self.listview_picture.clicked.connect(
                self.on_picture_listview_clicked)
            self.treeview_picture.setColumnHidden(1, True)
            self.treeview_picture.setColumnWidth(0, 275)
            self.treeview_picture.setMinimumWidth(500)
            self.listview_picture.setMinimumWidth(500)

            # List view for file directory overview of five label models
            self.model_directory_label = QLabel('Select a Five Label Model:')
            model_path = 'trained_five_Models\\'
            self.listview_model = QListView()
            self.dirModel_model = QFileSystemModel()

            self.dirModel_model.setRootPath(model_path)
            self.dirModel_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)

            self.listview_model.setModel(self.dirModel_model)
            self.listview_model.setRootIndex(
                self.dirModel_model.index(model_path))
            self.listview_model.clicked.connect(self.on_model_listview_clicked)

            # List view for file directory overview of binary models
            self.model_binary_directory_label = QLabel(
                'Select a Binary Model:')
            model_binary_path = 'trained_binary_Models\\'
            self.listview_model_binary = QListView()
            self.dirModel_model_binary = QFileSystemModel()

            self.dirModel_model_binary.setRootPath(model_binary_path)
            self.dirModel_model_binary.setFilter(QDir.NoDotAndDotDot
                                                 | QDir.AllDirs)

            self.listview_model_binary.setModel(self.dirModel_model_binary)
            self.listview_model_binary.setRootIndex(
                self.dirModel_model_binary.index(model_binary_path))
            self.listview_model_binary.setSelectionMode(
                QAbstractItemView.MultiSelection)
            self.listview_model_binary.clicked.connect(
                self.on_model_binary_listview_clicked)

            # Layout handling.

            # self.gridlayout = QGridLayout()
            # self.gridlayout.addWidget(self.model_directory_label, 0, 0)
            # self.gridlayout.setColumnStretch(-15, -11)
            # self.gridlayout.addWidget(self.listview_model, 1, 0)
            # self.gridlayout.addWidget(self.picture_directory_label, 2, 0)
            # self.gridlayout.addWidget(self.treeview_picture, 3, 0)
            #
            # self.gridlayout.addWidget(self.model_binary_directory_label, 0, 1)
            # self.gridlayout.addWidget(self.listview_model_binary, 1, 1)
            # self.gridlayout.addWidget(self.listview_picture, 3, 1)
            #
            # self.gridlayout.addWidget(self.picture_label, 0, 2)
            # self.gridlayout.addWidget(self.picture_name_label, 1, 2)
            # self.gridlayout.addWidget(self.prediction_text, 3, 2)

            self.vbox = QVBoxLayout()
            self.vbox_left = QVBoxLayout()
            self.vbox_right = QVBoxLayout()
            self.hbox_outer = QHBoxLayout()
            self.hbox_top = QHBoxLayout()
            self.hbox_buttom = QHBoxLayout()
            self.vbox_five_label = QVBoxLayout()
            self.vbox_binary = QVBoxLayout()

            self.vbox.addLayout(self.hbox_outer)
            self.hbox_outer.addLayout(self.vbox_left)
            self.hbox_outer.addLayout(self.vbox_right)
            self.vbox_left.addLayout(self.hbox_top)
            self.hbox_top.addLayout(self.vbox_five_label)
            self.hbox_top.addLayout(self.vbox_binary)

            self.vbox_five_label.addWidget(self.model_directory_label)
            self.vbox_five_label.addWidget(self.listview_model)
            self.vbox_binary.addWidget(self.model_binary_directory_label)
            self.vbox_binary.addWidget(self.listview_model_binary)

            self.vbox_left.addWidget(self.picture_directory_label)
            self.vbox_left.addLayout(self.hbox_buttom)
            self.hbox_buttom.addWidget(self.treeview_picture)
            self.hbox_buttom.addWidget(self.listview_picture)

            self.vbox_right.addWidget(self.picture_label,
                                      alignment=Qt.AlignHCenter)
            self.vbox_right.addWidget(self.picture_name_label,
                                      alignment=Qt.AlignHCenter)
            self.vbox_right.addWidget(self.model_label,
                                      alignment=Qt.AlignHCenter)
            self.vbox_right.addWidget(self.prediction_text)

            self.vbox_right.setAlignment(Qt.AlignCenter)

            self.setLayout(self.vbox)
            self.sizePolicy = QSizePolicy(QSizePolicy.Minimum,
                                          QSizePolicy.Preferred)
            self.setSizePolicy(self.sizePolicy)
            self.show()

        def init_picture_and_predictions(self):
            if currently_selected_picture == 'Currently No Image Selected':
                self.picture = QtGui.QPixmap('GUI/no_image_selected.png')
                self.prediction_text.setText('')

        def on_picture_treeview_clicked(self, index):
            pathof_selected_dir = self.dirModel_picture.fileInfo(
                index).absoluteFilePath()
            self.listview_picture.setRootIndex(
                self.fileModel_picture.setRootPath(pathof_selected_dir))

        def on_picture_listview_clicked(self, index):
            global currently_selected_model
            global currently_selected_model_name
            global currently_selected_picture

            currently_selected_picture = self.fileModel_picture.fileInfo(
                index).absoluteFilePath()

            try:
                Image.open(currently_selected_picture)
                self.picture_name_label.setText(currently_selected_picture)
                self.picture_label.setPixmap(
                    QtGui.QPixmap(currently_selected_picture))
            except IOError:
                print('Exception: Chosen file is not a picture')

            # Checks if the selected picture has size 299
            image_in = cv2.imread(currently_selected_picture)
            size = image_in.shape[:2]
            if size[0] == 299:
                if currently_selected_model is not None:
                    for model in currently_selected_model:
                        new_prediction = self.makePrediction(
                            model,
                            self.convertPictureToNumpy(
                                currently_selected_picture))
                        split = currently_selected_model_name.split('_')
                        if split[4] in ('neg', 'bc', 'bm', 'mc', 'mm'):
                            self.show_binary_prediction(
                                new_prediction, split[4])
                        else:
                            self.show_five_prediction(new_prediction)
                else:
                    self.prediction_text.setText(
                        'No Model is Chosen for Prediction. Choose one to the left.'
                    )
            # If the selected picture is not size 299 it will be padded and cropped
            else:
                cropped_images = resize_image_padding(
                    currently_selected_picture)
                self.listview_picture.setRootIndex(
                    self.fileModel_picture.setRootPath('pictures/cropped/%s' %
                                                       cropped_images))

        def on_model_listview_clicked(self, index):
            global currently_selected_model
            global currently_selected_picture

            currently_selected_model = []

            selected_model_path = self.dirModel_model.fileInfo(
                index).absoluteFilePath()
            currently_selected_model.append(self.getModel(selected_model_path))

            self.model_label.setText(currently_selected_model_name[0])

            if currently_selected_picture != 'Currently No Image Selected':
                for model in currently_selected_model:
                    new_prediction = self.makePrediction(
                        model,
                        self.convertPictureToNumpy(currently_selected_picture))
                    self.show_five_prediction(new_prediction)

        def on_model_binary_listview_clicked(self):
            global currently_selected_model
            global currently_selected_picture
            currently_selected_model = []

            self.prediction_text.setText('')
            self.model_label.setText('')

            for x in self.listview_model_binary.selectedIndexes():
                selected_model_path = self.dirModel_model_binary.fileInfo(
                    x).absoluteFilePath()
                currently_selected_model.append(
                    self.getModel(selected_model_path))
            # if not currently_selected_model_name:
            #     self.model_label.setText(currently_selected_model_name)

            if currently_selected_picture != 'Currently No Image Selected':
                for y in currently_selected_model:
                    new_prediction = self.makePrediction(
                        y,
                        self.convertPictureToNumpy(currently_selected_picture))
                    self.show_binary_prediction(new_prediction, y.category)

        def getModel(self, model_path):
            global currently_selected_model_name
            currently_selected_model_name = []

            split = os.path.split(model_path)[1].split('_')
            model_version = split[0] + '_' + split[1] + '_' + split[
                2] + '_' + split[3]
            currently_selected_model_name.append(os.path.split(model_path)[1])

            model = getattr(sys.modules[__name__], model_version)()
            checkpoint_path = model_path + '/cp.ckpt'
            model.load_weights(checkpoint_path)
            return model

        def makePrediction(self, input_model, input_picture):
            image = tf.reshape(input_picture, [-1, 299, 299, 1])
            image = tf.cast(image, tf.float32)
            image = image / 255.0
            return input_model.predict(image)

        def convertPictureToNumpy(self, filename):
            img = Image.open(filename)
            np_array = np.array(img, dtype='uint8')
            return np_array

        def show_five_prediction(self, prediction):
            self.prediction_text.setText(
                "Probability of Negative: %s" % prediction[0, 0] +
                "\n\nProbability of Benign Calcification: %s" %
                prediction[0, 1] +
                "\n\nProbability of Benign Mass: %s" % prediction[0, 2] +
                "\n\nProbability of Malignant Calcification: %s" %
                prediction[0, 3] +
                "\n\nProbability of Malignant Mass: %s" % prediction[0, 4])

        def show_binary_prediction(self, prediction, category):
            if category == 'neg':
                self.prediction_text.append(
                    "Probability of Negative: %s %s \n" %
                    (prediction[0, 0], prediction[0, 1]))
            elif category == 'bc':
                self.prediction_text.append(
                    "Probability of Benign Calcification:  %s %s \n" %
                    (prediction[0, 0], prediction[0, 1]))
            elif category == 'bm':
                self.prediction_text.append(
                    "Probability of Benign Mass: %s %s \n" %
                    (prediction[0, 0], prediction[0, 1]))
            elif category == 'mc':
                self.prediction_text.append(
                    "Probability of Malignant Calcification: %s %s \n" %
                    (prediction[0, 0], prediction[0, 1]))
            elif category == 'mm':
                self.prediction_text.append(
                    "Probability of Malignant Mass: %s %s \n" %
                    (prediction[0, 0], prediction[0, 1]))
            else:
                self.prediction_text.append(
                    "Probability of ????: %s %s \n" %
                    (prediction[0, 0], prediction[0, 1]))

        def openFileDialog(self):
            fileName, _ = QFileDialog.getOpenFileName(
                self, "QFileDialog.getOpenFileName()", "",
                "All Files (*);;Python Files (*.py)")
            if fileName:
                return fileName

        def is_png(data):
            return data[:8] == '\x89PNG\x0d\x0a\x1a\x0a'
Exemplo n.º 15
0
class HttpMessagesTreeView(QWidget):
    selected = pyqtSignal(object)

    class ModelItem:
        def __init__(self, model, branch):
            self.branch = branch
            self.model = model

    def __init__(self, plugin_registry, parent=None):
        super().__init__(parent)
        self.plugin_registry = plugin_registry
        self.tree_view = QTreeView()
        self.label = QLabel()
        self.clear()

        self.column_definitions = self.plugin_registry.get_columns()

        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.tree_view)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

    def getAllMessagePairs(self):
        return (item.model for item in self.__index.values())

    def clear(self):
        self.model = QStandardItemModel()
        self.filteredModel = FilteredModel(self.plugin_registry)
        self.filteredModel.setSourceModel(self.model)

        self.rootNode = self.model.invisibleRootItem()
        self.__index = OrderedDict()
        self.tree_view.setModel(self.filteredModel)
        self.label.setText(self.__getLabelText())

        self.tree_view.selectionModel().selectionChanged.connect(
            self.onSelectionChanged)

    def refresh(self):
        self.filteredModel.invalidateFilter()
        self.label.setText(self.__getLabelText())

    def applyModel(self):
        self.tree_view.setModel(self.filteredModel)
        for i, column in enumerate(self.column_definitions):
            self.model.setHeaderData(i, Qt.Horizontal, column[1])
        column_count = self.model.columnCount()
        column_width = self.tree_view.width() / column_count
        for col in range(0, column_count):
            self.tree_view.setColumnWidth(col, column_width)
        self.label.setText(self.__getLabelText())

    def onSelectionChanged(self, selection: QItemSelection):
        if selection.isEmpty():
            return
        item = selection.indexes()[0]
        data = item.data(ROLE_HTTP_MESSAGE)
        if data:
            self.selected.emit(data)

    def onRequestResponse(self, request_response):
        new_row = request_response.guid not in self.__index

        if not new_row:
            model_item = self.__index[request_response.guid]
            branch = model_item.branch
            model_item.model = request_response
        else:
            branch = [QStandardItem() for x in self.column_definitions]
            self.__index[
                request_response.guid] = HttpMessagesTreeView.ModelItem(
                    request_response, branch)

        branch[0].setData(request_response, ROLE_HTTP_MESSAGE)

        for i, column in enumerate(self.column_definitions):
            text = self.plugin_registry.get_cell_content(
                request_response, column[0])
            if text:
                branch[i].setText(text)

        if new_row:
            self.rootNode.appendRow(branch)
        self.applyModel()

    def __getLabelText(self):
        return "Displaying <b>{}</b> out of <b>{}</b>.".format(
            self.filteredModel.rowCount(), self.model.rowCount())
Exemplo n.º 16
0
    from node import Node
    # noinspection PyUnresolvedReferences,PyPackageRequirements
    from model import FileSystemTreeModel, ActionDelegate

if __name__ == "__main__":
    app = QApplication(sys.argv)

    model = FileSystemTreeModel(Node('Filename'), path='/')

    tree = QTreeView()
    tree.setModel(model)
    tree.setIconSize(QSize(48, 48))

    tree.setHeaderHidden(False)
    # tree.setColumnWidth(0, 250)
    tree.setColumnWidth(1, 30)

    hv = tree.header()
    hv.setStretchLastSection(False)
    hv.setSectionResizeMode(0, QHeaderView.Stretch)
    hv.setSectionResizeMode(1, QHeaderView.Fixed)

    tree.setWordWrap(True)
    tree.setTextElideMode(Qt.ElideNone)
    act_delegate = ActionDelegate()
    tree.setItemDelegateForColumn(1, act_delegate)
    # tree.setFixedSize(700, 900)
    tree.setMinimumSize(700, 900)

    @pyqtSlot('QPoint')
    def open_menu(pos):
Exemplo n.º 17
0
class TwoLines(QWidget):
    def __init__(self):
        super().__init__()
        self.top = QListWidget()
        if MOVIE_UNSEEN:
            self.current_dict = MOVIE_UNSEEN
            self.current_list = MOVIE_UNSEEN.keys()
        else:
            self.current_dict = MOVIE_SEEN
            self.current_list = MOVIE_SEEN.keys()

        self.tabs = QTabWidget()
        self.bottom = QLabel()
        self.tree = QTreeView()

        self.init_ui()

    def init_ui(self):
        hbox = QHBoxLayout(self)

        self.top.addItems(self.current_list)
        self.top.setCurrentRow(0)
        self.top.setContextMenuPolicy(Qt.CustomContextMenu)

        # TAB movie info
        self.data_to_show()
        # TAB ls dir
        self.ls_current_dir()
        # TABS
        self.set_tabs()

        # must be here because of QBasicTimer red msg
        # QBasicTimer can only be used with threads started with QThread
        def changed_item():
            if self.top.currentItem():
                self.data_to_show()
                self.ls_current_dir()

        self.top.currentItemChanged.connect(changed_item)
        self.top.customContextMenuRequested.connect(self.right_click)
        self.tree.doubleClicked.connect(self.clicked_movie)

        # to choose a browser
        # self.labelOnlineHelp.linkActivated.connect(self.link_handler)
        self.bottom.setOpenExternalLinks(True)

        splitter1 = QSplitter(Qt.Vertical)
        splitter1.addWidget(self.top)
        splitter1.addWidget(self.tabs)

        hbox.addWidget(splitter1)
        self.setLayout(hbox)

    def set_tabs(self):
        """
        movie info on one tab
        ls dir on the other tab
        """
        # movie info
        tab_synopsys = QWidget()

        # layout
        synopsys_vbox = QVBoxLayout()

        # ls dir
        tab_ls_dir = QWidget()

        lsdir_vbox = QVBoxLayout()

        # tab one
        synopsys_vbox.addWidget(self.bottom)
        tab_synopsys.setLayout(synopsys_vbox)
        self.tabs.addTab(tab_synopsys, "Movie Info")
        # tab two
        lsdir_vbox.addWidget(self.tree)
        tab_ls_dir.setLayout(lsdir_vbox)
        self.tabs.addTab(tab_ls_dir, "ls dir")

    def data_to_show(self):
        """
        call HtmlTags to build html with a poster and a synopsis
        and put the result on self.bottom
        """
        title = self.top.currentItem().text()
        url = self.current_dict[title][0]
        context = HtmlTags(url, title)
        self.bottom.setText(context.context)

    def ls_current_dir(self):
        path_to_dir = self.current_dict[self.top.currentItem().text()][-1]
        # ls content of the current dirQt.CustomContextMenu
        lsdir = QFileSystemModel()
        lsdir.setRootPath(path_to_dir)
        self.tree.setModel(lsdir)
        self.tree.setRootIndex(lsdir.index(path_to_dir))
        self.tree.setColumnWidth(0, 450)

    def right_click(self):
        RightClickMenu(self.current_dict, self.top)

    def clicked_movie(self):
        item = self.tree.selectedIndexes()[0]
        file_to_play = item.model().filePath(item)
        if file_to_play.endswith(('.avi', 'mp4', '.mkv')):
            call(['/usr/bin/mpv', file_to_play])

    def on_changed(self, text):
        self.lbl.setText(text)
        self.lbl.adjustSize()
Exemplo n.º 18
0
class mainWindow(QMainWindow):#											||
	def __init__(self):#												||
		QMainWindow.__init__(self)#										||
		pxcfg = here+'/gui.yaml'
		self.config = monk.stone(pxcfg).
		self.setAttribute(Qt.WA_DeleteOnClose)#							||
		self.setWindowTitle("Pyffice 0.0.0.0.0.0")#						||
		self.setStyleSheet(open(qss, "r").read())#						||
		self.setAutoFillBackground(True)#								||
		self.loadMenu()#												||
		self.setLayout()#												||
		self.loadApp()#													||
	def buildMenu():
		pass
	def desktopMenu(self, application, cfg=None):
		#dynamically build menu from config file
		dtmcfg = self.config['menu']
		for item in cfg.keys():
			self.menu = QMenu(dtmcfg[item]['name'], application)
	def loadMenu(self):#												||
		menu = self.desktopMenu(self)# this sends the desktop object (self) to the menu object
		for mu in menu.__dir__():#										||dynamically add
			obj = getattr(menu, mu)#									||menu items to the
			if isinstance(obj, QMenu):#									||layout
				self.menuBar().addMenu(obj)#							||
	def setLayout(self):#												||
		self.main_widget = QWidget(self)
		self.l = QHBoxLayout(self.main_widget)
#		tbar = docAddBar()
#		l.addWidget(tbar.toolbar)
	def loadApp(self):#													||
		''
		app = alpr.App()
		self.formulaBar()
		self.createLayout()
		self.l.addWidget(app)
		self.main_widget.setFocus()
		self.setCentralWidget(self.main_widget)
		windowLayout = QBoxLayout(QBoxLayout.LeftToRight)
		self.treeview.setFixedWidth=200
		windowLayout.addWidget(self.treeview)
		windowLayout.addWidget(self.tabwidget)
		self.setLayout(windowLayout)
		self.show()
		return self
		self.functionBar = QToolBar()
		self.addToolBar(self.functionBar)
		self.functionInput = QLineEdit()
		self.functionBar.addWidget(self.functionInput)
		self.formulaBar = QToolBar()
		self.addToolBar(self.formulaBar)
		self.formulaInput = QLineEdit()
		self.formulaBar.addWidget(self.formulaInput)
		self.statusBar().showMessage('Pyffice is about to Live')
	def fileQuit(self):
		self.close()
	def closeEvent(self, ce):
		self.fileQuit()

	def treeView(self,):
		self.treeview = QTreeView()
		self.treeview.setModel(model)

		self.treeview.setRootIndex(model.index(QDir.homePath()))

		self.treeview.setColumnWidth(0,50)
		self.treeview.setColumnHidden(1, True)
		self.treeview.setColumnHidden(2, True)
		self.treeview.setColumnHidden(3, True)
		self.treeview.setFixedWidth(200)
		self.treeview.setAnimated(False)
		self.treeview.setIndentation(20)
		self.treeview.setSortingEnabled(True)
		return self
	def setupContextMenu(self):
		'I believe this should setup the right click menu'
		self.addAction(self.cell_addAction)
		self.addAction(self.cell_subAction)
		self.addAction(self.cell_mulAction)
		self.addAction(self.cell_divAction)
		self.addAction(self.cell_sumAction)
		self.addAction(self.firstSeparator)
		self.addAction(self.colorAction)
		self.addAction(self.fontAction)
		self.addAction(self.secondSeparator)
		self.addAction(self.clearAction)
		self.setContextMenuPolicy(Qt.ActionsContextMenu)
		return self
	def formulaBar(self):
		return self
	def functionBar(self):
		return self
Exemplo n.º 19
0
class Explorer(QDialog):
    def __init__(
        self, parent, window_title=_("Select resources"), subtitle=_("Select files and/or folders to include")
    ):
        super().__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.setModal(True)
        self.setSizeGripEnabled(True)
        self.setWindowTitle(window_title)
        self.subtitle = subtitle
        self.file_set = set()
        self.config = Configuration()
        self.__init_ui__()
        self.filename_filter = FilenameFilter()
        # self.show()

    def __init_ui__(self):
        # layout
        vert = QVBoxLayout(self)
        vert.setContentsMargins(0, 0, 0, 0)

        resource_dir = self.config.cfg_resource_dir()

        p_top = QVBoxLayout()
        lb_subtitle = QLabel(self.subtitle)
        lb_subtitle.setContentsMargins(10, 10, 10, 0)
        p_top.addWidget(lb_subtitle)

        self.model = QFileSystemModel()
        self.model.setRootPath(resource_dir)

        self.view = QTreeView()
        self.view.setModel(self.model)
        self.view.setRootIndex(self.model.index(self.model.rootPath()))
        self.view.setAlternatingRowColors(True)
        self.view.setSelectionMode(QAbstractItemView.MultiSelection)
        self.view.selectionModel().selectionChanged.connect(self.selection_changed)
        self.view.collapsed.connect(self.item_collapsed)
        self.view.expanded.connect(self.item_expanded)
        p_top.addWidget(self.view)

        p_info = QHBoxLayout()
        lb_resource = QLabel(_("resource dir") + ": " + resource_dir)
        lb_resource.setContentsMargins(10, 0, 10, 0)

        self.lb_selection_count = QLabel(str(self.selected_file_count()) + " " + _("resources selected"))
        self.lb_selection_count.setContentsMargins(10, 0, 10, 0)

        p_info.addWidget(self.lb_selection_count)
        p_info.addStretch(1)
        p_info.addWidget(lb_resource)

        p_top.addLayout(p_info)

        p_bottom = QHBoxLayout()

        self.pb_deselect = QPushButton(_("Deselect all"))
        self.pb_deselect.clicked.connect(self.pb_deselect_clicked)
        self.pb_deselect.setEnabled(self.selected_file_count() > 0)
        p_bottom.addWidget(self.pb_deselect)

        p_bottom.addStretch(1)
        self.pb_ok = QPushButton(_("OK"))
        self.pb_ok.setAutoDefault(True)
        self.pb_ok.clicked.connect(self.accept)
        p_bottom.addWidget(self.pb_ok)

        pb_cancel = QPushButton(_("Cancel"))
        pb_cancel.clicked.connect(self.reject)
        p_bottom.addWidget(pb_cancel)

        vert.addLayout(p_top)
        vert.addLayout(p_bottom)

        self.setLayout(vert)
        self.resize(self.config.explorer_width(), self.config.explorer_height())
        width = self.view.width() - 50
        self.view.setColumnWidth(0, width / 2)
        self.view.setColumnWidth(1, width / 6)
        self.view.setColumnWidth(2, width / 6)
        self.view.setColumnWidth(3, width / 6)

    def __persist__(self):
        # persist properties of the explorer
        self.config.set_explorer_width(self.width())
        self.config.set_explorer_height(self.height())
        self.config.persist()

    def __compute_filenames__(self, item_selection):
        # item_selection: a QItemSelection
        # return corresponding absolute filenames as a set, including filenames in underlying folders
        s = set()
        for index in item_selection.indexes():
            # we have an index for each column in the model
            if index.column() == 0:
                path = index.model().filePath(index)
                if os.path.isdir(path):
                    for root, directories, filenames in os.walk(path):
                        for filename in filenames:
                            if self.filename_filter.accept(filename):
                                s.add(os.path.join(root, filename))
                elif os.path.isfile(path):
                    s.add(path)
                else:
                    self.logger.warn("isUnknownThing", path)
        return s

    def showEvent(self, QShowEvent):
        # self.pb_ok.setFocus()
        pass

    def set_filename_filter(self, filename_filter):
        # set the FilenameFilter
        self.filename_filter = filename_filter

    def selected_file_count(self):
        return len(self.file_set)

    def selected_file_set(self):
        return frozenset(self.file_set)

    def selection_changed(self, selected, deselected):
        # selected, deselected: PyQt5.QtCore.QItemSelection
        selected_filenames = self.__compute_filenames__(selected)
        self.file_set.update(selected_filenames)
        deselected_filenames = self.__compute_filenames__(deselected)
        self.file_set.difference_update(deselected_filenames)

        self.pb_deselect.setEnabled(self.selected_file_count() > 0)
        self.lb_selection_count.setText(str(self.selected_file_count()) + " " + _("resources selected"))

    def item_expanded(self, index):
        # index: a QModelIndex
        # show all child items selected/deselected in accordance with state of parent folder
        pass

    def item_collapsed(self, index):
        pass

    def pb_deselect_clicked(self):
        self.view.selectionModel().clear()

    def hideEvent(self, QHideEvent):
        self.__persist__()
Exemplo n.º 20
0
class Explorer(QDialog):
    def __init__(self,
                 parent,
                 window_title=_("Select resources"),
                 subtitle=_("Select files and/or folders to include")):
        super().__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.setModal(True)
        self.setSizeGripEnabled(True)
        self.setWindowTitle(window_title)
        self.subtitle = subtitle
        self.file_set = set()
        self.config = Configuration()
        self.__init_ui__()
        self.filename_filter = FilenameFilter()
        #self.show()

    def __init_ui__(self):
        # layout
        vert = QVBoxLayout(self)
        vert.setContentsMargins(0, 0, 0, 0)

        resource_dir = self.config.cfg_resource_dir()

        p_top = QVBoxLayout()
        lb_subtitle = QLabel(self.subtitle)
        lb_subtitle.setContentsMargins(10, 10, 10, 0)
        p_top.addWidget(lb_subtitle)

        self.model = QFileSystemModel()
        self.model.setRootPath(resource_dir)

        self.view = QTreeView()
        self.view.setModel(self.model)
        self.view.setRootIndex(self.model.index(self.model.rootPath()))
        self.view.setAlternatingRowColors(True)
        self.view.setSelectionMode(QAbstractItemView.MultiSelection)
        self.view.selectionModel().selectionChanged.connect(
            self.selection_changed)
        self.view.collapsed.connect(self.item_collapsed)
        self.view.expanded.connect(self.item_expanded)
        p_top.addWidget(self.view)

        p_info = QHBoxLayout()
        lb_resource = QLabel(_("resource dir") + ": " + resource_dir)
        lb_resource.setContentsMargins(10, 0, 10, 0)

        self.lb_selection_count = QLabel(
            str(self.selected_file_count()) + " " + _("resources selected"))
        self.lb_selection_count.setContentsMargins(10, 0, 10, 0)

        p_info.addWidget(self.lb_selection_count)
        p_info.addStretch(1)
        p_info.addWidget(lb_resource)

        p_top.addLayout(p_info)

        p_bottom = QHBoxLayout()

        self.pb_deselect = QPushButton(_("Deselect all"))
        self.pb_deselect.clicked.connect(self.pb_deselect_clicked)
        self.pb_deselect.setEnabled(self.selected_file_count() > 0)
        p_bottom.addWidget(self.pb_deselect)

        p_bottom.addStretch(1)
        self.pb_ok = QPushButton(_("OK"))
        self.pb_ok.setAutoDefault(True)
        self.pb_ok.clicked.connect(self.accept)
        p_bottom.addWidget(self.pb_ok)

        pb_cancel = QPushButton(_("Cancel"))
        pb_cancel.clicked.connect(self.reject)
        p_bottom.addWidget(pb_cancel)

        vert.addLayout(p_top)
        vert.addLayout(p_bottom)

        self.setLayout(vert)
        self.resize(self.config.explorer_width(),
                    self.config.explorer_height())
        width = self.view.width() - 50
        self.view.setColumnWidth(0, width / 2)
        self.view.setColumnWidth(1, width / 6)
        self.view.setColumnWidth(2, width / 6)
        self.view.setColumnWidth(3, width / 6)

    def __persist__(self):
        # persist properties of the explorer
        self.config.set_explorer_width(self.width())
        self.config.set_explorer_height(self.height())
        self.config.persist()

    def __compute_filenames__(self, item_selection):
        # item_selection: a QItemSelection
        # return corresponding absolute filenames as a set, including filenames in underlying folders
        s = set()
        for index in item_selection.indexes():
            # we have an index for each column in the model
            if index.column() == 0:
                path = index.model().filePath(index)
                if os.path.isdir(path):
                    for root, directories, filenames in os.walk(path):
                        for filename in filenames:
                            if self.filename_filter.accept(filename):
                                s.add(os.path.join(root, filename))
                elif os.path.isfile(path):
                    s.add(path)
                else:
                    self.logger.warn("isUnknownThing", path)
        return s

    def showEvent(self, QShowEvent):
        #self.pb_ok.setFocus()
        pass

    def set_filename_filter(self, filename_filter):
        # set the FilenameFilter
        self.filename_filter = filename_filter

    def selected_file_count(self):
        return len(self.file_set)

    def selected_file_set(self):
        return frozenset(self.file_set)

    def selection_changed(self, selected, deselected):
        # selected, deselected: PyQt5.QtCore.QItemSelection
        selected_filenames = self.__compute_filenames__(selected)
        self.file_set.update(selected_filenames)
        deselected_filenames = self.__compute_filenames__(deselected)
        self.file_set.difference_update(deselected_filenames)

        self.pb_deselect.setEnabled(self.selected_file_count() > 0)
        self.lb_selection_count.setText(
            str(self.selected_file_count()) + " " + _("resources selected"))

    def item_expanded(self, index):
        # index: a QModelIndex
        # show all child items selected/deselected in accordance with state of parent folder
        pass

    def item_collapsed(self, index):
        pass

    def pb_deselect_clicked(self):
        self.view.selectionModel().clear()

    def hideEvent(self, QHideEvent):
        self.__persist__()
Exemplo n.º 21
0
class MyMainWindow(QMainWindow):

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.config_window()
        self.create_widgets()
        self.config_widgets()
        self.create_menubar()
        self.bind_widgets()
        self.show_widgets()

    def config_window(self):
        self.setWindowTitle('DirectoPy')
        self.setMinimumHeight(600)
        self.setMinimumWidth(1000)

    def create_widgets(self):
        self.central_widget = QWidget()
        self.main_layout = QGridLayout()
        self.moveup_button = QPushButton('Collapse all', self)
        self.goto_lineedit = QLineEdit('', self)
        self.goto_button = QPushButton('Go', self)
        self.folder_view = QTreeView(self)
        self.file_view = QTreeView(self)
        self.folder_model = QFileSystemModel(self)
        self.file_model = QFileSystemModel(self)

    def config_widgets(self):
        self.main_layout.addWidget(self.moveup_button, 0, 0)
        self.main_layout.addWidget(self.goto_lineedit, 0, 1, 1, 2)
        self.main_layout.addWidget(self.goto_button, 0, 3)
        self.main_layout.addWidget(self.folder_view, 1, 0, 1, 2)
        self.main_layout.addWidget(self.file_view, 1, 2, 1, 2)

        self.central_widget.setLayout(self.main_layout)

        # Кнопка "вверх"
        self.moveup_button.setMaximumWidth(100)

        # Кнопка "перейти"
        self.goto_button.setMaximumWidth(70)
        self.setCentralWidget(self.central_widget)
        # панели
        self.folder_model.setRootPath(None)
        self.folder_model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        self.folder_view.setModel(self.folder_model)
        self.folder_view.setRootIndex(self.folder_model.index(None))
        self.folder_view.clicked[QModelIndex].connect(self.clicked_onfolder)
        self.folder_view.hideColumn(1)
        self.folder_view.hideColumn(2)
        self.folder_view.hideColumn(3)

        self.file_model.setFilter(QDir.Files)
        self.file_view.setModel(self.file_model)
        self.file_model.setReadOnly(False)
        self.file_view.setColumnWidth(0, 200)
        self.file_view.setSelectionMode(QAbstractItemView.ExtendedSelection)

    # открытие папки при нажати на неё в окне папок
    def clicked_onfolder(self, index):
        selection_model = self.folder_view.selectionModel()
        index = selection_model.currentIndex()
        dir_path = self.folder_model.filePath(index)
        self.file_model.setRootPath(dir_path)
        self.file_view.setRootIndex(self.file_model.index(dir_path))

    # ф-я открытия нового файла
    def open_file(self):
        index = self.file_view.selectedIndexes()
        if not index:
            return
        else:
            index = index[0]
        file_path = self.file_model.filePath(index).replace('/', '\\')
        print(file_path)
        self.file_view.update()

    # ф-я создания нового файла
    def new_file(self):
        global file_name
        index = self.folder_view.selectedIndexes()
        if len(index) > 0:
            path = self.folder_model.filePath(index[0])
            for i in range(1, 9999999999999999):
                if not os.path.isfile(os.path.join(path, "newfile{}.txt".format(i))):
                    file_name = os.path.join(path, "newfile{}.txt".format(i))
                    break
            file_name = os.path.abspath(file_name)
            open(file_name, 'w').close()
        else:
            print("Please, select folder")

    # ф-я удаления файла
    def delete_file(self):
        indexes = self.file_view.selectedIndexes()
        for i in indexes:
            self.file_model.remove(i)

    # ф-я переименования файла
    def rename_file(self):
        index = self.file_view.selectedIndexes()
        if not index:
            return
        else:
            index = index[0]
        self.file_view.edit(index)

    # ф-я копирования файла
    def copy_file(self):
        print("COPY")
        ask = QFileDialog.getExistingDirectory(self, "Open Directory", "C:\\",
                                               QFileDialog.ShowDirsOnly |
                                               QFileDialog.DontResolveSymlinks)
        new_path = ask.replace('\\', '/')
        indexes = self.file_view.selectedIndexes()[::4]
        for i in indexes:
            new_filename = new_path + '/' + self.file_model.fileName(i)
            copy2(self.file_model.filePath(i), new_filename)

    # ф-я возвращения к корню пути
    def colapse(self):
        self.folder_view.collapseAll()

    # ф-я перемещения в заданную директорию
    def go_to(self):
        dir_path = self.goto_lineedit.text().replace('\\', '/')
        print(dir_path)
        self.file_model.setRootPath(dir_path)
        self.file_view.setRootIndex(self.file_model.index(dir_path))

        #self.file_model.setRootPath()

    # ф-я перемещения файла
    def move_file(self):
        print("MOVE")
        ask = QFileDialog.getExistingDirectory(self, "Open Directory", "C:\\",
                                               QFileDialog.ShowDirsOnly |
                                               QFileDialog.DontResolveSymlinks)
        if ask == '':
            return
        new_path = ask.replace('\\', '/')
        indexes = self.file_view.selectedIndexes()[::4]
        for i in indexes:
            new_filename = new_path + '/' + self.file_model.fileName(i)
            move(self.file_model.filePath(i), new_filename)

    # ф-я создания новой папки
    def new_folder(self):
        global file_name
        index = self.folder_view.selectedIndexes()
        if len(index) > 0:
            path = self.folder_model.filePath(index[0])
            for i in range(1, 9999999999999999):
                if not os.path.isdir(os.path.join(path, "newfolder{}".format(i))):
                    file_name = os.path.join(path, "newfolder{}".format(i))
                    break
            file_name = os.path.abspath(file_name)
            os.mkdir(file_name)
        else:
            print("Please, select folder")

    # ф-я удаления папки
    def delete_folder(self):
        indexes = self.folder_view.selectedIndexes()
        for i in indexes:
            self.folder_model.remove(i)

    # ф-я переименования папки
    def rename_folder(self):
        index = self.folder_view.selectedIndexes()
        if not index:
            return
        else:
            index = index[0]
        self.folder_view.edit(index)

    # ф-я закрытия окна файлового менеджера
    def exit_application(self):
       print("EXIT")
       self.close()

    # задавание функции каждой кнопке
    def bind_widgets(self):
        self.open_file_action.triggered.connect(self.open_file)
        self.new_file_action.triggered.connect(self.new_file)
        self.delete_file_action.triggered.connect(self.delete_file)
        self.rename_file_action.triggered.connect(self.rename_file)
        self.copy_file_action.triggered.connect(self.copy_file)
        self.move_file_action.triggered.connect(self.move_file)
        self.exit_action.triggered.connect(self.exit_application)
        self.new_folder_action.triggered.connect(self.new_folder)
        self.delete_folder_action.triggered.connect(self.delete_folder)
        self.rename_folder_action.triggered.connect(self.rename_folder)


        self.goto_button.clicked.connect(partial(self.go_to))
        self.moveup_button.clicked.connect(partial(self.colapse))

    # создание меню
    def create_menubar(self):

        self.exit_action = QAction('Exit', self)
        self.exit_action.setShortcut('Ctrl+Q')

        self.new_file_action = QAction('New file', self)
        self.new_file_action.setShortcut('F4')

        self.open_file_action = QAction('Open file', self)
        self.open_file_action.setShortcut('F3')

        self.rename_file_action = QAction('Rename file', self)
        self.rename_file_action.setShortcut('F2')

        self.delete_file_action = QAction('Remove file', self)
        self.delete_file_action.setShortcut(QKeySequence.Delete)

        self.copy_file_action = QAction('Copy folder...', self)
        self.copy_file_action.setShortcut(QKeySequence.Copy)

        self.move_file_action = QAction('Move folder...', self)
        self.move_file_action.setShortcut(QKeySequence.Cut)

        self.new_folder_action = QAction('New folder', self)
        self.new_folder_action.setShortcut('Ctrl+Shift+N')

        self.delete_folder_action = QAction('Delete folder', self)
        self.delete_folder_action.setShortcut('Ctrl+Shift+Del')

        self.rename_folder_action = QAction('Rename folder', self)
        self.rename_folder_action.setShortcut('Ctrl+Shift+R')

        self.menubar = self.menuBar()
        self.file_menu = self.menubar.addMenu('File')
        self.file_menu.addAction(self.new_file_action)
        self.file_menu.addAction(self.open_file_action)
        self.file_menu.addAction(self.rename_file_action)
        self.file_menu.addAction(self.delete_file_action)
        self.file_menu.addAction(self.copy_file_action)
        self.file_menu.addAction(self.move_file_action)
        self.file_menu.addSeparator()
        self.file_menu.addAction(self.exit_action)

        self.folder_menu = self.menubar.addMenu('Folder')
        self.folder_menu.addAction(self.new_folder_action)
        self.folder_menu.addAction(self.delete_folder_action)
        self.folder_menu.addAction(self.rename_folder_action)

    def show_widgets(self):
        self.setLayout(self.main_layout)
class AttributeController(QMainWindow):
    _visibility_dict = {
        'Beginner': EVisibility.Beginner,
        'Expert': EVisibility.Expert,
        'Guru': EVisibility.Guru,
        'All': EVisibility.Invisible,
    }

    def __init__(self, node_map, parent=None):
        #
        super().__init__(parent=parent)

        #
        self.setWindowTitle('Attribute Controller')

        #
        self._view = QTreeView()
        self._view.setFont(get_system_font())

        #
        self._node_map = node_map
        self._model = FeatureTreeModel(node_map=self._node_map, )

        #
        self._proxy = FilterProxyModel()
        self._proxy.setSourceModel(self._model)
        self._proxy.setDynamicSortFilter(False)

        #
        self._delegate = FeatureEditDelegate(proxy=self._proxy)
        self._view.setModel(self._proxy)
        self._view.setItemDelegate(self._delegate)
        self._view.setUniformRowHeights(True)

        #
        unit = 260
        for i in range(2):
            self._view.setColumnWidth(i, unit)

        w, h = 700, 600
        self._view.setGeometry(100, 100, w, h)

        self.setCentralWidget(self._view)
        self.setGeometry(100, 100, unit * 2, 640)

        self._combo_box_visibility = None
        self._line_edit_search_box = None

        #
        self._setup_toolbars()

    def _setup_toolbars(self):
        #
        group_filter = self.addToolBar('Node Visibility')
        group_manipulation = self.addToolBar('Node Tree Manipulation')

        #
        label_visibility = QLabel()
        label_visibility.setText('Visibility')
        label_visibility.setFont(get_system_font())

        #
        self._combo_box_visibility = QComboBox()
        self._combo_box_visibility.setSizeAdjustPolicy(
            QComboBox.AdjustToContents)

        #
        items = ('Beginner', 'Expert', 'Guru', 'All')
        for item in items:
            self._combo_box_visibility.addItem(item)

        shortcut_key = 'Ctrl+v'
        shortcut = QShortcut(QKeySequence(shortcut_key), self)

        def show_popup():
            self._combo_box_visibility.showPopup()

        shortcut.activated.connect(show_popup)

        self._combo_box_visibility.setToolTip(
            compose_tooltip('Filter the nodes to show', shortcut_key))
        self._combo_box_visibility.setFont(get_system_font())
        self._combo_box_visibility.currentIndexChanged.connect(
            self._invalidate_feature_tree_by_visibility)

        #
        button_expand_all = ActionExpandAll(icon='expand.png',
                                            title='Expand All',
                                            parent=self,
                                            action=self.action_on_expand_all)
        shortcut_key = 'Ctrl+e'
        button_expand_all.setToolTip(
            compose_tooltip('Expand the node tree', shortcut_key))
        button_expand_all.setShortcut(shortcut_key)
        button_expand_all.toggle()

        #
        button_collapse_all = ActionCollapseAll(
            icon='collapse.png',
            title='Collapse All',
            parent=self,
            action=self.action_on_collapse_all)
        shortcut_key = 'Ctrl+c'
        button_collapse_all.setToolTip(
            compose_tooltip('Collapse the node tree', shortcut_key))
        button_collapse_all.setShortcut(shortcut_key)
        button_collapse_all.toggle()

        #
        label_search = QLabel()
        label_search.setText('RegEx Search')
        label_search.setFont(get_system_font())

        #
        self._line_edit_search_box = QLineEdit()
        self._line_edit_search_box.setFont(get_system_font())
        self._line_edit_search_box.textEdited.connect(
            self._invalidate_feature_tree_by_keyword)

        #
        group_filter.addWidget(label_visibility)
        group_filter.addWidget(self._combo_box_visibility)
        group_filter.addWidget(label_search)
        group_filter.addWidget(self._line_edit_search_box)
        group_filter.setStyleSheet('QToolBar{spacing:6px;}')

        #
        group_manipulation.addAction(button_expand_all)
        group_manipulation.addAction(button_collapse_all)

        #
        group_manipulation.actionTriggered[QAction].connect(
            self.on_button_clicked_action)

        #
        self._combo_box_visibility.setCurrentIndex(
            self._visibility_dict['Expert'])

    def _invalidate_feature_tree_by_visibility(self):
        visibility = self._visibility_dict[
            self._combo_box_visibility.currentText()]
        self._proxy.setVisibility(visibility)
        self._view.expandAll()

    @pyqtSlot('QString')
    def _invalidate_feature_tree_by_keyword(self, keyword):
        self._proxy.setKeyword(keyword)
        self._view.expandAll()

    @staticmethod
    def on_button_clicked_action(action):
        action.execute()

    def expand_all(self):
        self._view.expandAll()

    def collapse_all(self):
        self._view.collapseAll()

    def resize_column_width(self):
        for i in range(self._model.columnCount()):
            self._view.resizeColumnToContents(i)

    def action_on_expand_all(self):
        self.expand_all()

    def action_on_collapse_all(self):
        self.collapse_all()
Exemplo n.º 23
0
    def __init__(self):
        super().__init__()
        hbox = QHBoxLayout()

        # -----------------------------
        # Create frames
        # -----------------------------

        # 1. Plot frame:
        plotFrame = QFrame()
        plotFrame.setFrameShape(QFrame.Panel | QFrame.Raised)
        plotFrame.setStyleSheet(stylesheet_qframe1())
        figure = plt.figure()
        canvas = FigureCanvas(figure)
        ln = 100000
        data = [random.random() for i in range(ln)]
        data = np.cumsum(data - np.mean(data))
        ax = figure.add_subplot(111)
        plt.subplots_adjust(left=0.00,
                            bottom=0.002,
                            right=1,
                            top=1,
                            wspace=0,
                            hspace=0)
        ax.plot(data)
        ax.grid()
        ax.set_facecolor('#C4C4C4')
        ax.grid(color='#B80C09', linestyle=':')
        plt.xlim([0, len(data)])
        canvas.draw()
        pLayout = QVBoxLayout()
        pLayout.addWidget(canvas)
        plotFrame.setLayout(pLayout)
        plotFrame.setContentsMargins(0, 0, 0, 0)

        # 2. Horizontal sliders frame:
        sHbox = QVBoxLayout()
        slider1h = QSlider(Qt.Horizontal, self)
        slider1h.setStyleSheet(stylesheet_h())
        slider2h = QSlider(Qt.Horizontal, self)
        slider2h.setStyleSheet(stylesheet_h())
        sHbox.addWidget(slider1h)
        sHbox.addWidget(slider2h)
        sHbox.setSpacing(0)
        sHbox.setContentsMargins(1, 0, 1, 0)
        sFrameH = QFrame()
        sFrameH.setFrameShape(QFrame.Panel | QFrame.Raised)
        sFrameH.setLayout(sHbox)

        # 3. Vertical sliders frame:
        sVbox = QHBoxLayout()
        slider1v = QSlider(Qt.Vertical, self)
        slider1v.setStyleSheet(stylesheet_v())
        slider2v = QSlider(Qt.Vertical, self)
        slider2v.setStyleSheet(stylesheet_v())
        sVbox.addWidget(slider1v)
        sVbox.addWidget(slider2v)
        sVbox.setSpacing(0)
        sVbox.setContentsMargins(1, 0, 1, 0)
        sFrameV = QFrame()
        sFrameV.setFrameShape(QFrame.Panel | QFrame.Raised)
        sFrameV.setLayout(sVbox)

        # 4. SlidersControl frame:
        cornerFrame = QFrame()
        btnMax1 = QPushButton('max', cornerFrame)
        btnMax2 = QPushButton('max', cornerFrame)
        btnMax1.setGeometry(1, 0, 30, 20)
        btnMax2.setGeometry(1, 17, 30, 20)
        editMax1 = QLineEdit('0', cornerFrame)
        editMax2 = QLineEdit('0', cornerFrame)
        editMax1.setGeometry(31, 0, 60, 20)
        editMax2.setGeometry(31, 17, 60, 20)
        cornerFrame.setFrameShape(QFrame.Panel | QFrame.Raised)

        # 5. Control Panel frame:
        controlFrame = QFrame()
        controlFrame.setFrameShape(QFrame.Panel | QFrame.Raised)
        controlFrame.setLineWidth(2)
        control_tab = QTabWidget()
        cTab1 = QWidget()

        # Tab Browser
        # ------------------------
        cLayout1 = QVBoxLayout()
        cFrame1 = QFrame()
        self.lst_file = QListWidget()
        self.lst_dir = QListWidget()
        self.tab_files = QTabWidget()
        self.tab_files.addTab(self.lst_file, 'Files')
        self.tab_files.addTab(self.lst_dir, 'Directories')
        cLayout_btn = QHBoxLayout()
        self.btn_load = QPushButton('Load')
        self.btn_load.setObjectName('Load')
        self.btn_load.clicked.connect(self.openFileNameDialog)
        self.btn_info = QPushButton('Info')
        self.btn_info.setObjectName('Info')
        self.btn_info.clicked.connect(self.openFileNameDialog)
        self.btn_prev = QPushButton('Preview')
        self.btn_prev.setObjectName('Preview')
        self.btn_prev.clicked.connect(self.openFileNameDialog)

        # get open histories
        self.filepath = ''
        if os.path.exists('files_history.txt'):
            with open('files_history.txt', 'r') as f:
                files_history = f.read().splitlines()
            path_history = getPathList(files_history)
            self.filepath = path_history[0]
        else:
            files_history = list()
            path_history = list()
        for item in files_history:
            self.lst_file.addItem(item)
        for item in path_history:
            self.lst_dir.addItem(item)

        cLayout_btn.addWidget(self.btn_load)
        cLayout_btn.addWidget(self.btn_info)
        cLayout_btn.addWidget(self.btn_prev)
        lbl_hist = QLabel('Load data files history')
        cLayout1.addWidget(lbl_hist)
        cLayout1.addWidget(self.tab_files)
        cLayout1.addLayout(cLayout_btn)
        cFrame1.setLayout(cLayout1)

        lbl_obj = QLabel('Loaded objects')
        b_tree = QTreeView()
        b_tree.setAlternatingRowColors(True)
        b_tree_model = QStandardItemModel(0, 5)
        b_tree_node = b_tree_model.invisibleRootItem()
        branch1 = QStandardItem("a")
        branch1.appendRow([QStandardItem("Child A"), None])
        childNode = QStandardItem("Child B")
        branch1.appendRow([childNode, None])
        branch2 = QStandardItem("b")
        branch2.appendRow([QStandardItem("Child C"), None])
        branch2.appendRow([QStandardItem("Child D"), None])
        branch3 = QStandardItem('c')
        branch4 = QStandardItem('d')

        b_tree_node.appendRow([branch1, None])
        b_tree_node.appendRow([branch2, None])
        b_tree_node.appendRow([branch3, None])
        b_tree_node.appendRow([branch4, None])

        b_tree.setModel(b_tree_model)
        b_tree_model.setHeaderData(0, Qt.Horizontal, 'Name')
        b_tree_model.setHeaderData(1, Qt.Horizontal, 'Type')
        b_tree_model.setHeaderData(2, Qt.Horizontal, 'Data')
        b_tree_model.setHeaderData(3, Qt.Horizontal, 'Size')
        b_tree_model.setHeaderData(4, Qt.Horizontal, 'Modified')
        b_tree.setColumnWidth(0, 70)

        cLayout2 = QVBoxLayout()
        cLayout2.addWidget(lbl_obj)
        cLayout2.addWidget(b_tree)
        cFrame2 = QFrame()
        cFrame2.setLayout(cLayout2)

        cSplitBrowser = QSplitter(Qt.Vertical)

        cSplitBrowser.addWidget(cFrame1)
        cSplitBrowser.addWidget(cFrame2)
        cSplitBrowser.setSizes([200, 50])

        cLayout = QVBoxLayout()
        cLayout.addWidget(cSplitBrowser)
        cLayout.setContentsMargins(0, 0, 0, 0)

        # cLayout.addWidget(cFrame2)
        cFrame = QFrame()
        cFrame.setLayout(cLayout)
        control_tab.addTab(cFrame, 'Browser')

        # Tab Work
        # -------------------------------
        wFrame1 = QFrame()
        wLayout = QGridLayout()
        wLbl_proc = QLabel('Process type')
        wComboBox1 = QComboBox()
        w_list = [
            "Signal view", "Differentiation", "Integration", "Correlation",
            "Allan variance", "Fitting", "Termo compensations", "Calibration",
            "Navigation", "Fourier transform"
        ]
        wComboBox1.setStyleSheet(stylesheet_combo2())
        wComboBox1.addItems(w_list)

        wFrame2 = QFrame()
        wFrame2.setFrameShape(QFrame.Box)
        wLayout.addWidget(wLbl_proc, 0, 0, 1, 1)
        wLayout.addWidget(wComboBox1, 1, 0, 1, 1)
        wLayout.addWidget(wFrame2, 2, 0, 35, 1)
        # Frame 2
        wLayout2 = QHBoxLayout()
        wLayout2.addWidget(QPushButton('one'))
        wLayout2.addWidget(QPushButton('two'))
        wLayout2.addWidget(QPushButton('three'))
        wLayout2.setAlignment(Qt.AlignTop)
        wLayout2.setSpacing(0)
        wFrame2.setLayout(wLayout2)

        wLayout.setContentsMargins(1, 1, 1, 1)
        wFrame1.setLayout(wLayout)
        control_tab.addTab(wFrame1, 'Work')

        # Tab Model
        # -------------------------------
        cTab3 = QWidget()
        control_tab.addTab(cTab3, 'Model')

        control_layout = QVBoxLayout()
        control_layout.addWidget(control_tab)
        control_layout.setContentsMargins(0, 0, 0, 0)
        controlFrame.setLayout(control_layout)

        # 6. Log panel:
        LogEdit = QTextEdit('>>')

        # -----------------------------
        # Split frames
        # -----------------------------

        # 1.  Plot + Vertical sliders:
        split1 = QSplitter(Qt.Horizontal)
        split1.addWidget(plotFrame)
        split1.addWidget(sFrameV)
        split1.setSizes([680, 20])

        # 2.  Horizontal sliders + SlidersControl:
        split2 = QSplitter(Qt.Horizontal)
        split2.addWidget(sFrameH)
        split2.addWidget(cornerFrame)
        split2.setSizes([700, 40])

        # 3.  1 + 2 :
        ver_split = QSplitter(Qt.Vertical)
        ver_split.addWidget(split1)
        ver_split.addWidget(split2)
        ver_split.setSizes([800, 50])

        # 4.  3 + Control Panel:
        hor_split = QSplitter(Qt.Horizontal)
        hor_split.addWidget(ver_split)
        hor_split.addWidget(controlFrame)
        hor_split.setSizes([700, 200])

        # 5.  4 + Log frame:
        bottom_split = QSplitter(Qt.Vertical)
        bottom_split.addWidget(hor_split)
        bottom_split.addWidget(LogEdit)
        bottom_split.setSizes([700, 0])

        hbox.addWidget(bottom_split)

        self.setLayout(hbox)
        QApplication.setStyle(QStyleFactory.create('cleanlooks'))
Exemplo n.º 24
0
class AutoREView(idaapi.PluginForm):
    ADDR_ROLE = QtCore.Qt.UserRole + 1

    def __init__(self, data):
        super(AutoREView, self).__init__()
        self._data = data

    def Show(self):
        return idaapi.PluginForm.Show(self, 'AutoRE', options=idaapi.PluginForm.FORM_PERSIST)

    def OnCreate(self, form):
        # if HAS_PYSIDE:
        #     self.parent = self.FormToPySideWidget(form)
        # else:
        self.parent = self.FormToPyQtWidget(form)

        self.tv = QTreeView()
        self.tv.setExpandsOnDoubleClick(False)

        root_layout = QVBoxLayout(self.parent)
        # self.le_filter = QLineEdit(self.parent)

        # root_layout.addWidget(self.le_filter)
        root_layout.addWidget(self.tv)

        self.parent.setLayout(root_layout)

        self._model = QtGui.QStandardItemModel()
        self._init_model()
        self.tv.setModel(self._model)

        self.tv.setColumnWidth(0, 200)
        self.tv.setColumnWidth(1, 300)
        self.tv.header().setStretchLastSection(True)

        self.tv.expandAll()

        self.tv.doubleClicked.connect(self.on_navigate_to_method_requested)
        # self.le_filter.textChanged.connect(self.on_filter_text_changed)

    def OnClose(self, form):
        # print 'TODO: OnClose(): clear the pointer to form in the plugin'
        pass

    def _tv_init_header(self, model):
        item_header = QtGui.QStandardItem("EA")
        item_header.setToolTip("Address")
        model.setHorizontalHeaderItem(0, item_header)

        item_header = QtGui.QStandardItem("Function name")
        model.setHorizontalHeaderItem(1, item_header)

        item_header = QtGui.QStandardItem("API called")
        model.setHorizontalHeaderItem(2, item_header)

    def _tv_make_tag_item(self, name):
        rv = QtGui.QStandardItem(name)

        rv.setEditable(False)
        return [rv, QtGui.QStandardItem(), QtGui.QStandardItem()]

    def _tv_make_ref_item(self, tag, ref):
        ea_item = QtGui.QStandardItem(('%0' + get_addr_width() + 'X') % ref['ea'])
        ea_item.setEditable(False)
        ea_item.setData(ref['ea'], self.ADDR_ROLE)

        name_item = QtGui.QStandardItem(ref['name'])
        name_item.setEditable(False)
        name_item.setData(ref['ea'], self.ADDR_ROLE)

        apis = ', '.join(ref['tags'][tag])
        api_name = QtGui.QStandardItem(apis)
        api_name.setEditable(False)
        api_name.setData(ref['ea'], self.ADDR_ROLE)
        api_name.setToolTip(apis)

        return [ea_item, name_item, api_name]

    def _init_model(self):
        self._model.clear()

        root_node = self._model.invisibleRootItem()
        self._tv_init_header(self._model)

        for tag, refs in self._data.items():
            item_tag_list = self._tv_make_tag_item(tag)
            item_tag = item_tag_list[0]

            root_node.appendRow(item_tag_list)

            for ref in refs:
                ref_item_list = self._tv_make_ref_item(tag, ref)

                item_tag.appendRow(ref_item_list)

    def on_navigate_to_method_requested(self, index):
        addr = index.data(role=self.ADDR_ROLE)
        if addr is not None:
            idaapi.jumpto(addr)
Exemplo n.º 25
0
class StatWidget(QWidget):
    def __init__(self, parent=None, domain=None, headers=None):
        super().__init__(parent=parent)

        self._root = None
        self._domain = domain

        self._button = QPushButton('Открыть...')
        self._edit = QLineEdit()
        self._tree = QTreeView()

        self._model = StatTreeModel(parent=self, headers=headers)

        self._layoutControl = QHBoxLayout()
        self._layoutControl.addWidget(self._button)
        self._layoutControl.addWidget(self._edit)

        self._layoutMain = QVBoxLayout()
        self._layoutMain.addLayout(self._layoutControl)
        self._layoutMain.addWidget(self._tree)

        self.setLayout(self._layoutMain)

        self._edit.setPlaceholderText('Папка...')
        self._edit.setReadOnly(True)

        self._button.clicked.connect(self._on_button_clicked)

        self._tree.setModel(self._model)
        self._tree.setItemDelegateForColumn(3, ProgressBarDelegate())
        self._tree.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self._tree.setSelectionBehavior(QAbstractItemView.SelectRows)

    def init(self):
        self._domain.workDir = os.path.normpath(os.getcwd()) + '\\xlsx'
        self._edit.setText(self._domain.workDir)
        self._model.init(self._domain._root)

    @pyqtSlot()
    def _on_button_clicked(self):
        dialog = QFileDialog(self, 'Выбрать папку...', self._domain.workDir)
        dialog.setFileMode(QFileDialog.DirectoryOnly)
        if dialog.exec() != QFileDialog.Accepted:
            return

        self._domain.workDir = dialog.selectedFiles()[0]
        self._model.init(self._domain._root)

    @property
    def hasSelection(self):
        return self._tree.selectionModel().hasSelection()

    @property
    def rows(self):
        top_level_rows = [
            index for index in self._tree.selectionModel().selectedIndexes()
            if index.data(StatTreeModel.RoleTier) == StatTreeModel.TIER_1
            and index.column() == 0
        ]
        sorted_row_numbers = list(
            sorted([index.row() for index in top_level_rows]))
        return sorted_row_numbers

    def getEmailData(self, rows):
        # TODO handle selected rows
        # TODO handle different domains for email generation, works only for batch stats now
        email_data = dict()
        for batch in self._model._rootNode.child_nodes:
            specs_for_dev = defaultdict(list)
            for spec in batch.child_nodes:
                if not spec['received']:
                    specs_for_dev[spec['developer']].append(spec)
            email_data[batch] = specs_for_dev

        return email_data

    def resizeTable(self, width, columns):
        for index, column in enumerate(columns):
            self._tree.setColumnWidth(index, width * column)
Exemplo n.º 26
0
try:
    rootPath = parser.positionalArguments().pop(0)
except IndexError:
    rootPath = None

model = QFileSystemModel()
model.setRootPath('')
if parser.isSet(dontUseCustomDirectoryIconsOption):
    model.iconProvider().setOptions(
            QFileIconProvider.DontUseCustomDirectoryIcons)
tree = QTreeView()
tree.setModel(model)
if rootPath is not None:
    rootIndex = model.index(QDir.cleanPath(rootPath))
    if rootIndex.isValid():
        tree.setRootIndex(rootIndex)

# Demonstrating look and feel features.
tree.setAnimated(False)
tree.setIndentation(20)
tree.setSortingEnabled(True)

availableSize = QApplication.desktop().availableGeometry(tree).size()
tree.resize(availableSize / 2)
tree.setColumnWidth(0, tree.width() / 3)

tree.setWindowTitle("Dir View")
tree.show()

sys.exit(app.exec_())
Exemplo n.º 27
0
class MainWindowClass(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.interface_lng_val = 'Russian'
        if self.interface_lng_val == 'Russian':
            self.setWindowTitle("Графический интерфейс программы OpenFOAM")
        elif self.interface_lng_val == 'English':
            self.setWindowTitle("OpenFOAM_decompose_GUI")

        # Базовые переменные
        self.full_dir = ''
        self.prj_name = ''
        self.con = ''
        self.lock_bool = False
        self.application = ''
        self.object_edit_txt = ''

        # ---------------------------Панель управления подготовкой задачи МСС----------------------------- #

        self.proj_open = QAction(self)
        self.proj_open.setEnabled(True)
        proj_ico = self.style().standardIcon(QStyle.SP_ArrowUp)
        self.proj_open.setIcon(proj_ico)
        if self.interface_lng_val == 'Russian':
            self.proj_open.setToolTip('Открыть проект')
        elif self.interface_lng_val == 'English':
            self.proj_open.setToolTip('Open the project')

        self.lng_chs = QAction(self)
        self.lng_chs.setEnabled(True)
        lng_chs_ico = self.style().standardIcon(
            QStyle.SP_FileDialogDetailedView)
        self.lng_chs.setIcon(lng_chs_ico)
        if self.interface_lng_val == 'Russian':
            self.lng_chs.setToolTip('Выбрать язык интерфейса программы')
        elif self.interface_lng_val == 'English':
            self.lng_chs.setToolTip('Select the interface language')

        self.file_open = QAction(self)
        self.file_open.setEnabled(False)
        file_open_ico = self.style().standardIcon(QStyle.SP_FileIcon)
        self.file_open.setIcon(file_open_ico)
        if self.interface_lng_val == 'Russian':
            self.file_open.setToolTip(
                'Открыть форму создания служебного файла для директории 0')
        elif self.interface_lng_val == 'English':
            self.file_open.setToolTip(
                'Open the form for creating the service file for the directory 0'
            )

        self.toolBar_1 = QToolBar("MyToolBar")
        self.toolBar_1.addAction(self.proj_open)
        self.toolBar_1.addAction(self.lng_chs)
        self.toolBar_1.addAction(self.file_open)

        self.proj_open.triggered.connect(
            lambda: first_toolbar_functions_class.on_proj_open(self))
        self.lng_chs.triggered.connect(
            lambda: first_toolbar_functions_class.on_lng_chs(self))
        self.file_open.triggered.connect(
            lambda: first_toolbar_functions_class.on_0_files_window_chs(self))

        self.addToolBar(self.toolBar_1)

        ###----------------------Панель управления подготовкой РС--------------------------###

        self.msh_open = QAction(self)
        self.msh_open.setEnabled(False)
        msh_ico = self.style().standardIcon(QStyle.SP_FileDialogNewFolder)
        self.msh_open.setIcon(msh_ico)
        if self.interface_lng_val == 'Russian':
            self.msh_open.setToolTip('Открыть форму выбора расчетной сетки')
        elif self.interface_lng_val == 'English':
            self.msh_open.setToolTip('Open the mesh selection form')

        self.msh_run = QAction(self)
        self.msh_run.setEnabled(False)
        msh_ico = self.style().standardIcon(QStyle.SP_ArrowRight)
        self.msh_run.setIcon(msh_ico)
        if self.interface_lng_val == 'Russian':
            self.msh_run.setToolTip('Выполнить генерацию расчетной сетки')
        elif self.interface_lng_val == 'English':
            self.msh_run.setToolTip('Make the mesh generation')

        self.msh_visual = QAction(self)
        self.msh_visual.setEnabled(False)
        msh_visual_ico = self.style().standardIcon(QStyle.SP_MediaSeekForward)
        self.msh_visual.setIcon(msh_visual_ico)
        if self.interface_lng_val == 'Russian':
            self.msh_visual.setToolTip(
                'Выполнить визуализацию расчетной сетки')
        elif self.interface_lng_val == 'English':
            self.msh_visual.setToolTip('Make the mesh visualization')

        self.toolBar_2 = QToolBar()
        self.toolBar_2.addAction(self.msh_open)
        self.toolBar_2.addAction(self.msh_run)
        self.toolBar_2.addAction(self.msh_visual)

        self.msh_open.triggered.connect(
            lambda: second_toolbar_functions_class.on_msh_open(self))
        self.msh_run.triggered.connect(
            lambda: second_toolbar_functions_class.on_msh_run(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.msh_visual.triggered.connect(
            lambda: second_toolbar_functions_class.on_visual_msh_run(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.addToolBar(self.toolBar_2)
        self.insertToolBarBreak(self.toolBar_2)

        ###----------------------Панель управления решением задачи МСС--------------------------###

        self.solv_run = QAction(self)
        self.solv_run.setEnabled(False)
        solv_run_ico = self.style().standardIcon(QStyle.SP_DialogNoButton)
        self.solv_run.setIcon(solv_run_ico)
        if self.interface_lng_val == 'Russian':
            self.solv_run.setToolTip('Выполнить решение')
        elif self.interface_lng_val == 'English':
            self.solv_run.setToolTip('Run solution')

        self.solv_stop = QAction(self)
        self.solv_stop.setEnabled(False)
        close_ico = self.style().standardIcon(QStyle.SP_DockWidgetCloseButton)
        self.solv_stop.setIcon(close_ico)
        if self.interface_lng_val == 'Russian':
            self.solv_stop.setToolTip('Остановить процесс решения')
        elif self.interface_lng_val == 'English':
            self.solv_stop.setToolTip('Stop the solution process')

        self.solv_run_vis = QAction(self)
        self.solv_run_vis.setEnabled(False)
        solv_run_vis_ico = self.style().standardIcon(QStyle.SP_CommandLink)
        self.solv_run_vis.setIcon(solv_run_vis_ico)
        if self.interface_lng_val == 'Russian':
            self.solv_run_vis.setToolTip(
                'Выполнить визуализацию результатов решения')
        elif self.interface_lng_val == 'English':
            self.solv_run_vis.setToolTip('Visualize the solution results')

        self.toolBar_3 = QToolBar()
        self.toolBar_3.addAction(self.solv_run)
        self.toolBar_3.addAction(self.solv_stop)
        self.toolBar_3.addAction(self.solv_run_vis)

        self.solv_run.triggered.connect(
            lambda: second_toolbar_functions_class.on_solv_run(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.solv_stop.triggered.connect(
            lambda: second_toolbar_functions_class.on_solv_stop(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.solv_run_vis.triggered.connect(
            lambda: second_toolbar_functions_class.on_solv_vis(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.addToolBar(self.toolBar_3)
        self.insertToolBarBreak(self.toolBar_3)

        ###----------------Верхний виджет с полным путем до файла сетки----------------###

        self.tdw = QDockWidget()
        self.tdw.setFixedSize(1400, 65)
        self.tdw.setFeatures(self.tdw.NoDockWidgetFeatures)
        self.tdw_grid = QGridLayout()
        self.tdw_grid.setColumnStretch(2, 1)
        self.tdw_frame = QFrame()
        self.tdw_frame.setStyleSheet("background-color: ghostwhite;"
                                     "border-width: 0.5px;"
                                     "border-style: solid;"
                                     "border-color: silver;")
        self.tdw_frame.setLayout(self.tdw_grid)
        self.tdw.setWidget(self.tdw_frame)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.tdw)

        ###-----------------Левый виджет с файловой системой проекта---------------------###

        self.fsw = QDockWidget()
        self.fsw.setFeatures(self.fsw.NoDockWidgetFeatures)
        self.fsw_label = QLabel()
        self.fsw_label.setAlignment(QtCore.Qt.AlignCenter)
        self.fsw_grid = QGridLayout()
        self.fsw_grid.addWidget(self.fsw_label, 0, 0)
        self.fsw_frame = QFrame()
        self.fsw_frame.setFixedSize(200, 35)
        self.fsw_frame.setStyleSheet("background-color: honeydew;"
                                     "border-width: 1px;"
                                     "border-style: solid;"
                                     "border-color: dimgray;"
                                     "border-radius: 4px;")
        self.fsw_frame.setLayout(self.fsw_grid)

        if self.interface_lng_val == 'Russian':
            fs_lbl = "Файловая Cтруктура Проекта"
        elif self.interface_lng_val == 'English':
            fs_lbl = "File Structure of the Project"

        self.fsw_label.setText("<font color='SeaGreen'>" + fs_lbl + "</font>")
        self.fsw_label.setStyleSheet("border-style: none;" "font-size: 10pt;")
        self.fsw.setTitleBarWidget(self.fsw_frame)
        self.treeview = QTreeView()
        self.treeview.setFixedSize(200, 520)
        self.treeview.model = QtGui.QStandardItemModel()
        self.treeview.setModel(self.treeview.model)
        self.treeview.setColumnWidth(0, 100)
        self.treeview.setColumnHidden(1, True)
        self.treeview.setColumnHidden(2, True)
        self.treeview.setColumnHidden(3, True)
        self.treeview.header().hide()
        self.treeview.setItemsExpandable(False)
        self.treeview.clicked.connect(self.on_treeview_clicked)
        self.fsw.setWidget(self.treeview)

        ###-----------Правый виджет с формой вывода результатов генерации файлов-----------###

        self.cdw = QDockWidget()
        self.cdw.setFeatures(self.cdw.NoDockWidgetFeatures)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.cdw)

        self.cdw_grid = QGridLayout()
        self.cdw_frame = QFrame()
        self.cdw_frame.setFixedSize(495, 35)
        self.cdw_frame.setStyleSheet("border-width: 1px;"
                                     "border-style: solid;"
                                     "border-color: dimgray;"
                                     "border-radius: 4px;"
                                     "background-color: honeydew;")
        self.cdw_frame.setLayout(self.cdw_grid)

        self.outf_lbl = QLabel()
        self.outf_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.outf_lbl.setStyleSheet("border-style: none;" "font-size: 9pt;")

        self.cdw_grid.addWidget(self.outf_lbl, 0, 0)

        self.outf_edit = QTextEdit()
        self.outf_scroll = QScrollArea()
        self.outf_scroll.setWidgetResizable(True)
        self.outf_scroll.setWidget(self.outf_edit)
        self.outf_scroll.setFixedSize(495, 520)

        ###-----------------Центральный виджет с формой параметров---------------------###

        self.ffw = QDockWidget()
        self.ffw.setFeatures(self.ffw.NoDockWidgetFeatures)
        self.ffw_label = QLabel()
        self.ffw_label.setAlignment(QtCore.Qt.AlignCenter)
        self.ffw_grid = QGridLayout()
        self.ffw_grid.addWidget(self.ffw_label, 0, 0)
        self.ffw_frame = QFrame()
        self.ffw_frame.setFixedSize(693, 44)
        self.ffw_frame.setStyleSheet("border-width: 1px;"
                                     "border-style: solid;"
                                     "border-color: dimgray;"
                                     "border-radius: 4px;"
                                     "background-color: honeydew;")
        self.ffw_frame.setLayout(self.ffw_grid)

        ###------------------Нижний виджет со служебными сообщениями------------------###

        if self.interface_lng_val == 'Russian':
            self.serv_mes = QDockWidget("Служебные сообщения")
        elif self.interface_lng_val == 'English':
            self.serv_mes = QDockWidget("Service messages")

        self.serv_mes.setFixedSize(1400, 160)
        self.serv_mes.setFeatures(self.serv_mes.NoDockWidgetFeatures)
        self.listWidget = QListWidget()
        self.serv_mes.setWidget(self.listWidget)

    ###---------------------Функции, связанные с работой главного окна------------------------###

    # ...........................Функция клика по файлу из дерева.........................

    ###........................Функция открытия окна выбора интерфейса программы...................###

    # ...........................Функция клика по файлу из дерева.........................

    def on_treeview_clicked(self, index):
        global fileName
        indexItem = self.treeview.model.index(index.row(), 0, index.parent())
        self.lock_bool = True
        self.file_name = self.treeview.model.itemFromIndex(indexItem).text()
        file_form_class.inp_file_form_func(self, self.file_name, self.con)
        file_name_title = file_form_class.out_file_name_func()
        self.clear_label = QLabel()
        if file_name_title != None:
            if file_name_title != 'md':
                #self.cdw.setWidget(self.clear_label)
                #self.cdw.setTitleBarWidget

                if os.path.exists(self.full_dir + '/system/' +
                                  file_name_title):
                    outf = open(self.full_dir + '/system/' + file_name_title)
                    data = outf.read()
                    self.outf_edit.setText(data)
                    outf.close()
                elif os.path.exists(self.full_dir + '/constant/' +
                                    file_name_title):
                    outf = open(self.full_dir + '/constant/' + file_name_title)
                    data = outf.read()
                    self.outf_edit.setText(data)
                    outf.close()
                elif os.path.exists(self.full_dir + '/0/' + file_name_title):
                    outf = open(self.full_dir + '/0/' + file_name_title)
                    data = outf.read()
                    self.outf_edit.setText(data)
                    outf.close()

                self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.cdw)

                self.cdw.setWidget(self.outf_scroll)

                #data = outf.read()

                if self.interface_lng_val == 'Russian':
                    self.outf_lbl.setText("Файл " + "<font color='peru'>" +
                                          file_name_title + "</font>")
                elif self.interface_lng_val == 'English':
                    self.outf_lbl.setText("<font color='peru'>" +
                                          file_name_title + "</font>" +
                                          " file")
                #self.outf_edit.setText(data)

                self.cdw.setTitleBarWidget(self.cdw_frame)
                #outf.close()

                self.setCentralWidget(self.ffw)
                file_form = file_form_class.out_file_form_func()
                self.ffw.setWidget(file_form)
                self.ffw.setTitleBarWidget(self.ffw_frame)

                if self.interface_lng_val == 'Russian':
                    self.ffw_label.setText("Форма параметров файла: " +
                                           "<font color='peru'>" +
                                           file_name_title + "</font>")
                elif self.interface_lng_val == 'English':
                    self.ffw_label.setText("<font color='peru'>" +
                                           file_name_title + "</font>" +
                                           " file parameters form")
                self.ffw_label.setStyleSheet("border-style: none;"
                                             "font-size: 9pt;")

            elif file_name_title == 'md':
                if self.interface_lng_val == 'Russian':
                    msg_lbl = QLabel(
                        '<span style="color:blue">Для создания расчетной сетки воспользуйтесь панелью инструментов</span>'
                    )
                elif self.interface_lng_val == 'English':
                    msg_lbl = QLabel(
                        '<span style="color:blue">To create a mesh use the toolbar.</span>'
                    )

                self.listWidget.clear()
                self.item = QListWidgetItem()
                self.listWidget.addItem(self.item)
                self.listWidget.setItemWidget(self.item, msg_lbl)

        else:

            self.ffw.setTitleBarWidget(self.clear_label)
            self.ffw.setWidget(self.clear_label)
            self.cdw.setWidget(self.clear_label)
            self.cdw.setTitleBarWidget(self.clear_label)

    # .........................Функция получения языка интерфейса..........................

    def on_lng_get(self, interface_lng):
        global interface_lng_val

        self.interface_lng_val = interface_lng

        if self.interface_lng_val == 'Russian':
            self.setWindowTitle("Графический интерфейс программы OpenFOAM")
            self.proj_open.setToolTip('Открыть проект')
            self.msh_run.setToolTip('Выполнить генерацию расчетной сетки')
            self.msh_visual.setToolTip(
                'Выполнить визуализацию расчетной сетки')
            self.lng_chs.setToolTip('Выбрать язык интерфейса программы')
            self.file_open.setToolTip(
                'Открыть форму создания служебного файла для директории 0')
            self.msh_open.setToolTip('Открыть форму выбора расчетной сетки')
            self.solv_run.setToolTip('Выполнить решение')
            self.solv_stop.setToolTip('Остановить процесс решения')
            self.solv_run_vis.setToolTip(
                'Выполнить визуализацию результатов решения')

        elif self.interface_lng_val == 'English':
            self.setWindowTitle("OpenFOAM_decompose_GUI")
            self.proj_open.setToolTip('Open the project')
            self.msh_run.setToolTip('Run mesh generation')
            self.msh_visual.setToolTip('Run mesh visualization')
            self.lng_chs.setToolTip(
                'Select the interface language for the program')
            self.file_open.setToolTip(
                'Open the form for creating the service file for the directory 0'
            )
            self.msh_open.setToolTip('Open the mesh selection form')
            self.solv_run.setToolTip('Run solution')
            self.solv_stop.setToolTip('Stop the solution process')
            self.solv_run_vis.setToolTip('Visualize the solution results')

    # .........................Функция получения пути до директории..........................

    def on_prj_path_get(self, prj_path, mesh_name_txt):
        global prj_path_val
        global mesh_name_txt_val
        global pp_dir

        prj_path_val = prj_path
        mesh_name_txt_val = mesh_name_txt

        pp_dir, pp_sys = os.path.split(prj_path_val)

    # .............................Функция получения типа сетки..............................

    def on_mesh_type_get(self, pd_2):
        global msh_type
        msh_type = pd_2
Exemplo n.º 28
0
class _LocatorDialog(QDialog):
    """Locator widget and implementation
    """
    def __init__(self, parent, commandClasses):
        QDialog.__init__(self, parent)
        self._terminated = False
        self._commandClasses = commandClasses

        self._createUi()

        self._loadingTimer = QTimer(self)
        self._loadingTimer.setSingleShot(True)
        self._loadingTimer.setInterval(200)
        self._loadingTimer.timeout.connect(self._applyLoadingCompleter)

        self._completerLoaderThread = _CompleterLoaderThread(self)

        self.finished.connect(self._terminate)

        self._command = None
        self._updateCurrentCommand()

    def _createUi(self):
        self.setWindowTitle(core.project().path() or 'Locator')

        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(1)

        biggerFont = self.font()
        biggerFont.setPointSizeF(biggerFont.pointSizeF() * 2)
        self.setFont(biggerFont)

        self._edit = _CompletableLineEdit(self)
        self._edit.updateCurrentCommand.connect(self._updateCurrentCommand)
        self._edit.enterPressed.connect(self._onEnterPressed)
        self._edit.installEventFilter(self)  # catch Up, Down
        self.layout().addWidget(self._edit)
        self.setFocusProxy(self._edit)

        self._table = QTreeView(self)
        self._table.setFont(biggerFont)
        self._model = _CompleterModel()
        self._table.setModel(self._model)
        self._table.setItemDelegate(HTMLDelegate(self._table))
        self._table.setRootIsDecorated(False)
        self._table.setHeaderHidden(True)
        self._table.clicked.connect(self._onItemClicked)
        self._table.setAlternatingRowColors(True)
        self._table.installEventFilter(
            self)  # catch focus and give to the edit
        self.layout().addWidget(self._table)

        width = QFontMetrics(self.font()).width('x' *
                                                64)  # width of 64 'x' letters
        self.resize(width, width * 0.62)

    def _terminate(self):
        if not self._terminated:
            if self._command is not None:
                self._command.terminate()
                self._command = None

            self._edit.terminate()

            self._completerLoaderThread.terminate()
            core.workspace().focusCurrentDocument()
            self._terminated = True

    def _updateCurrentCommand(self):
        """Try to parse line edit text and set current command
        """
        if self._terminated:
            return

        newCommand = self._parseCurrentCommand()

        if newCommand is not self._command:
            if self._command is not None:
                self._command.updateCompleter.disconnect(
                    self._updateCompletion)
                self._command.terminate()

            self._command = newCommand
            if self._command is not None:
                self._command.updateCompleter.connect(self._updateCompletion)

        self._updateCompletion()

    def _updateCompletion(self):
        """User edited text or moved cursor. Update inline and TreeView completion
        """
        if self._command is not None:
            completer = self._command.completer()

            if completer is not None and completer.mustBeLoaded:
                self._loadingTimer.start()
                self._completerLoaderThread.loadCompleter(
                    self._command, completer)
            else:
                self._applyCompleter(self._command, completer)
        else:
            self._applyCompleter(None, _HelpCompleter(self._commandClasses))

    def _applyLoadingCompleter(self):
        """Set 'Loading...' message
        """
        self._applyCompleter(None, StatusCompleter('<i>Loading...</i>'))

    def onCompleterLoaded(self, command, completer):
        """The method called from _CompleterLoaderThread when the completer is ready
        This code works in the GUI thread
        """
        self._applyCompleter(command, completer)

    def _applyCompleter(self, command, completer):
        """Apply completer. Called by _updateCompletion or by thread function when Completer is constructed
        """
        self._loadingTimer.stop()

        if command is not None:
            command.onCompleterLoaded(completer)

        if completer is None:
            completer = _HelpCompleter([command])

        if self._edit.cursorPosition() == len(
                self._edit.text()):  # if cursor at the end of text
            self._edit.setInlineCompletion(completer.inline())

        self._model.setCompleter(completer)
        if completer.columnCount() > 1:
            self._table.resizeColumnToContents(0)
            self._table.setColumnWidth(0,
                                       self._table.columnWidth(0) +
                                       20)  # 20 px spacing between columns

        selItem = completer.autoSelectItem()
        if selItem:
            index = self._model.createIndex(selItem[0], selItem[1])
            self._table.setCurrentIndex(index)

    def _onItemClicked(self, index):
        """Item in the TreeView has been clicked.
        Open file, if user selected it
        """
        if self._command is not None:
            fullText = self._model.completer.getFullText(index.row())
            if fullText is not None:
                self._command.onItemClicked(fullText)
                if self._tryExecCurrentCommand():
                    self.accept()
                    return
                else:
                    self._edit.setText(self._command.lineEditText())
                    self._updateCurrentCommand()

        self._edit.setFocus()

    def _onEnterPressed(self):
        """User pressed Enter or clicked item. Execute command, if possible
        """
        if self._table.currentIndex().isValid():
            self._onItemClicked(self._table.currentIndex())
        else:
            self._tryExecCurrentCommand()

    def _tryExecCurrentCommand(self):
        if self._command is not None and self._command.isReadyToExecute():
            self._command.execute()
            self.accept()
            return True
        else:
            return False

    def _chooseCommand(self, words):
        for cmd in self._commandClasses:
            if cmd.command == words[0]:
                return cmd, words[1:]

        isPath = words and (words[0].startswith('/')
                            or words[0].startswith('./')
                            or words[0].startswith('../')
                            or words[0].startswith('~/')
                            or words[0][1:3] == ':\\' or words[0][1:3] == ':/')
        isNumber = len(words) == 1 and all([c.isdigit() for c in words[0]])

        def matches(cmd):
            if isPath:
                return cmd.isDefaultPathCommand
            elif isNumber:
                return cmd.isDefaultNumericCommand
            else:
                return cmd.isDefaultCommand

        for cmd in self._commandClasses:
            if matches(cmd):
                return cmd, words

    def _parseCurrentCommand(self):
        """ Parse text and try to get (command, completable word index)
        Return None if failed to parse
        """
        # Split line
        text = self._edit.commandText()
        words = splitLine(text)
        if not words:
            return None

        # Find command
        cmdClass, args = self._chooseCommand(words)

        if isinstance(self._command, cmdClass):
            command = self._command
        else:
            command = cmdClass()

        # Try to make command object
        try:
            command.setArgs(args)
        except InvalidCmdArgs:
            return None
        else:
            return command

    def eventFilter(self, obj, event):
        if obj is self._edit:
            if event.type() == QEvent.KeyPress and \
               event.key() in (Qt.Key_Up, Qt.Key_Down, Qt.Key_PageUp, Qt.Key_PageDown):
                return self._table.event(event)
        elif obj is self._table:
            if event.type() == QEvent.FocusIn:
                self._edit.setFocus()
                return True

        return False
Exemplo n.º 29
0
class PyCommonist(QWidget):

    tool = None

    def __init__(self):
        super(PyCommonist, self).__init__()
        self.initUI()
        self.threads = []
        self.workers = []

    def initUI(self):

        self.currentDirectoryPath = ""

        self.generateSplitter()
        self.generateLeftTopFrame()
        self.generateLeftBottomFrame()

        self.showMaximized()
        self.setWindowTitle("PyCommonist - Wikimedia Commons")
        self.show()

    """
        onSelectFolder
    """

    def onSelectFolder(self, selected, deselected):

        try:
            currentIndex = selected.indexes()[0]
            self.currentDirectoryPath = self.modelTree.filePath(currentIndex)
            print(self.currentDirectoryPath)
            self.statusBar.setText("")
            self.exifImageCollection = []

            list_dir = os.listdir(self.currentDirectoryPath)
            files = [
                f for f in sorted(list_dir)
                if isfile(join(self.currentDirectoryPath, f))
            ]
            for file in files:
                fullFilePath = os.path.join(self.currentDirectoryPath, file)
                if fullFilePath.endswith(".jpeg") or fullFilePath.endswith(
                        ".jpg") or fullFilePath.endswith(".png"):

                    currentExifImage = EXIFImage()
                    currentExifImage.fullFilePath = fullFilePath
                    currentExifImage.filename = file
                    tags = None

                    try:
                        """ EXIF """
                        f_exif = open(fullFilePath, "rb")
                        tags = exifread.process_file(f_exif)
                        # print(tags)
                    except:
                        print("A problem with EXIF data reading")
                    """ Location"""
                    # 'GPS GPSLatitude', 'GPS GPSLongitude'] # [45, 49, 339/25] [4, 55, 716/25]
                    # 'GPS GPSImgDirection' 'GPS GPSLatitudeRef'
                    lat = ""
                    long = ""
                    heading = ""
                    try:
                        currentExifImage.lat, currentExifImage.long, currentExifImage.heading = get_exif_location(
                            tags)
                    except:
                        print("A problem with EXIF data reading")

                    dt = None
                    try:
                        """ Date Time """
                        dt = tags[
                            "EXIF DateTimeOriginal"]  # 2021:01:13 14:48:44
                    except:
                        print("A problem with EXIF data reading")

                    print(dt)
                    dt = str(dt)
                    indexSpace = dt.find(" ")
                    currentExifImage.date = dt[0:indexSpace].replace(":", "-")
                    currentExifImage.time = dt[indexSpace + 1:]

                    self.exifImageCollection.append(currentExifImage)
                    print(currentExifImage)

            self.generateRightFrame()

        except:
            print("Something bad happened inside onSelectFolder function")
            traceback.print_exc()

    """
        cbImportNoneStateChanged
    """

    def cbImportNoneStateChanged(self):

        print(self.cbImportNone.isChecked())
        print(len(self._currentUpload))

        if self.cbImportNone.isChecked() and len(self._currentUpload) > 0:

            for element in self._currentUpload:
                element.cbImport.setCheckState(False)

    """
        cbImportAllStateChanged
    """

    def cbImportAllStateChanged(self):

        print(self.cbImportAll.isChecked())
        print(len(self._currentUpload))
        if self.cbImportAll.isChecked() and len(self._currentUpload) > 0:

            for element in self._currentUpload:
                element.cbImport.setCheckState(True)

    """
        onClickImport
    """

    def onClickImport(self):
        if self.tool == None:
            self.tool = UploadTool()
        ret = self.tool.uploadImages(self)

    """
        cleanThreads
    """

    def cleanThreads(self):
        try:
            print("Clean properly threads")

            for thread in self.threads:
                print("Current thread proper deletion")
                thread.quit()
                thread.wait()

        except:
            print("A problem with cleanThreads")

    """
        generateSplitter
    """

    def generateSplitter(self):

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()

        self.leftTopFrame = QFrame()
        self.leftTopFrame.setFrameShape(QFrame.StyledPanel)

        self.rightWidget = QWidget()
        self.rightWidget.resize(300, 300)
        self.layoutRight = QVBoxLayout()
        self.rightWidget.setLayout(self.layoutRight)

        self.scroll = QScrollArea()
        self.layoutRight.addWidget(self.scroll)
        self.scroll.setWidgetResizable(True)
        self.scrollContent = QWidget(self.scroll)

        self.scrollLayout = QVBoxLayout(self.scrollContent)
        self.scrollContent.setLayout(self.scrollLayout)
        self.scroll.setWidget(self.scrollContent)

        self.splitterLeft = QSplitter(Qt.Vertical)
        self.leftBottonFrame = QFrame()
        self.leftBottonFrame.setFrameShape(QFrame.StyledPanel)

        self.splitterLeft.addWidget(self.leftTopFrame)
        self.splitterLeft.addWidget(self.leftBottonFrame)
        self.splitterLeft.setSizes([VERTICAL_TOP_SIZE, VERTICAL_BOTTOM_SIZE])
        """ Horizontal Splitter """
        self.splitterCentral = QSplitter(Qt.Horizontal)
        self.splitterCentral.addWidget(self.splitterLeft)
        self.splitterCentral.addWidget(self.rightWidget)
        self.splitterCentral.setSizes(
            [HORIZONTAL_LEFT_SIZE, HORIZONTAL_RIGHT_SIZE])
        hbox.addWidget(self.splitterCentral)

        vbox.addLayout(hbox)
        """ Status Bar """
        self.statusBar = QLabel()
        self.statusBar.setStyleSheet(STYLE_STATUSBAR)
        vbox.addWidget(self.statusBar)

        self.setLayout(vbox)

    """
        generateLeftTopFrame
    """

    def generateLeftTopFrame(self):

        self.layoutLeftTop = QFormLayout()
        self.layoutLeftTop.setFormAlignment(Qt.AlignTop)

        self.lblUserName = QLabel("Username: "******"Password: "******"Source: ")
        self.lblSource.setAlignment(Qt.AlignLeft)
        self.lineEditSource = QLineEdit()
        self.lineEditSource.setFixedWidth(WIDTH_WIDGET)
        self.lineEditSource.setText(LeftFrameConfig.source)
        self.lineEditSource.setAlignment(Qt.AlignLeft)
        self.layoutLeftTop.addRow(self.lblSource, self.lineEditSource)

        self.lblAuthor = QLabel("Author: ")
        self.lblAuthor.setAlignment(Qt.AlignLeft)
        self.lineEditAuthor = QLineEdit()
        self.lineEditAuthor.setFixedWidth(WIDTH_WIDGET)
        self.lineEditAuthor.setText(LeftFrameConfig.author)
        self.lineEditAuthor.setAlignment(Qt.AlignLeft)
        self.layoutLeftTop.addRow(self.lblAuthor, self.lineEditAuthor)

        self.lblCategories = QLabel("Categories: ")
        self.lblCategories.setAlignment(Qt.AlignLeft)
        self.lineEditCategories = QLineEdit()
        self.lineEditCategories.setText(LeftFrameConfig.categories)
        self.lineEditCategories.setFixedWidth(WIDTH_WIDGET)
        self.lineEditCategories.setAlignment(Qt.AlignLeft)
        self.layoutLeftTop.addRow(self.lblCategories, self.lineEditCategories)

        self.lblLicense = QLabel("License: ")
        self.lblLicense.setAlignment(Qt.AlignLeft)
        self.lineEditLicense = QLineEdit()
        self.lineEditLicense.setFixedWidth(WIDTH_WIDGET)
        self.lineEditLicense.setText(LeftFrameConfig.licence)
        self.lineEditLicense.setAlignment(Qt.AlignLeft)
        self.layoutLeftTop.addRow(self.lblLicense, self.lineEditLicense)

        self.lblDescription = QLabel("Description: ")
        self.lblDescription.setAlignment(Qt.AlignLeft)
        self.lineEditDescription = QPlainTextEdit()
        self.lineEditDescription.setFixedWidth(WIDTH_WIDGET)
        self.layoutLeftTop.addRow(self.lblDescription,
                                  self.lineEditDescription)

        separationLeftTopFrame = QLabel()
        self.layoutLeftTop.addWidget(separationLeftTopFrame)
        """ Button Import & None/All checkboxes"""
        importWidget = QWidget()
        importLayout = QHBoxLayout()
        importWidget.setLayout(importLayout)

        self.cbImportNone = QCheckBox("None")
        self.cbImportNone.stateChanged.connect(self.cbImportNoneStateChanged)

        self.cbImportAll = QCheckBox("All")
        self.cbImportAll.stateChanged.connect(self.cbImportAllStateChanged)

        self.btnImport = QPushButton("Import!")

        self.btnImport.clicked.connect(self.onClickImport)

        importLayout.addWidget(self.cbImportNone)
        importLayout.addWidget(self.cbImportAll)
        importLayout.addWidget(self.btnImport)
        self.layoutLeftTop.addWidget(importWidget)
        importWidget.setStyleSheet("border:1px solid #808080;")
        self.cbImportNone.setStyleSheet("border:0px;")
        self.cbImportAll.setStyleSheet("border:0px;")

        self.btnImport.setStyleSheet(STYLE_IMPORT_BUTTON)
        """ Layout Association of the Left Top Frame"""
        self.leftTopFrame.setLayout(self.layoutLeftTop)

    """
        generateLeftBottomFrame
    """

    def generateLeftBottomFrame(self):

        self.layoutLeftBottom = QVBoxLayout()
        """Model for QTreeView"""
        self.modelTree = QFileSystemModel()
        self.modelTree.setRootPath(QDir.currentPath())
        self.modelTree.setFilter(QDir.Dirs)  # Only directories
        """ QTreeView """
        self.treeLeftBottom = QTreeView()
        self.treeLeftBottom.setModel(self.modelTree)
        self.treeLeftBottom.setAnimated(False)
        self.treeLeftBottom.setIndentation(10)
        self.treeLeftBottom.setColumnWidth(0, 300)
        self.treeLeftBottom.expandAll()
        self.treeLeftBottom.selectionModel().selectionChanged.connect(
            self.onSelectFolder)
        self.layoutLeftBottom.addWidget(self.treeLeftBottom)
        self.leftBottonFrame.setLayout(self.layoutLeftBottom)

    """
        generateRightFrame
    """

    def generateRightFrame(self):

        self._currentUpload = []

        layout = self.scrollLayout
        print(layout)
        print(layout.count())

        while layout.count():
            print("destroy")
            child = layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

        for currentExifImage in self.exifImageCollection:
            """ Current image """
            localWidget = ImageUpload()
            localLayout = QHBoxLayout()
            localLayout.setAlignment(Qt.AlignRight)
            localWidget.setLayout(localLayout)
            self.scrollLayout.addWidget(localWidget)
            self._currentUpload.append(localWidget)
            """Local Left Widget"""
            localLeftWidget = QWidget()
            localLeftLayout = QFormLayout()
            localLeftLayout.setAlignment(Qt.AlignRight)
            localLeftWidget.setLayout(localLeftLayout)
            localLayout.addWidget(localLeftWidget)
            """ import? + Import Status """
            cbImport = QCheckBox("Import")
            lblUploadResult = QLabel()
            lblUploadResult.setStyleSheet(STYLE_IMPORT_STATUS)
            localLeftLayout.addRow(cbImport, lblUploadResult)
            localWidget.cbImport = cbImport
            localWidget.lblUploadResult = lblUploadResult
            """ File Name of picture """
            lblFileName = QLabel("Name: ")
            lblFileName.setAlignment(Qt.AlignLeft)
            lineEditFileName = QLineEdit()
            lineEditFileName.setFixedWidth(WIDTH_WIDGET_RIGHT)
            lineEditFileName.setText(currentExifImage.filename)
            lineEditFileName.setAlignment(Qt.AlignLeft)
            localLeftLayout.addRow(lblFileName, lineEditFileName)
            localWidget.lineEditFileName = lineEditFileName
            """ Shadow Real FileName """
            lblRealFileName = QLineEdit()
            lblRealFileName.setText(currentExifImage.filename)
            localWidget.lblRealFileName = lblRealFileName
            localWidget.lblRealFileName.isVisible = False
            """ Description """
            lblDescription = QLabel("Description: ")
            lblDescription.setAlignment(Qt.AlignLeft)
            lineEditDescription = QPlainTextEdit()
            lineEditDescription.setFixedWidth(WIDTH_WIDGET_RIGHT)
            localLeftLayout.addRow(lblDescription, lineEditDescription)
            localWidget.lineEditDescription = lineEditDescription
            """ Categories """
            lblCategories = QLabel("Categories: ")
            lblCategories.setAlignment(Qt.AlignLeft)
            lineEditCategories = QLineEdit()
            lineEditCategories.setFixedWidth(WIDTH_WIDGET_RIGHT)
            lineEditCategories.setAlignment(Qt.AlignLeft)
            localLeftLayout.addRow(lblCategories, lineEditCategories)
            localWidget.lineEditCategories = lineEditCategories

            lblLocation = QLabel("Location: ")
            lblLocation.setAlignment(Qt.AlignLeft)
            lineEditLocation = QLineEdit()
            lineEditLocation.setFixedWidth(WIDTH_WIDGET_RIGHT)
            if currentExifImage.lat == None or currentExifImage.long == None:
                lineEditLocation.setText("")
            else:
                lineEditLocation.setText(
                    str(currentExifImage.lat) + "|" +
                    str(currentExifImage.long) + "|heading:" +
                    str(currentExifImage.heading))
            lineEditLocation.setAlignment(Qt.AlignLeft)
            localLeftLayout.addRow(lblLocation, lineEditLocation)
            localWidget.lineEditLocation = lineEditLocation

            lblDateTime = QLabel("Date Time: ")
            lblDateTime.setAlignment(Qt.AlignLeft)
            lineEditDateTime = QLineEdit()
            lineEditDateTime.setFixedWidth(WIDTH_WIDGET_RIGHT)
            lineEditDateTime.setText(currentExifImage.date + " " +
                                     currentExifImage.time)
            lineEditDateTime.setAlignment(Qt.AlignLeft)
            localLeftLayout.addRow(lblDateTime, lineEditDateTime)
            localWidget.lineEditDateTime = lineEditDateTime
            """ Image itself """
            label = QLabel()
            pixmap = QPixmap(currentExifImage.fullFilePath)
            pixmapResize = pixmap.scaledToWidth(IMAGE_DIMENSION,
                                                Qt.FastTransformation)
            label.setPixmap(pixmapResize)
            localLayout.addWidget(label)
            localWidget.fullFilePath = currentExifImage.fullFilePath

            self.update()
Exemplo n.º 30
0
class ImageViewer(QWidget):
    def __init__(self):

        super(ImageViewer, self).__init__()

        pal = QPalette()
        pal.setColor(QPalette.Background, Qt.lightGray)

        self.factor = 3.0

        self.config = Config()
        self.currentRep = ""

        self.createActions()
        self.createToolbarMenus()
        #self.createMenus()

        self.browserFile()
        self.imgqLabel()
        self.boxSliders()

        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout(self)

        self.textInfo = QTextEdit()

        self.textInfoTop = QTextEdit()
        self.textInfoTop.setEnabled(True)
        self.textInfoTop.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Ignored)
        self.textInfoTop.setFontPointSize(11)
        self.textInfoTop.setStyleSheet("background-color: lightgray")
        #self.textInfoTop.adjustSize()
        self.textInfoTop.setText('Welcome to IRMaGe')

        self.tableJson = QTableWidget()
        self.tableJson.setColumnCount(2)
        self.tableJson.setColumnWidth(0, 150)
        self.tableJson.setColumnWidth(1, 400)
        self.tableJson.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)

        self.tableJson.setHorizontalHeaderLabels(['Keys', 'Values'])
        #self.tableJson.setBackgroundRole(QPalette.Light)

        self.scrollText = QScrollArea()
        self.scrollText.setBackgroundRole(QPalette.Dark)
        self.scrollText.setWidget(self.textInfoTop)
        self.scrollText.setWidgetResizable(True)
        #=======================================================================
        # self.adjustScrollBar(self.scrollText.horizontalScrollBar(), 1.0)
        # self.adjustScrollBar(self.scrollText.verticalScrollBar(), 2.0)
        #=======================================================================
        self.scrollTable = QScrollArea()
        self.scrollTable.setBackgroundRole(QPalette.Dark)
        self.scrollTable.setWidget(self.tableJson)
        self.scrollTable.setWidgetResizable(True)
        #=======================================================================
        # self.adjustScrollBar(self.scrollTable.horizontalScrollBar(), 2.0)
        # self.adjustScrollBar(self.scrollTable.verticalScrollBar(), 2.0)
        #=======================================================================

        self.headerTabData = [
            'Data', 'PatientName', 'StudyName', 'DateCreation', 'PatientSex',
            'PatientWeight', 'ProtocolName', 'SequenceName'
        ]

        self.tableData = TableDataBrower(self)
        self.tableData.setColumnCount(8)
        self.tableData.setRowCount(10)
        self.tableData.setColumnWidth(0, 200)
        self.tableData.setHorizontalHeaderLabels(self.headerTabData)
        self.tableData.setBackgroundRole(QPalette.Light)
        self.tableData.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)
        self.tableData.verticalHeader().hide()

        self.scrollBrowser = QScrollArea()
        self.scrollBrowser.setBackgroundRole(QPalette.Dark)
        self.scrollBrowser.setWidget(self.tableData)
        self.scrollBrowser.setWidgetResizable(True)

        self.splitter0 = QSplitter(Qt.Vertical)
        self.splitter0.addWidget(self.scrollText)
        self.splitter0.addWidget(self.scrollTable)

        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.imageLabel)
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setAlignment(Qt.AlignCenter)

        self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), 0.8)
        self.adjustScrollBar(self.scrollArea.verticalScrollBar(), 1.0)

        self.splitter1 = QSplitter(Qt.Horizontal)
        self.splitter1.addWidget(self.splitter0)
        self.splitter1.addWidget(self.scrollArea)
        self.splitter1.addWidget(self.layoutSlide)

        self.splitter3 = QSplitter(Qt.Horizontal)
        self.splitter3.addWidget(self.browser)
        self.splitter3.addWidget(self.scrollBrowser)

        self.splitter2 = QSplitter(Qt.Vertical)
        self.splitter2.addWidget(self.splitter1)
        self.splitter2.addWidget(self.splitter3)
        self.splitter2.setHandleWidth(15)
        #=======================================================================
        # self.splitter2.
        #=======================================================================

        self.verticalLayout.addWidget(self.menuToolBar)
        self.verticalLayout.addWidget(self.splitter2)

        self.setWindowTitle("MRImage Viewer (IRMaGe)")
        self.resize(800, 600)

        self.setAutoFillBackground(True)
        self.setPalette(pal)

    def changeSel(self):
        print('Tab changed')

    def adjustScrollBar(self, scrollBar, factor):
        scrollBar.setValue(
            int(factor * scrollBar.value() +
                ((factor - 1) * scrollBar.pageStep() / 2)))

    def imgqLabel(self):
        QLabel.__init__(self)
        image = QImage('sources_images/LogoIRMaGe.png')
        self.scaleFactor = 1.0
        self.imageLabel = QLabel()
        self.imageLabel.setBackgroundRole(QPalette.Base)
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)
        self.imageLabel.setPixmap(QPixmap.fromImage(image))
        self.scaleFactor *= self.factor
        self.imageLabel.adjustSize()
        self.imageLabel.resize(self.scaleFactor *
                               self.imageLabel.pixmap().size())

    def open(self, filePath):
        self.img = nib.load(filePath)
        self.textInfoTop.setText('File : ' + filePath + '\n')
        self.textInfoTop.append('Dim : ' + str(self.img.shape) + '\n')
        self.enableSliders()
        self.a1.setValue(0)
        self.a2.setValue(0)
        self.a3.setValue(0)
        self.c2.setMaximum(self.img.shape[0])
        self.c2.setMinimum(-self.img.shape[0])
        self.c3.setMaximum(self.img.shape[1])
        self.c3.setMinimum(-self.img.shape[1])
        self.navigImage()
        self.fitToWindowAct.setEnabled(True)
        self.fitToWindow()

    def openJson(self, pathJson, fileName):
        with open(pathJson, 'r') as stream:
            try:
                json_object = json.load(stream)
                data = json.dumps(json_object, indent=0, sort_keys=True)
                data = json.loads(data)
                rowPosition = 0
                self.tableJson.setRowCount(0)

                i = 0
                for keyd in self.headerTabData:
                    try:
                        val = str(data[keyd])
                        val = val.replace('[', '')
                        val = val.replace(']', '')
                    except:
                        val = ''
                    #===========================================================
                    # self.tableData.insertRow(i)
                    # self.tableData.setItem(0,i,QTableWidgetItem(val))
                    # i+=1
                    #===========================================================
                #===============================================================
                # self.tableData.setItem(0,0,QTableWidgetItem(fileName))
                # self.tableData.selectRow(0)
                #===============================================================
                for keys in data:
                    stringValue = str(data[keys])
                    stringValue = stringValue.replace('[', '')
                    stringValue = stringValue.replace(']', '')
                    self.tableJson.insertRow(rowPosition)
                    self.tableJson.setItem(rowPosition, 0,
                                           QTableWidgetItem(keys))
                    self.tableJson.setItem(rowPosition, 1,
                                           QTableWidgetItem(stringValue))
                    rowPosition += 1
                self.tableJson.resizeColumnsToContents()
            except json.JSONDecodeError as exc:
                itemError = 'Error Json format'
                self.tableJson.setRowCount(0)
                self.tableJson.insertRow(0)
                self.tableJson.setItem(0, 0, QTableWidgetItem(itemError))
                print(exc)

    def jsonParser(self, pathJson):
        with open(pathJson, 'r') as stream:
            try:
                json_object = json.load(stream)
                listTag = json.dumps(json_object, indent=0, sort_keys=True)
                listTag = json.loads(listTag)
            except json.JSONDecodeError as exc:
                itemError = 'Error Json format'
        return listTag

    def tableDataFill(self, pathRepertory):
        files = [f for f in fnmatch.filter(os.listdir(pathRepertory), '*.nii')]
        self.tableData.setRowCount(0)
        j = 0
        for f in files:
            base = os.path.splitext(f)[0]
            g = os.path.join(pathRepertory, base + ".json")
            self.tableData.insertRow(j)
            if os.path.isfile(g):
                data = self.jsonParser(g)
                i = 0
                for keyw in self.headerTabData:
                    try:
                        val = str(data[keyw])
                        val = val.replace('[', '')
                        val = val.replace(']', '')
                    except:
                        val = ''
                    self.tableData.setItem(j, i, QTableWidgetItem(val))
                    i += 1
            else:
                self.tableData.setItem(j, 1,
                                       QTableWidgetItem('No json file found'))
            self.tableData.setItem(j, 0, QTableWidgetItem(f))
            self.tableData.resizeColumnsToContents()
            j += 1

    def indexImage(self):
        sl1 = self.a1.value()
        sl2 = self.a2.value()
        sl3 = self.a3.value()
        if len(self.img.shape) == 3:
            x = self.img.get_data()[:, :, sl1].copy()
            self.a1.setMaximum(self.img.shape[2] - 1)
            self.a2.setMaximum(0)
            self.a3.setMaximum(0)
        if len(self.img.shape) == 4:
            x = self.img.get_data()[:, :, sl1, sl2].copy()
            self.a1.setMaximum(self.img.shape[2] - 1)
            self.a2.setMaximum(self.img.shape[3] - 1)
            self.a3.setMaximum(0)
        if len(self.img.shape) == 5:
            x = self.img.get_data()[:, :, sl1, sl2, sl3].copy()
            self.a1.setMaximum(self.img.shape[2] - 1)
            self.a2.setMaximum(self.img.shape[3] - 1)
            self.a3.setMaximum(self.img.shape[4] - 1)
        x = rotate(x, -90, reshape=False)
        x = np.uint8((x - x.min()) / x.ptp() * 255.0)
        self.x = x

############################ Slice controls  #########################################

    def boxSliders(self):
        self.k1 = QLabel('Slider 1    ')
        self.k2 = QLabel('Slider 2')
        self.k3 = QLabel('Slider 3')

        self.a1 = self.createSlider(0, 0, 0)
        self.a2 = self.createSlider(0, 0, 0)
        self.a3 = self.createSlider(0, 0, 0)

        self.a1.valueChanged.connect(self.changePosValue)
        self.a2.valueChanged.connect(self.changePosValue)
        self.a3.valueChanged.connect(self.changePosValue)

        self.txta1 = self.createFieldValue()
        self.txta2 = self.createFieldValue()
        self.txta3 = self.createFieldValue()

        self.controlsGroup = QGroupBox('Slice Controls')
        gridCtrl = QGridLayout()
        gridCtrl.addWidget(self.k1, 0, 0)
        gridCtrl.addWidget(self.a1, 0, 1)
        gridCtrl.addWidget(self.txta1, 0, 2)
        gridCtrl.addWidget(self.k2, 1, 0)
        gridCtrl.addWidget(self.a2, 1, 1)
        gridCtrl.addWidget(self.txta2, 1, 2)
        gridCtrl.addWidget(self.k3, 2, 0)
        gridCtrl.addWidget(self.a3, 2, 1)
        gridCtrl.addWidget(self.txta3, 2, 2)
        self.controlsGroup.setLayout(gridCtrl)

        ############################ brightness and contrast  ################################
        self.txtb1 = self.createFieldValue()
        self.txtb2 = self.createFieldValue()
        self.txtb3 = self.createFieldValue()
        self.txtb4 = self.createFieldValue()

        self.l1 = QLabel('Brightness    ')
        self.b1 = self.createSlider(101, 0, 50)
        self.l2 = QLabel('Contrast')
        self.b2 = self.createSlider(101, 0, 50)
        self.l3 = QLabel('Sharpness')
        self.b3 = self.createSlider(101, 0, 50)
        self.l4 = QLabel('Color')
        self.b4 = self.createSlider(101, 0, 50)

        self.b1.valueChanged.connect(self.changeContValue)
        self.b2.valueChanged.connect(self.changeContValue)
        self.b3.valueChanged.connect(self.changeContValue)
        self.b4.valueChanged.connect(self.changeContValue)

        self.txtb1.setText(str(0))
        self.txtb2.setText(str(0))
        self.txtb3.setText(str(0))
        self.txtb4.setText(str(0))

        self.buttonResetContrast = QPushButton('reset', self)
        self.buttonResetContrast.setToolTip('Reset all values')
        self.buttonResetContrast.setEnabled(False)
        self.buttonResetContrast.clicked.connect(self.resetValuesContrast)

        self.contrastGroup = QGroupBox('Brightness and Contrast')
        gridCont = QGridLayout()
        gridCont.addWidget(self.l1, 0, 0)
        gridCont.addWidget(self.b1, 0, 1)
        gridCont.addWidget(self.txtb1, 0, 2)
        gridCont.addWidget(self.l2, 1, 0)
        gridCont.addWidget(self.b2, 1, 1)
        gridCont.addWidget(self.txtb2, 1, 2)
        gridCont.addWidget(self.l3, 2, 0)
        gridCont.addWidget(self.b3, 2, 1)
        gridCont.addWidget(self.txtb3, 2, 2)
        gridCont.addWidget(self.l4, 3, 0)
        gridCont.addWidget(self.b4, 3, 1)
        gridCont.addWidget(self.txtb4, 3, 2)
        gridCont.addWidget(self.buttonResetContrast, 4, 2)
        self.contrastGroup.setLayout(gridCont)

        ############################ Transformation  #########################################
        self.txtc1 = self.createFieldValue()
        self.txtc2 = self.createFieldValue()
        self.txtc3 = self.createFieldValue()
        self.txtc4 = self.createFieldValue()

        self.m1 = QLabel('Rotation')
        self.c1 = self.createSlider(180, -180, 0)
        self.m2 = QLabel('Translate X    ')
        self.c2 = self.createSlider(1, -1, 0)
        self.m3 = QLabel('Translate Y    ')
        self.c3 = self.createSlider(1, -1, 0)
        self.m4 = QLabel('Resize')
        self.c4 = self.createSlider(10, 0, 0)

        self.c1.valueChanged.connect(self.changeTransValue)
        self.c2.valueChanged.connect(self.changeTransValue)
        self.c3.valueChanged.connect(self.changeTransValue)
        self.c4.valueChanged.connect(self.changeTransValue)

        self.txtc1.setText(str(0))
        self.txtc2.setText(str(0))
        self.txtc3.setText(str(0))
        self.txtc4.setText(str(0))

        self.buttonResetTransform = QPushButton('reset', self)
        self.buttonResetTransform.setToolTip('Reset all values')
        self.buttonResetTransform.setEnabled(False)
        self.buttonResetTransform.clicked.connect(self.resetValuesTransform)

        self.transformationGroup = QGroupBox('Transformations')
        gridTransf = QGridLayout()
        gridTransf.addWidget(self.m1, 0, 0)
        gridTransf.addWidget(self.c1, 0, 1)
        gridTransf.addWidget(self.txtc1, 0, 2)
        gridTransf.addWidget(self.m2, 1, 0)
        gridTransf.addWidget(self.c2, 1, 1)
        gridTransf.addWidget(self.txtc2, 1, 2)
        gridTransf.addWidget(self.m3, 2, 0)
        gridTransf.addWidget(self.c3, 2, 1)
        gridTransf.addWidget(self.txtc3, 2, 2)
        gridTransf.addWidget(self.m4, 3, 0)
        gridTransf.addWidget(self.c4, 3, 1)
        gridTransf.addWidget(self.txtc4, 3, 2)
        gridTransf.addWidget(self.buttonResetTransform, 4, 2)
        self.transformationGroup.setLayout(gridTransf)

        ####################################################################################
        self.layoutSliders = QVBoxLayout()
        self.layoutSliders.addWidget(self.controlsGroup)
        self.layoutSliders.addWidget(self.contrastGroup)
        self.layoutSliders.addWidget(self.transformationGroup)

        self.layoutSlide = QWidget()
        self.layoutSlide.setLayout(self.layoutSliders)

    def createSlider(self, maxm=0, minm=0, pos=0):
        slider = QSlider(Qt.Horizontal)
        slider.setFocusPolicy(Qt.StrongFocus)
        #slider.setTickPosition(QSlider.TicksBothSides)
        slider.setTickInterval(1)
        #slider.setSingleStep(1)
        slider.setMaximum(maxm)
        slider.setMinimum(minm)
        slider.setValue(pos)
        slider.setEnabled(False)
        return slider

    def createFieldValue(self):
        fieldValue = QLineEdit()
        fieldValue.setEnabled(False)
        fieldValue.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        return fieldValue

    def displayPosValue(self):
        self.txta1.setText(
            str(self.a1.value() + 1) + ' / ' + str(self.a1.maximum() + 1))
        self.txta2.setText(
            str(self.a2.value() + 1) + ' / ' + str(self.a2.maximum() + 1))
        self.txta3.setText(
            str(self.a3.value() + 1) + ' / ' + str(self.a3.maximum() + 1))

    def changePosValue(self):
        self.navigImage()

    def navigImage(self):
        self.indexImage()
        self.displayPosValue()
        w, h = self.x.shape
        image = QImage(self.x.data, w, h, QImage.Format_Indexed8)
        self.pixm = QPixmap.fromImage(image)
        self.imageLabel.setPixmap(self.pixm)
        self.imageLabel.adjustSize()
        self.imageLabel.resize(self.scaleFactor *
                               self.imageLabel.pixmap().size())
        self.filter()

    def changeContValue(self):
        self.txtb1.setText(str(self.b1.value() - 50))
        self.txtb2.setText(str(self.b2.value() - 50))
        self.txtb3.setText(str(self.b3.value() - 50))
        self.txtb4.setText(str(self.b4.value() - 50))
        self.filter()

    def changeTransValue(self):
        self.txtc1.setText(str(self.c1.value()))
        self.txtc2.setText(str(self.c2.value()))
        self.txtc3.setText(str(self.c3.value()))
        self.txtc4.setText(str(self.c4.value()))
        self.filter()

    def filter(self):
        img = Image.fromarray(self.x, 'L')

        brightness = ImageEnhance.Brightness(img)
        newImg = brightness.enhance(1.2 * (self.b1.value() + 1) / 50.0)

        contrast = ImageEnhance.Contrast(newImg)
        newImg = contrast.enhance((self.b2.value() + 1) / 50.0)

        sharpness = ImageEnhance.Sharpness(newImg)
        newImg = sharpness.enhance(2.0 * (self.b3.value() + 1) / 50.0)

        color = ImageEnhance.Color(newImg)
        newImg = color.enhance((self.b4.value() + 1) / 50.0)

        newImg = newImg.rotate(self.c1.value())

        newImg = newImg.transform(
            img.size, Image.AFFINE,
            (1, 0, self.c2.value(), 0, 1, self.c3.value()))

        size1 = int(img.size[0] * (self.c4.value() + 1))
        size2 = int(img.size[1] * (self.c4.value() + 1))

        newImg = newImg.resize((size1, size2), Image.ANTIALIAS)

        self.pixm = QPixmap.fromImage(newImg.toqimage())
        self.imageLabel.setPixmap(self.pixm)
        self.imageLabel.adjustSize()
        self.imageLabel.resize(self.scaleFactor *
                               self.imageLabel.pixmap().size())

    def resetValuesContrast(self):
        self.b1.setSliderPosition(50)
        self.b2.setSliderPosition(50)
        self.b3.setSliderPosition(50)
        self.b4.setSliderPosition(50)
        self.changeContValue()

    def resetValuesTransform(self):
        self.c1.setSliderPosition(0)
        self.c2.setSliderPosition(0)
        self.c3.setSliderPosition(0)
        self.c4.setSliderPosition(0)
        self.changeTransValue()

    def enableSliders(self):
        self.a1.setEnabled(True)
        self.a2.setEnabled(True)
        self.a3.setEnabled(True)
        self.b1.setEnabled(True)
        self.b2.setEnabled(True)
        self.b3.setEnabled(True)
        self.b4.setEnabled(True)
        self.c1.setEnabled(True)
        self.c2.setEnabled(True)
        self.c3.setEnabled(True)
        self.c4.setEnabled(True)
        self.buttonResetContrast.setEnabled(True)
        self.buttonResetTransform.setEnabled(True)

####################################################################################

    def browserFile(self):

        global Browser, Model

        self.browser = QTreeView()

        model = QFileSystemModel()
        model.setNameFilters(['*.nii'])
        model.setNameFilterDisables(False)
        model.setReadOnly(True)

        self.browser.setModel(model)
        self.browser.expandAll()
        self.browser.setColumnWidth(0, 400)

        self.browser.selectionModel().selectionChanged.connect(self.select)

        Browser = self.browser
        Model = model

        #=======================================================================
        # self.browser.doubleClicked.connect(self.selection)
        #self.browser.clicked.connect(self.selection)
        #=======================================================================

    def select(self, signal):
        file_path = self.browser.model().filePath(signal.indexes()[0])
        shortName, fileExt = os.path.splitext(file_path)
        filePath, fileName = os.path.split(file_path)
        self.textInfo.setText(filePath)
        blackColor = QColor(0, 0, 0)

        if os.path.isfile(file_path):
            if fileExt == ".nii":
                if self.currentRep != filePath:
                    self.tableDataFill(filePath)
                    self.currentRep = filePath
                self.open(file_path)
                self.tableData.selectRow(
                    self.tableData.findItems(fileName,
                                             Qt.MatchExactly)[0].row())
                if os.path.isfile(shortName + '.json'):
                    greenColor = QColor(50, 150, 100)
                    self.textInfoTop.setTextColor(greenColor)
                    self.textInfoTop.append('Json file exists ' + '\n')
                    self.openJson(shortName + '.json', fileName)
                else:
                    redColor = QColor(255, 0, 0)
                    self.textInfoTop.setTextColor(redColor)
                    self.textInfoTop.append('Json file doesn\'t exist' + '\n')
                    self.tableJson.setRowCount(0)
        else:
            self.tableData.setRowCount(0)
            self.currentRep = filePath

        self.textInfoTop.setTextColor(blackColor)
        self.scrollText.setWidgetResizable(True)


####################################################################################

    def createMenus(self):
        self.fileMenu = QMenu("&File", self)
        self.fileMenu.addAction(self.exitAct)

        self.viewMenu = QMenu("&View", self)
        self.viewMenu.addAction(self.zoomInAct)
        self.viewMenu.addAction(self.zoomOutAct)
        self.viewMenu.addAction(self.normalSizeAct)
        self.viewMenu.addSeparator()
        self.viewMenu.addAction(self.fitToWindowAct)
        self.viewMenu.addSeparator()

        self.helpMenu = QMenu("&Help", self)
        self.helpMenu.addAction(self.aboutAct)

        self.menuBar = QMenuBar()

        self.menuBar.addMenu(self.fileMenu)
        self.menuBar.addMenu(self.viewMenu)
        self.menuBar.addMenu(self.helpMenu)

    def createToolbarMenus(self):
        self.menuToolBar = QToolBar()

        viewMenu = QToolButton()
        viewMenu.setText('View')
        viewMenu.setPopupMode(QToolButton.MenuButtonPopup)
        aMenu = QMenu()
        aMenu.addAction(self.zoomInAct)
        aMenu.addAction(self.zoomOutAct)
        aMenu.addAction(self.normalSizeAct)
        aMenu.addSeparator()
        aMenu.addAction(self.fitToWindowAct)
        viewMenu.setMenu(aMenu)

        helpMenu = QToolButton()
        helpMenu.setText('Help')
        helpMenu.setPopupMode(QToolButton.MenuButtonPopup)
        bMenu = QMenu()
        helpMenu.setMenu(bMenu)

        self.menuToolBar.addWidget(viewMenu)
        self.menuToolBar.addWidget(helpMenu)

    def createActions(self):
        self.exitAct = QAction("Exit",
                               self,
                               shortcut="Ctrl+Q",
                               triggered=self.close)

        self.zoomInAct = QAction("Zoom In (25%)",
                                 self,
                                 shortcut="Ctrl++",
                                 enabled=False,
                                 triggered=self.zoomIn)

        self.zoomOutAct = QAction("Zoom Out (25%)",
                                  self,
                                  shortcut="Ctrl+-",
                                  enabled=False,
                                  triggered=self.zoomOut)

        self.normalSizeAct = QAction("Normal Size",
                                     self,
                                     shortcut="Ctrl+S",
                                     enabled=False,
                                     triggered=self.normalSize)

        self.fitToWindowAct = QAction("Fit to Window",
                                      self,
                                      enabled=False,
                                      checkable=True,
                                      shortcut="Ctrl+F",
                                      triggered=self.fitToWindow)

    def zoomIn(self):
        self.factor = 1.25
        self.scaleImage(self.factor)

    def zoomOut(self):
        self.factor = 0.8
        self.scaleImage(self.factor)

    def normalSize(self):
        self.imageLabel.adjustSize()
        self.scaleFactor = 1.0

    def fitToWindow(self):
        fitToWindow = self.fitToWindowAct.isChecked()
        self.scrollArea.setWidgetResizable(fitToWindow)
        self.scrollText.setWidgetResizable(fitToWindow)
        if not fitToWindow:
            self.normalSize()

        self.updateActions()

    def updateActions(self):
        self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked())
        self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked())
        self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked())

    def scaleImage(self, factor):
        self.scaleFactor *= factor
        self.imageLabel.resize(self.scaleFactor *
                               self.imageLabel.pixmap().size())

        self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
        self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)

        self.zoomInAct.setEnabled(self.scaleFactor < 5.0)
        self.zoomOutAct.setEnabled(self.scaleFactor > 0.333)

    def close(self):
        self.close()
Exemplo n.º 31
0
        print('Directory') # Directory 출력
    else:
        path = model.filePath(index)
        label.setPixmap(QPixmap(path))

if __name__ == '__main__':
    app = QApplication(sys.argv)

    tree_view = QTreeView()
    tree_view.show()

    model = QFileSystemModel() # 파일 창 띄우기
    tree_view.setModel(model)

    root_path = "../" # 파일 경로
    model.setRootPath(root_path)
    tree_view.setRootIndex(model.index(root_path))
    tree_view.setColumnWidth(0, 400)
    tree_view.resize(700, 500)

    tree_view.setColumnHidden(1, True) # 두번째 컬럼 숨기기
    tree_view.setColumnHidden(2, True) # 세번째 컬럼 숨기기
    tree_view.setColumnHidden(3, True) # 네번째 컬럼 숨기기

    tree_view.doubleClicked.connect(double_click_event) # 트리 창 더블클릭하면 함수 double_click_event수행

    label = QLabel("label") # label 창 띄우기
    label.resize(600, 400) # label 창 크기 정하기
    label.show() # label 창 보여주기

    app.exec_()
Exemplo n.º 32
0
try:
    rootPath = parser.positionalArguments().pop(0)
except IndexError:
    rootPath = None

model = QFileSystemModel()
model.setRootPath("")
if parser.isSet(dontUseCustomDirectoryIconsOption):
    model.iconProvider().setOptions(
        QFileIconProvider.DontUseCustomDirectoryIcons)
tree = QTreeView()
tree.setModel(model)
if rootPath is not None:
    rootIndex = model.index(QDir.cleanPath(rootPath))
    if rootIndex.isValid():
        tree.setRootIndex(rootIndex)

# Demonstrating look and feel features.
tree.setAnimated(False)
tree.setIndentation(20)
tree.setSortingEnabled(True)

availableSize = QApplication.desktop().availableGeometry(tree).size()
tree.resize(availableSize / 2)
tree.setColumnWidth(0, tree.width() / 3)

tree.setWindowTitle("Dir View")
tree.show()

sys.exit(app.exec_())
Exemplo n.º 33
0
class MyWindow(QWidget):
    def __init__(self):
        super(MyWindow, self).__init__()

        self.setMinimumSize(1000, 1000)
        self.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.setWindowTitle(
            QCoreApplication.translate("MainWindow", "PyInspect"))

        self.settings = QSettings('py_inspect', 'MainWindow')

        # Main layout
        self.mainLayout = QGridLayout()

        # Backend label
        self.backendLabel = QLabel("Backend Type")

        # Backend combobox
        self.comboBox = QComboBox()
        self.comboBox.setMouseTracking(False)
        self.comboBox.setMaxVisibleItems(5)
        self.comboBox.setObjectName("comboBox")

        for _backend in backend.registry.backends.keys():
            self.comboBox.addItem(_backend)

        # Add top widgets to main window
        self.mainLayout.addWidget(self.backendLabel, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.comboBox, 0, 1, 1, 1)

        self.tree_view = QTreeView()
        self.tree_view.setColumnWidth(0, 150)

        self.comboBox.setCurrentText('uia')
        self.__initialize_calc()

        self.table_view = QTableView()

        self.comboBox.activated[str].connect(self.__show_tree)

        # Add center widgets to main window
        self.mainLayout.addWidget(self.tree_view, 1, 0, 1, 1)
        self.mainLayout.addWidget(self.table_view, 1, 1, 1, 1)

        self.setLayout(self.mainLayout)
        geometry = self.settings.value('Geometry', bytes('', 'utf-8'))
        self.restoreGeometry(geometry)

    def __initialize_calc(self, _backend='uia'):
        self.element_info \
            = backend.registry.backends[_backend].element_info_class()
        self.tree_model = MyTreeModel(self.element_info, _backend)
        self.tree_model.setHeaderData(0, Qt.Horizontal, 'Controls')
        self.tree_view.setModel(self.tree_model)
        self.tree_view.clicked.connect(self.__show_property)

    def __show_tree(self, text):
        backend = text
        self.__initialize_calc(backend)

    def __show_property(self, index=None):
        data = index.data()
        self.table_model \
            = MyTableModel(self.tree_model.props_dict.get(data), self)
        self.table_view.wordWrap()
        self.table_view.setModel(self.table_model)
        self.table_view.setColumnWidth(1, 320)

    def closeEvent(self, event):
        geometry = self.saveGeometry()
        self.settings.setValue('Geometry', geometry)
        super(MyWindow, self).closeEvent(event)