コード例 #1
0
    def __init__(self, main_window):
        """The constructor ...

        :param main_window: an instance of the MainWindow class
        """
        super(DataViewerTab, self).__init__()
        self.docs = []
        self.lay = []
        self.project = []
        self.stacks = []
        self.viewers_loaded = {}
        self.viewer_current = {}

        #Display of combobox containing the viewers
        self.main_window = main_window
        self.lay = Qt.QVBoxLayout()
        self.setLayout(self.lay)

        hlay = Qt.QHBoxLayout()
        self.lay.addLayout(hlay)
        hlay.addWidget(Qt.QLabel('use viewer:'))

        #Combobox will contain the viewers if they are available
        self.viewers_combo = Qt.QComboBox()
        self.viewers_combo.setMinimumWidth(150)

        hlay.addWidget(self.viewers_combo)
        hlay.addStretch(1)

        self.viewers_combo.currentIndexChanged.connect(self.change_viewer)
コード例 #2
0
    def paintEvent(self, event):
        if self._first_paint:
            self._first_paint = True
            self.update_buttons()

        painter = Qt.QStylePainter(self)
        opt = Qt.QStyleOptionTab()

        for i in range(self.count()):
            self.initStyleOption(opt, i)
            painter.drawControl(Qt.QStyle.CE_TabBarTabShape, opt)
            painter.save()

            s = opt.rect.size()
            s.transpose()
            r = Qt.QRect(Qt.QPoint(), s)
            r.moveCenter(opt.rect.center())
            opt.rect = r

            c = self.tabRect(i).center()
            painter.translate(c)
            painter.rotate(90)
            painter.translate(-c)
            painter.drawControl(Qt.QStyle.CE_TabBarTabLabel, opt)
            painter.restore()

        Qt.QWidget.paintEvent(self, event)
コード例 #3
0
ファイル: mia_anatomist.py プロジェクト: populse/populse_mia
    def __init__(self, init_global_handlers = None):

        super(MiaViewer, self).__init__()

        self.anaviewer = AnaSimpleViewer(init_global_handlers)

        # count global number of viewers using anatomist, in order to close it
        # nicely
        if not hasattr(DataViewer, 'mia_viewers'):
            DataViewer.mia_viewers = 0
        DataViewer.mia_viewers += 1

        findChild = lambda x, y: Qt.QObject.findChild(x, Qt.QObject, y)

        awidget = self.anaviewer.awidget
        toolbar = findChild(awidget, 'toolBar')
        open_action = findChild(awidget, 'fileOpenAction')
        db_action = Qt.QAction(open_action.icon(), 'filter', awidget)
        toolbar.insertAction(open_action, db_action)
        db_action.triggered.connect(self.filter_documents)

        layout = Qt.QVBoxLayout()
        self.setLayout(layout)
        self.anaviewer.awidget.setSizePolicy(Qt.QSizePolicy.Expanding,
                                          Qt.QSizePolicy.Expanding)
        layout.addWidget(self.anaviewer.awidget)

        self.project = None
        self.documents = []
        self.displayed = []
コード例 #4
0
    def update_buttons(self):
        # check if tab is closable
        if self.tabsClosable():
            opt = Qt.QStyleOptionTab()

            for i in range(self.count()):
                self.initStyleOption(opt, i)
                optRect = opt.rect
                optRect.setX(optRect.width() - 14)  # set X pos of close button
                optRect.setY(optRect.y() +
                             8)  # calcs the Y pos of close button
                optRect.setSize(Qt.QSize(12, 12))
                self.tabButton(i, Qt.QTabBar.RightSide).setGeometry(optRect)
コード例 #5
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self, None, QtCore.Qt.WindowStaysOnTopHint)

        #Load ui file
        uifile = 'second_window.ui'
        cwd = os.getcwd()
        mainwindowdir = os.path.join(cwd,
                                     'user_interface/data_viewer/anatomist_2')
        os.chdir(mainwindowdir)
        awin = loadUi(os.path.join(mainwindowdir, uifile))
        os.chdir(cwd)

        # connect GUI actions callbacks
        def findChild(x, y):
            return Qt.QObject.findChild(x, QtCore.QObject, y)

        self.window = awin
        self.viewNewWindow = findChild(awin, 'windows')
        self.newViewLay = Qt.QHBoxLayout(self.viewNewWindow)
        self.new_awindow = None
        self.object = None
        self.window_index = 0

        self.popup_window = Qt.QWidget()
        self.popup_window.setWindowFlags(self.windowFlags()
                                         | QtCore.Qt.WindowStaysOnTopHint)
        self.popups = []

        self.layout = Qt.QVBoxLayout()
        self.popup_window.setLayout(self.layout)
        self.popup_window.resize(730, 780)
        self.window.setSizePolicy(Qt.QSizePolicy.Expanding,
                                  Qt.QSizePolicy.Expanding)

        #find views viewButtons
        self.viewButtons = [
            findChild(awin, 'actionAxial'),
            findChild(awin, 'actionSagittal'),
            findChild(awin, 'actionCoronal'),
            findChild(awin, 'action3D')
        ]
        self.viewButtons[0].setChecked(True)

        self.viewButtons[0].triggered.connect(
            lambda: self.changeDisplay(0, self.object))
        self.viewButtons[1].triggered.connect(
            lambda: self.changeDisplay(1, self.object))
        self.viewButtons[2].triggered.connect(
            lambda: self.changeDisplay(2, self.object))
        self.viewButtons[3].triggered.connect(
            lambda: self.changeDisplay(3, self.object))
コード例 #6
0
ファイル: mia_anatomist.py プロジェクト: M40V/populse_mia
    def __init__(self, init_global_handlers=None):

        super(MiaViewer, self).__init__()

        self.anaviewer = AnaSimpleViewer2(init_global_handlers)

        # count global number of viewers using anatomist, in order to close it
        # nicely
        if not hasattr(DataViewer, 'mia_viewers'):
            DataViewer.mia_viewers = 0
        DataViewer.mia_viewers += 1

        findChild = lambda x, y: Qt.QObject.findChild(x, Qt.QObject, y)

        awidget = self.anaviewer.awidget

        filter_action = findChild(awidget, 'filterAction')
        preferences_action = findChild(awidget, 'actionPreferences')

        filter_action.triggered.connect(self.filter_documents)
        preferences_action.triggered.connect(self.preferences)

        layout = Qt.QVBoxLayout()
        self.setLayout(layout)
        self.anaviewer.awidget.setSizePolicy(Qt.QSizePolicy.Expanding,
                                             Qt.QSizePolicy.Expanding)
        layout.addWidget(self.anaviewer.awidget)

        self.project = None
        self.documents = []
        self.displayed = []
        self.table_data = []
コード例 #7
0
    def _label_context_menu(self, widget, control_name, pos):
        menu = Qt.QMenu(control_name, None)
        protect = menu.addAction('%s modified' % control_name)
        protect.setCheckable(True)
        protected = self.controller.is_parameter_protected(control_name)
        protect.setChecked(protected)

        menu.exec_(widget().mapToGlobal(pos))
        if protect.isChecked() != protected:
            self.controller.protect_parameter(control_name,
                                              protect.isChecked())
コード例 #8
0
ファイル: mia_anatomist.py プロジェクト: populse/populse_mia
    def filter_documents(self):
        dialog = Qt.QDialog()
        layout = Qt.QVBoxLayout()
        dialog.setLayout(layout)
        table_data = TableDataBrowser(
            self.project, self, self.project.session.get_shown_tags(), False,
            True, link_viewer=False)
        layout.addWidget(table_data)
        hlay = Qt.QHBoxLayout()
        layout.addLayout(hlay)
        ok = Qt.QPushButton('Display')
        hlay.addWidget(ok)
        ok.clicked.connect(dialog.accept)
        ok.setDefault(True)
        cancel = Qt.QPushButton('Cancel')
        hlay.addWidget(cancel)
        cancel.clicked.connect(dialog.reject)
        hlay.addStretch(1)

        # Reducing the list of scans to selection
        all_scans = table_data.scans_to_visualize
        table_data.scans_to_visualize = self.documents
        table_data.scans_to_search = self.documents
        table_data.update_visualized_rows(all_scans)

        res = dialog.exec_()
        if res == Qt.QDialog.Accepted:
            points = table_data.selectedIndexes()
            result_names = []
            for point in points:
                row = point.row()
                # We get the FileName of the scan from the first row
                scan_name = table_data.item(row, 0).text()
                value = self.project.session.get_value(COLLECTION_CURRENT,
                                                       scan_name, TAG_FILENAME)
                value = os.path.abspath(os.path.join(self.project.folder,
                                                     value))
                result_names.append(value)
            self.display_files(result_names)
コード例 #9
0
    def create_widget(parent, control_name, control_value, trait,
                      label_class=None, user_data=None):
        """ Method to create the string widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: str (mandatory)
            the default control value
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: QLineEdit,
            associated label: QLabel)
        """
        # Create the widget that will be used to fill a string
        try:
            str_value = str(control_value)
        except TypeError:
            try:
                str_value = repr(control_value)
            except TypeError:
                str_value = ' <%s>' % type(control_value).__name__

        widget = Qt.QLabel(
            '<style>background-color: gray; text-color: red;</style>'
            + str_value, parent)
        widget.setEnabled(False)

        # Create the label associated with the string widget
        control_label = getattr(trait, 'label', control_name)
        if label_class is None:
            label_class = Qt.QLabel
        if control_label is not None:
            label = label_class(control_label, parent)
        else:
            label = None

        return (widget, label)
コード例 #10
0
def wait_for_close(self, win):
    import threading
    from soma.qt_gui.qt_backend import Qt
    if isinstance(threading.current_thread(), threading._MainThread):
        # we are running in the main thread: use a local event loop to wait
        # for the editor window to be closed by the user. The destroyed
        # callback will take care of ending the loop.
        self.local_event_loop = Qt.QEventLoop()
        self.local_event_loop.exec_()
    else:
        # we are running in a secondary thrad: poll in the main thread for
        # the editor window to be closed by the user
        done = False
        while not done:
            time.sleep(0.1)
            done = mainThreadActions().call(getattr, self, 'win_deleted')
コード例 #11
0
    def create_widget(parent,
                      control_name,
                      control_value,
                      trait,
                      label_class=None,
                      user_data=None):
        """ Method to create the list widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: list of items (mandatory)
            the default control value
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: ,
            associated labels: (a label QLabel, the tools QWidget))
        """
        widget, labels = OffscreenListControlWidget.create_widget(
            parent,
            control_name,
            control_value,
            trait,
            label_class=label_class,
            user_data=user_data)

        button = Qt.QPushButton("...", widget)
        button.setObjectName('files_button')
        button.setStyleSheet('QPushButton#files_button '
                             '{padding: 2px 10px 2px 10px; margin: 0px;}')
        layout = widget.layout()
        layout.addWidget(button)
        button.clicked.connect(
            partial(OffscreenListFileControlWidget.select_files, widget))

        return (widget, labels)
コード例 #12
0
    def load_viewer(self, viewer_name):
        """Available viewers in data_viewer folder are loaded as soon
        as Data Viewer tab is clicked.

        :param viewer_name: string
        """
        if viewer_name:
            detected_viewer = [viewer_name]

        else:
            detected_viewer = [
                p for p in os.listdir(os.path.dirname(__file__))
                if os.path.isdir(
                    os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                 p))) and p != '__pycache__'
            ]

        if not self.viewers_loaded:
            self.stacks = Qt.QStackedLayout()
            self.lay.addLayout(self.stacks)

        init_global_handlers = True

        #Try import detected viewers
        for viewer_name in detected_viewer:

            if viewer_name not in self.viewers_loaded:

                try:
                    viewer_module = importlib.import_module(
                        '%s.%s' % (__name__.rsplit('.', 1)[0], viewer_name))
                    self.viewers_loaded[viewer_name] = viewer_module.MiaViewer(
                        init_global_handlers)
                    self.stacks.addWidget(self.viewers_loaded[viewer_name])
                    self.viewers_combo.addItem(viewer_name)
                    #Check if initialization of controls has been done:
                    if self.viewers_loaded[
                            viewer_name].anaviewer._global_handlers_initialized:
                        init_global_handlers = False

                except Exception as e:
                    print('\n{0} viewer is not available or not working '
                          '...!\nTraceback:'.format(viewer_name))
                    print(''.join(traceback.format_tb(e.__traceback__)),
                          end='')
                    print('{0}: {1}\n'.format(e.__class__.__name__, e))
コード例 #13
0
ファイル: type_editors.py プロジェクト: M40V/populse_mia
    def create_widget(parent,
                      control_name,
                      control_value,
                      trait,
                      label_class=None,
                      user_data=None):
        """ Method to create the Undefined widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: str (mandatory)
            the default control value
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: QLineEdit,
            associated label: QLabel)
        """

        # Create the widget
        widget = Qt.QLabel(
            '<style>background-color: gray; text-color: red;</style>' +
            str(traits.Undefined), parent)

        # Create the label associated with the string widget
        control_label = control_name
        if label_class is None:
            label_class = QtGui.QLabel
        if control_label is not None:
            label = label_class(control_label, parent)
        else:
            label = None

        return (widget, label)
コード例 #14
0
ファイル: settings_editor.py プロジェクト: servoz/capsul
    def __init__(self, engine, parent=None):
        super(SettingsEditor, self).__init__(parent)

        self.engine = engine

        layout = Qt.QVBoxLayout()
        self.setLayout(layout)

        env_layout = Qt.QHBoxLayout()
        layout.addLayout(env_layout)
        env_layout.addWidget(Qt.QLabel('Environment:'))
        self.environment_combo = Qt.QComboBox()
        self.environment_combo.setEditable(True)
        self.environment_combo.setInsertPolicy(
            Qt.QComboBox.InsertAlphabetically)
        self.environment_combo.addItem('global')
        env_layout.addWidget(self.environment_combo)

        #htab_layout = Qt.QHBoxLayout()
        self.tab_wid = QVTabWidget()  # Qt.QTabWidget()
        #self.tab_wid.setTabPosition(Qt.QTabWidget.West)
        layout.addWidget(self.tab_wid)
        self.module_tabs = {}

        buttons_layout = Qt.QHBoxLayout()
        layout.addLayout(buttons_layout)
        buttons_layout.addStretch(1)
        ok = Qt.QPushButton('OK')
        buttons_layout.addWidget(ok)
        cancel = Qt.QPushButton('Cancel')
        buttons_layout.addWidget(cancel)

        ok.clicked.connect(self.accept)
        cancel.clicked.connect(self.reject)
        #ok.setDefault(True)
        self.environment_combo.activated.connect(self.change_environment)

        self.update_gui()
コード例 #15
0
ファイル: application.py プロジェクト: M40V/capsul
    def __init__(self, extra_options=None):
        """ Method to initialize the Application class.

        The capsulview application can be executed with command
        line options (that can also be passed to the class constructor
        as extra_options). From the command line, we can set the
        debug level with the -d option:
        * debug
        * info
        * warning
        * error
        * critical

        For exemple:
        >>> capsulview -d debug

        The default mode is error.

        From the command line we can also redirect all messages
        to a graphical message box with the -r option:
        >>> capsulview -r

        Parameters
        ----------
        extra_options: list (optional)
            some additional options that are not passed through the command
            line.
        """
        # Inheritance
        Qt.QApplication.__init__(self, [])

        # Extra application options
        extra_options = extra_options or []

        # Define a mapping to the logging level
        levels = {
            "debug": logging.DEBUG,
            "info": logging.INFO,
            "warning": logging.WARNING,
            "error": logging.ERROR,
            "critical": logging.CRITICAL
        }

        # Parse command line and internal options
        parser = optparse.OptionParser()
        parser.add_option("-d",
                          "--debug",
                          dest="debug",
                          help="Set the logging level "
                          "(debug, info, warning, error, or critical",
                          metavar="LEVEL")
        parser.add_option("-r",
                          "--redirect-to-messagebox",
                          dest="redirect",
                          action="store_true",
                          default=False,
                          help="Redirect all messages to the console")
        parser.add_option("-t",
                          "--test",
                          dest="test",
                          action="store_true",
                          default=False,
                          help="Add a set of test pipelines")
        for args, kwargs in extra_options:
            parser.add_option(*args, **kwargs)
        self.options, self.arguments = parser.parse_args()

        # Logging format
        logging_format = ("[%(asctime)s] "
                          "{%(pathname)s:%(lineno)d} "
                          "%(levelname)s - %(message)s")
        date_format = "%Y-%m-%d %H:%M:%S"

        # If someone tried to log something before basicConfig is called,
        # Python creates a default handler that goes to the console and
        # will ignore further basicConfig calls: we need to remove the
        # handlers if there is one.
        while len(logging.root.handlers) > 0:
            logging.root.removeHandler(logging.root.handlers[-1])

        # If the logging level is specified
        if self.options.debug is not None:

            # Get the real logging level from the mapping
            level = levels.get(self.options.debug, None)

            # If a no valid logging level is found raise an Exception
            if level is None:
                raise Exception("Warning : unknown logging level "
                                "{0}".format(self.options.debug))

            # Configure the logging module
            logging.basicConfig(level=level,
                                format=logging_format,
                                datefmt=date_format)

            # Disable deprecation warnings if we are not in the debug mode
            if level != logging.DEBUG:
                warnings.simplefilter("ignore", DeprecationWarning)

        # Set the default logging level
        else:
            logging.basicConfig(level=logging.ERROR,
                                format=logging_format,
                                datefmt=date_format)

            # Disable deprecation warnings
            warnings.simplefilter("ignore", DeprecationWarning)

        # Check if the redirection option is found: redirecect stdout and
        # stderr to a message box
        if self.options.redirect:

            # Create a message box
            self.message_box = Qt.QTextEdit()

            # Redirect stdout and stderr
            sys.stdout = EmittingStream()
            sys.stderr = EmittingStream()

            # Connect with text written signal
            self.connect(sys.stdout, Qt.SIGNAL('textWritten(QString)'),
                         self._on_text_print)
            self.connect(sys.stderr, Qt.SIGNAL('textWritten(QString)'),
                         self._on_text_print)

            # Update root logger handler
            root_logger = logging.getLogger()
            h = root_logger.handlers[0]
            h.stream = sys.stdout
コード例 #16
0
ファイル: Compound.py プロジェクト: populse/soma-base
    def create_widget(parent,
                      control_name,
                      control_value,
                      trait,
                      label_class=None,
                      user_data=None):
        """ Create the widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: str (mandatory)
            the default control value, here the enum values
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: QComboBox,
            associated label: QLabel)
        """
        # Create the widget that will be used to select a value
        widget = Qt.QWidget(parent)

        # we have a combobox for the trait type, and one of the control types
        # implementations depending on it

        layout = Qt.QVBoxLayout()
        widget.setLayout(layout)
        widget.type_combo = Qt.QComboBox()
        hlayout = Qt.QHBoxLayout()
        #layout.addLayout(hlayout)
        lwidget = Qt.QWidget()
        lwidget.setLayout(hlayout)
        hlayout.addWidget(Qt.QLabel('Compound type:'))
        hlayout.addWidget(widget.type_combo)
        widget.header_widget = lwidget
        widget.user_data = user_data

        # get compound types
        types = trait_ids(trait)
        for t in types:
            widget.type_combo.addItem(t)
        widget.type_combo.setCurrentIndex(0)

        widget.compound_widget = None
        widget.trait = trait  # we need to access it later
        widget.trait_name = control_name
        widget.compound_label = None

        type_id = CompoundControlWidget.type_id_for(trait.handler.handlers,
                                                    control_value)
        widget.current_type_id = type_id
        widget.type_combo.setCurrentIndex(type_id)

        CompoundControlWidget.create_compound_widget(widget)

        widget.type_combo.currentIndexChanged.connect(
            partial(CompoundControlWidget.change_type_index, widget))

        # Add a parameter to tell us if the widget is optional
        widget.optional = trait.optional

        # Create the label associated with the enum widget
        control_label = trait.label
        if control_label is None:
            control_label = control_name
        if label_class is None:
            label_class = Qt.QLabel
        if control_label is not None:
            label = (label_class(control_label, parent), lwidget)
        else:
            label = lwidget

        return (widget, label)
コード例 #17
0
ファイル: type_editors.py プロジェクト: M40V/populse_mia
    def create_widget(parent,
                      control_name,
                      control_value,
                      trait,
                      label_class=None,
                      user_data=None):
        """ Method to create the list widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: list of items (mandatory)
            the default control value
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: ,
            associated labels: (a label QLabel, the tools QWidget))
        """
        widget, label = OffscreenListFileControlWidget.create_widget(
            parent,
            control_name,
            control_value,
            trait,
            label_class=label_class,
            user_data=user_data)

        layout = widget.layout()

        project = user_data.get('project')
        scan_list = user_data.get('scan_list')
        main_window = user_data.get('main_window')
        if project and scan_list:
            # Create a browse button
            button = Qt.QPushButton("Filter", widget)
            button.setObjectName('filter_button')
            button.setStyleSheet('QPushButton#filter_button '
                                 '{padding: 2px 10px 2px 10px; margin: 0px;}')
            layout.addWidget(button)
            widget.filter_b = button

            # Set a callback on the browse button
            control_class = parent.get_control_class(trait)
            node_name = getattr(parent.controller, 'name', None)
            if node_name is None:
                node_name = parent.controller.__class__.__name__
            browse_hook = partial(control_class.filter_clicked,
                                  weak_proxy(widget), node_name, control_name)
            #parameters, process)
            widget.filter_b.clicked.connect(browse_hook)

        return (widget, label)
コード例 #18
0
ファイル: mia_anatomist.py プロジェクト: M40V/populse_mia
    def filter_documents(self):
        '''Filter documents already loaded in the Databrowser
        '''
        dialog = Qt.QDialog()
        dialog.setWindowTitle('Filter documents')
        dialog.resize(1150, 500)
        layout = Qt.QVBoxLayout()
        dialog.setLayout(layout)

        #Some specific filtering
        #QLineEdit for research
        self.search_bar = RapidSearch(dialog)
        self.search_bar.textChanged.connect(self.search_str)
        #Cancel search button
        sources_images_dir = Config().getSourceImageDir()
        button_cross = QToolButton()
        button_cross.setStyleSheet('background-color:rgb(255, 255, 255);')
        button_cross.setIcon(
            QIcon(os.path.join(sources_images_dir, 'gray_cross.png')))
        button_cross.clicked.connect(self.reset_search_bar)

        title = Qt.QLabel()
        title.setText('Search by FileName: ')

        layout.addWidget(title)

        search_bar_layout = QHBoxLayout()
        search_bar_layout.addWidget(self.search_bar)
        search_bar_layout.addSpacing(3)
        search_bar_layout.addWidget(button_cross)
        #Add layout to dialogBox
        layout.addLayout(search_bar_layout)
        layout.addSpacing(8)

        self.table_data = TableDataBrowser(
            self.project,
            self,
            self.project.session.get_shown_tags(),
            False,
            True,
            link_viewer=False)
        layout.addWidget(self.table_data)
        hlay = Qt.QHBoxLayout()
        layout.addLayout(hlay)
        ok = Qt.QPushButton('Import')
        hlay.addWidget(ok)
        ok.clicked.connect(dialog.accept)
        ok.setDefault(True)
        cancel = Qt.QPushButton('Cancel')
        hlay.addWidget(cancel)
        cancel.clicked.connect(dialog.reject)
        hlay.addStretch(1)

        # Reducing the list of scans to selection
        all_scans = self.table_data.scans_to_visualize
        self.table_data.scans_to_visualize = self.documents
        self.table_data.scans_to_search = self.documents
        self.table_data.update_visualized_rows(all_scans)

        res = dialog.exec_()
        if res == Qt.QDialog.Accepted:
            points = self.table_data.selectedIndexes()
            result_names = []
            for point in points:
                row = point.row()
                # We get the FileName of the scan from the first row
                scan_name = self.table_data.item(row, 0).text()
                value = self.project.session.get_value(COLLECTION_CURRENT,
                                                       scan_name, TAG_FILENAME)
                value = os.path.abspath(
                    os.path.join(self.project.folder, value))
                result_names.append(value)
            self.display_files(result_names)
コード例 #19
0
ファイル: mia_anatomist.py プロジェクト: M40V/populse_mia
    def preferences(self):
        '''Preferences for the dataviewer
        '''
        #Get initial config:
        im_sec = Config().getViewerFramerate()
        config = Config().getViewerConfig()
        ref = Config().get_referential()

        dialog = Qt.QDialog()
        dialog.setWindowTitle('Preferences')
        dialog.resize(600, 400)
        layout = Qt.QVBoxLayout()
        layout.setContentsMargins(25, 25, 25, 25)
        dialog.setLayout(layout)

        #Change Neuro/Radio configuration
        config_layout = QHBoxLayout()
        title_config = Qt.QLabel()
        title_config.setText('Configuration: ')
        box = Qt.QComboBox()
        box.addItem('Neuro')
        box.addItem('Radio')
        config_layout.addWidget(title_config)
        config_layout.addWidget(box)
        if config == 'radio':
            box.setCurrentIndex(1)

        #set automatic time frame rate
        frame_rate_layout = QHBoxLayout()
        title = Qt.QLabel()
        title.setText('Automatic time image display:')
        slider = Qt.QSlider(Qt.Qt.Horizontal)
        slider.setRange(1, 100)
        slider.setValue(int(im_sec))
        size = QtCore.QSize(180, 15)
        slider.setMinimumSize(size)
        slow_label = Qt.QLabel()
        fast_label = Qt.QLabel()
        slow_label.setText('slow')
        fast_label.setText('fast')
        frame_rate_layout.addWidget(title)
        frame_rate_layout.addWidget(slow_label)
        frame_rate_layout.addWidget(slider)
        frame_rate_layout.addWidget(fast_label)
        frame_rate_layout.insertSpacing(1, 200)

        #Change referential
        ref_layout = QHBoxLayout()
        title_ref = Qt.QLabel()
        title_ref.setText('Referential: ')
        box2 = Qt.QComboBox()
        box2.addItem('World Coordinates')
        box2.addItem('Image referential')
        ref_layout.addWidget(title_ref)
        ref_layout.addWidget(box2)
        box2.setCurrentIndex(int(ref))

        #Set general vertical layout
        layout.addLayout(config_layout)
        layout.addLayout(frame_rate_layout)
        layout.addLayout(ref_layout)
        layout.addStretch(1)

        #Save and cancel buttons
        hlay = Qt.QHBoxLayout()
        layout.addLayout(hlay)
        ok = Qt.QPushButton('Save')
        hlay.addStretch(1)
        hlay.addWidget(ok)
        ok.clicked.connect(dialog.accept)
        ok.setDefault(True)
        cancel = Qt.QPushButton('Cancel')
        hlay.addWidget(cancel)
        cancel.clicked.connect(dialog.reject)
        hlay.addStretch(1)

        res = dialog.exec_()

        if res == Qt.QDialog.Accepted:
            new_config = box.currentText().lower()
            new_ref = box2.currentIndex()

            #Save Config parameters and reload images
            #when config and referential have changed
            Config().setViewerFramerate(slider.value())
            Config().setViewerConfig(new_config)
            Config().set_referential(new_ref)
            if new_config != config:
                self.anaviewer.changeConfig(new_config)
            if new_ref != ref:
                self.anaviewer.changeRef()
コード例 #20
0
        def write_state():
            state_file_name = '/tmp/state.json'
            with open(state_file_name, 'w') as f:
                json.dump(pipeline.pipeline_state(), f)
            print('Wrote', state_file_name)

        import sys
        from soma.qt_gui import qt_backend
        qt_backend.set_qt_backend(compatible_qt5=True)
        from soma.qt_gui.qt_backend import Qt
        from capsul.qt_gui.widgets import PipelineDeveloperView
        #from capsul.qt_gui.widgets import PipelineUserView
        from capsul.api import capsul_engine

        app = Qt.QApplication(sys.argv)
        # pipeline = capsul_engine().get_process_instance(MainTestPipeline)
        pipeline = MainTestPipeline()
        pipeline.on_trait_change(write_state, 'selection_changed')
        view1 = PipelineDeveloperView(pipeline,
                                      show_sub_pipelines=True,
                                      allow_open_controller=True)
        view1.add_embedded_subpipeline('switch_pipeline', scale=0.7)
        view1.add_embedded_subpipeline('way1_1', scale=0.4)
        view1.add_embedded_subpipeline('way2_1', scale=0.4)
        view1.show()
        #view2 = PipelineUserView(pipeline)
        #view2.show()
        app.exec_()
        del view1
        #del view2
コード例 #21
0
    def create_widget(parent,
                      control_name,
                      control_value,
                      trait,
                      label_class=None,
                      user_data=None):
        """ Method to create the file widget.

        Parameters
        ----------
        parent: QWidget (mandatory)
            the parent widget
        control_name: str (mandatory)
            the name of the control we want to create
        control_value: str (mandatory)
            the default control value
        trait: Tait (mandatory)
            the trait associated to the control
        label_class: Qt widget class (optional, default: None)
            the label widget will be an instance of this class. Its constructor
            will be called using 2 arguments: the label string and the parent
            widget.

        Returns
        -------
        out: 2-uplet
            a two element tuple of the form (control widget: QWidget with two
            elements, a QLineEdit in the 'path' parameter and a browse button
            in the 'browse' parameter, associated label: QLabel)
        """
        # Create the widget that will be used to select a file
        widget, label = FileControlWidget.create_widget(
            parent,
            control_name,
            control_value,
            trait,
            label_class=label_class,
            user_data=user_data)
        if user_data is None:
            user_data = {}
        widget.user_data = user_data  # regular File does not store data

        layout = widget.layout()

        project = user_data.get('project')
        scan_list = user_data.get('scan_list')
        connected_inputs = user_data.get('connected_inputs', set())

        def is_number(x):
            try:
                int(x)
                return True
            except ValueError:
                return False

        main_window = user_data.get('main_window')
        # files in a list don't get a Filter button.
        if project and scan_list and not trait.output \
                and control_name not in connected_inputs \
                and not is_number(control_name):
            # Create a browse button
            button = Qt.QPushButton("Filter", widget)
            button.setObjectName('filter_button')
            button.setStyleSheet('QPushButton#filter_button '
                                 '{padding: 2px 10px 2px 10px; margin: 0px;}')
            layout.addWidget(button)
            widget.filter_b = button

            # Set a callback on the browse button
            control_class = parent.get_control_class(trait)
            node_name = getattr(parent.controller, 'name', None)
            if node_name is None:
                node_name = parent.controller.__class__.__name__
            browse_hook = partial(control_class.filter_clicked,
                                  weak_proxy(widget), node_name, control_name)
            widget.filter_b.clicked.connect(browse_hook)

        return (widget, label)