def setup_ui(self):
        """ Construct the UI for the dialog.

        """
        tab_widget = QTabWidget()

        general_widget = QWidget()
        general_layout = QVBoxLayout()

        general_layout.addWidget(self.setup_general_server_group())
        general_widget.setLayout(general_layout)
        tab_widget.addTab(general_widget, 'General')

        advanced_widget = QWidget()
        advanced_layout = QVBoxLayout()

        warning_label = QLabel('Caution: Changing these settings can potentially break the application.')
        warning_label.setStyleSheet('QLabel { color: red; }')
        advanced_layout.addWidget(warning_label)

        advanced_layout.addWidget(self.setup_advanced_server_group())
        advanced_layout.addWidget(self.setup_advanced_storage_group())
        advanced_widget.setLayout(advanced_layout)
        tab_widget.addTab(advanced_widget, 'Advanced')

        layout = QVBoxLayout()
        layout.addWidget(tab_widget)
        self.setLayout(layout)
 def setup_gui(self):
     """Sets up a sample gui interface."""
     central_widget = QWidget(self)
     central_widget.setObjectName('central_widget')
     self.label = QLabel('Hello World')
     self.input_field = QLineEdit()
     change_button = QPushButton('Change text')
     close_button = QPushButton('close')
     quit_button = QPushButton('quit')
     central_layout = QVBoxLayout()
     button_layout = QHBoxLayout()
     central_layout.addWidget(self.label)
     central_layout.addWidget(self.input_field)
     # a separate layout to display buttons horizontal
     button_layout.addWidget(change_button)
     button_layout.addWidget(close_button)
     button_layout.addWidget(quit_button)
     central_layout.addLayout(button_layout)
     central_widget.setLayout(central_layout)
     self.setCentralWidget(central_widget)
     # create a system tray icon. Uncomment the second form, to have an
     # icon assigned, otherwise you will only be seeing an empty space in
     # system tray
     self.systemtrayicon = QSystemTrayIcon(self)
     self.systemtrayicon.show()
     # set a fancy icon
     self.systemtrayicon.setIcon(QIcon.fromTheme('help-browser'))
     change_button.clicked.connect(self.change_text)
     quit_button.clicked.connect(QApplication.instance().quit)
     close_button.clicked.connect(self.hide)
     # show main window, if the system tray icon was clicked
     self.systemtrayicon.activated.connect(self.icon_activated)
示例#3
0
    def __init__(self, fig):
        QDialog.__init__(self)
        self.fig = fig
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)
        top_widget = QWidget()
        bottom_widget = QWidget()
        main_layout.addWidget(top_widget)
        main_layout.addWidget(bottom_widget)
        top_layout = QHBoxLayout()
        bottom_layout = QHBoxLayout()
        top_widget.setLayout(top_layout)
        bottom_widget.setLayout(bottom_layout)

        self.atext = qHotField("annotation", unicode, "the_text")
        top_layout.addWidget(self.atext)
        self.segment_number = qHotField("Segment", int, 1)
        top_layout.addWidget(self.segment_number)
        qmy_button(top_layout, self.annotate_it, "annotate")
        self.over = qHotField("over", int, -70)
        bottom_layout.addWidget(self.over)
        self.up = qHotField('up', int, 30)
        bottom_layout.addWidget(self.up)
        qmy_button(bottom_layout, self.remove_annotations, "remove all")
        qmy_button(bottom_layout, self.remove_last_annotation, "remove last")
        self.annotations = []
示例#4
0
def qbutton_with_arguments(parent, todo, button_display_text, argument_list):
    cWidget = QWidget()
    parent.addWidget(cWidget)
    cWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    cWidget.setContentsMargins(1, 1, 1, 1)
    newframe = QHBoxLayout()
    cWidget.setLayout(newframe)
    newframe.setSpacing(1)
    newframe.setContentsMargins(1, 1, 1, 1)
    qmy_button(newframe, todo, button_display_text)
    for entry in argument_list:
        # entry[0] is the variable, entry[1] is the text to display
        if len(entry) == 2:
            qe = qlabeled_entry(entry[0], entry[1], "top")
            qe.efield.returnPressed.connect(todo)
            
            var_val = entry[0].get()
            if type(var_val) == int:
                qe.efield.setText(str(var_val))
                qe.efield.setMaximumWidth(50)
            else:
                qe.efield.setText(var_val)
                qe.efield.setMaximumWidth(100)
            
            newframe.addWidget(qe)
        else:
            qp = aLabeledPopup(entry[0], entry[1], entry[2], "top")
            newframe.addWidget(qp)
    return
示例#5
0
    def _setup_ui(self):
        self._btn_pick_1.setFixedWidth(25)
        self._btn_pick_1.setToolTip('Pick first sequence.')
        self._btn_pick_2.setFixedWidth(25)
        self._btn_pick_2.setToolTip('Pick second sequence.')
        self._btn_compare.setToolTip('Compare sequences.')
        self._progress_bar.setFixedHeight(10)

        lyt_seq1 = QHBoxLayout()
        lyt_seq1.addWidget(self._ledit1)
        lyt_seq1.addWidget(self._btn_pick_1)

        lyt_seq2 = QHBoxLayout()
        lyt_seq2.addWidget(self._ledit2)
        lyt_seq2.addWidget(self._btn_pick_2)

        lyt_main = QVBoxLayout()
        lyt_main.addLayout(lyt_seq1)
        lyt_main.addLayout(lyt_seq2)
        lyt_main.addWidget(self._btn_compare)

        main_widget = QWidget()
        main_widget.setLayout(lyt_main)

        self.setCentralWidget(main_widget)
示例#6
0
 def make_central_widget(self, labelText):
     self.label = QLabel(labelText)
     mainLayout =  QVBoxLayout()
     mainLayout.addWidget(self.label)
     w = QWidget()
     w.setLayout(mainLayout)
     self.setCentralWidget(w)
示例#7
0
文件: gui.py 项目: caomw/ecto
 def generate_dialogs(self):
     vlayout = QVBoxLayout()
     commit_button = QPushButton("&Commit")
     w_all = QWidget()
     v = QVBoxLayout()
     for cell in self.plasm.cells():
         tendril_widgets = []
         for name, tendril in cell.params:
             if self.whitelist is None or self.is_in_whitelist(cell.name(), name):
                 tw = TendrilWidget(name, tendril)
                 commit_button.clicked.connect(tw.thunker.commit)
                 tendril_widgets.append(tw)
         if tendril_widgets:
             w = QWidget()
             cvlayout = QVBoxLayout()
             cvlayout.addWidget(QLabel(cell.name()))
             for tendril_widget in tendril_widgets:
                 cvlayout.addWidget(tendril_widget)
             w.setLayout(cvlayout)
             # w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
             v.addWidget(w)
     w_all.setLayout(v)
     s = QScrollArea()
     s.setWidget(w_all)
     vlayout.addWidget(s)
     vlayout.addWidget(commit_button)
     self.setLayout(vlayout)
示例#8
0
    def __init__(self):
        super(MainWindow, self).__init__()

        widget = QWidget()
        self.setCentralWidget(widget)

        fileMenu = self.menuBar().addMenu("File")
        newRepository = fileMenu.addAction("New Repository")
        openRepository = fileMenu.addAction("Open Repository")
        rollbackRepository = fileMenu.addAction("Discard last commit")

        newRepository.triggered.connect(self.create_new_repository)
        openRepository.triggered.connect(self.open_repository)
        rollbackRepository.triggered.connect(self.discard_last_commit)

        self.button = QPushButton("hello there")

        container = QVBoxLayout()
        menuContainer = QHBoxLayout()
        topContainer = QHBoxLayout()
        bottomContainer = QHBoxLayout()
        self.console = Console(bottomContainer)
        self.tree = TreeView(topContainer)

        container.addLayout(menuContainer, 0)
        container.addLayout(topContainer, 5)
        container.addLayout(bottomContainer, 3)
        self.tabs = TabView(topContainer)

        widget.setLayout(container)
示例#9
0
 def create_spinbox(self, prefix, suffix, option, default=NoDefault,
                    min_=None, max_=None, step=None, tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[option] = spinbox
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
示例#10
0
 def __init__(self):
     super(STMainWindow, self).__init__()
     self.createActions()
     self.createMenus()
     layout = QVBoxLayout()
     self.tabs = QTabWidget()
     self.tabs.setTabPosition(QTabWidget.West)
     self.tabs.currentChanged[int].connect(self.tabChanged)
     self.sessiontab = sweattrails.qt.sessiontab.SessionTab(self)
     self.tabs.addTab(self.sessiontab, "Sessions")
     self.tabs.addTab(sweattrails.qt.fitnesstab.FitnessTab(self),
                      "Fitness")
     self.tabs.addTab(sweattrails.qt.profiletab.ProfileTab(self),
                      "Profile")
     self.usertab = sweattrails.qt.usertab.UserTab(self)
     self.tabs.addTab(self.usertab, "Users")
     self.usertab.hide()
     layout.addWidget(self.tabs)
     w = QWidget(self)
     w.setLayout(layout)
     self.setCentralWidget(w)
     self.statusmessage = QLabel()
     self.statusmessage.setMinimumWidth(200)
     self.statusBar().addPermanentWidget(self.statusmessage)
     self.progressbar = QProgressBar()
     self.progressbar.setMinimumWidth(100)
     self.progressbar.setMinimum(0)
     self.progressbar.setMaximum(100)
     self.statusBar().addPermanentWidget(self.progressbar)
     self.setWindowTitle("SweatTrails")
     self.setWindowIconText("SweatTrails")
     icon = QPixmap("image/sweatdrops.png")
     self.setWindowIcon(QIcon(icon))
     QCoreApplication.instance().refresh.connect(self.userSet)
class ColorWidget(QWidget):
	"""
	ColorWidget
	"""

	valueChanged = Signal(object)

	def __init__(self):
		super(ColorWidget, self).__init__()

		self.label = QLabel()
		self.color = [1.0, 1.0, 1.0]
		
		buttonLayout = QHBoxLayout()
		buttonLayout.setContentsMargins(8, 0, 0, 0)

		self.buttonWidget = QWidget()
		self.buttonWidget.setLayout(buttonLayout)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.buttonWidget, 0, 1)
		self.setLayout(layout)

	def setName(self, name):
		self.label.setText(name)
示例#12
0
    def buildColorStepsControl(self):
        """Builds the portion of this widget for color cycling options."""
        widget = QWidget()
        layout = QHBoxLayout()

        self.stepBox = QCheckBox(self.color_step_label)
        self.stepBox.stateChanged.connect(self.colorstepsChange)

        self.stepEdit = QLineEdit("8", self)
        # Setting max to sys.maxint in the validator causes an overflow! D:
        self.stepEdit.setValidator(QIntValidator(1, 65536, self.stepEdit))
        self.stepEdit.setEnabled(False)
        self.stepEdit.editingFinished.connect(self.colorstepsChange)

        if self.color_step > 0:
            self.stepBox.setCheckState(Qt.Checked)
            self.stepEdit.setEnabled(True)

        layout.addWidget(self.stepBox)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(QLabel("with"))
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.stepEdit)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(QLabel(self.number_steps_label))

        widget.setLayout(layout)
        return widget
示例#13
0
文件: accd.py 项目: Sugz/Python
    def __init__( self, parent ):
        QScrollArea.__init__(self, parent)

        self.setFrameShape(QScrollArea.NoFrame)
        self.setAutoFillBackground(False)
        self.setWidgetResizable(True)
        self.setMouseTracking(True)
        #self.verticalScrollBar().setMaximumWidth(10)

        widget = QWidget(self)

        # define custom properties
        self._rolloutStyle = AccordionWidget.Rounded
        self._dragDropMode = AccordionWidget.NoDragDrop
        self._scrolling = False
        self._scrollInitY = 0
        self._scrollInitVal = 0
        self._itemClass = AccordionItem

        layout = QVBoxLayout()
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(2)
        layout.addStretch(1)

        widget.setLayout(layout)

        self.setWidget(widget)
示例#14
0
	def __init__(self,args,continuous):
		self.continuous = continuous
		gobject.GObject.__init__(self)
		#start by making our app
		self.app = QApplication(args)
		#make a window
		self.window = QMainWindow()
		#give the window a name
		self.window.setWindowTitle("BlatherQt")
		self.window.setMaximumSize(400,200)
		center = QWidget()
		self.window.setCentralWidget(center)

		layout = QVBoxLayout()
		center.setLayout(layout)
		#make a listen/stop button
		self.lsbutton = QPushButton("Listen")
		layout.addWidget(self.lsbutton)
		#make a continuous button
		self.ccheckbox = QCheckBox("Continuous Listen")
		layout.addWidget(self.ccheckbox)

		#connect the buttons
		self.lsbutton.clicked.connect(self.lsbutton_clicked)
		self.ccheckbox.clicked.connect(self.ccheckbox_clicked)

		#add a label to the UI to display the last command
		self.label = QLabel()
		layout.addWidget(self.label)

		#add the actions for quiting
		quit_action = QAction(self.window)
		quit_action.setShortcut('Ctrl+Q')
		quit_action.triggered.connect(self.accel_quit)
		self.window.addAction(quit_action)
示例#15
0
    def _set_layout ( self, adapter ):
        # If we did not receive a GUI toolkit neutral layout manager, convert
        # it to an adapted one (or None):
        if not isinstance( adapter, QtLayout ):
            adapter = adapted_layout( adapter )

        cur_layout = self.layout
        if cur_layout is None:
            if adapter is not None:
                self.control.setLayout( adapter() )

            return

        cur_layout = cur_layout()
        if (adapter is None) or (adapter.layout is not cur_layout):
            # According to the Qt docs, you have to 'delete' the existing
            # layout to remove it, but I don't know how to do a C++ 'delete'
            # from Python. So we instead delete all items from the current
            # layout as the next best thing, and then add the specified layout
            # manager (if any) to the original layout manager:
            while cur_layout.takeAt( 0 ) is not None: pass

            if adapter is not None:
                widget = cur_layout.parentWidget()
                if isinstance( widget, QMainWindow ):
                    layout = adapter()
                    ### PYSIDE: layout.setMargin( 0 )
                    panel = QWidget()
                    panel.setLayout( layout )
                    widget.setCentralWidget( panel )
                else:
                    cur_layout.addItem( adapter() )
示例#16
0
    def setup_ui(self):
        """ Setup the UI for the window.

        """
        central_widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.clock_view)
        layout.addWidget(self.message_view)
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        menubar = self.menuBar()

        file_menu = QMenu('File')

        preferences_action = QAction('Preferences', file_menu)
        preferences_action.triggered.connect(self.on_preferences_triggered)

        quit_action = QAction('Quit', file_menu)
        quit_action.triggered.connect(self.on_quit_triggered)

        file_menu.addAction(preferences_action)
        file_menu.addAction(quit_action)
        menubar.addMenu(file_menu)

        view_menu = QMenu('View')

        fullscreen_action = QAction('Fullscreen', view_menu)
        fullscreen_action.setCheckable(True)
        fullscreen_action.setChecked(Config.get('FULLSCREEN', True))
        fullscreen_action.setShortcut('Ctrl+Meta+F')
        fullscreen_action.toggled.connect(self.on_fullscreen_changed)

        view_menu.addAction(fullscreen_action)
        menubar.addMenu(view_menu)
    def __init__(self, parent,silhouette,completeness,homogeneity,v_score,AMI,ARS):
        QDialog.__init__( self, parent )
        layout = QVBoxLayout()

        viewLayout = QFormLayout()
        viewLayout.addRow(QLabel('Silhouette score: '),QLabel(silhouette))
        viewLayout.addRow(QLabel('Completeness: '),QLabel(completeness))
        viewLayout.addRow(QLabel('Homogeneity: '),QLabel(homogeneity))
        viewLayout.addRow(QLabel('V score: '),QLabel(v_score))
        viewLayout.addRow(QLabel('Adjusted mutual information: '),QLabel(AMI))
        viewLayout.addRow(QLabel('Adjusted Rand score: '),QLabel(ARS))

        viewWidget = QGroupBox()
        viewWidget.setLayout(viewLayout)

        layout.addWidget(viewWidget)

        #Accept cancel
        self.acceptButton = QPushButton('Ok')
        self.cancelButton = QPushButton('Cancel')

        self.acceptButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

        hbox = QHBoxLayout()
        hbox.addWidget(self.acceptButton)
        hbox.addWidget(self.cancelButton)
        ac = QWidget()
        ac.setLayout(hbox)
        layout.addWidget(ac)
        self.setLayout(layout)
示例#18
0
        def createLayout():
            label = QLabel()
            layout = QHBoxLayout()
            layout.addWidget(label)

            widget = QWidget()
            widget.setLayout(layout)
            return (layout, widget)
 def visual_proxy(self, read_only=False):
     view = QWidget()
     layout = QGridLayout()
     for row, attr in enumerate(["name", "surname", "age"]):
         layout.addWidget(QLabel(attr), row, 0)
         layout.addWidget(self.visual_proxy_attribute(attr, read_only), row, 1)
     view.setLayout(layout)
     return view
示例#20
0
    def edit_cell ( self, parent, row, column ):
        """ Returns the editor widget to use for editing a specified cell's
            value.
        """
        self.cell_row = self.data_row_for( row )

        # Get the editor factory to use. If none, exit (read-only cell):
        editor_factory = self.grid_adapter.get_editor( self.cell_row, column )
        if editor_factory is None:
            return None

        # Create the requested type of editor from the editor factory:
        # Note: We save the editor reference so that the editor doesn't get
        # garbage collected too soon.
        self.cell_column = column
        object, name     = self.grid_adapter.get_alias(  self.cell_row, column )
        editor           = editor_factory.simple_editor(
                               self.ui, object, name, '' ).set(
                               item        = self.item,
                               object_name = '' )

        # Tell the editor to actually build the editing widget:
        editor.prepare( control_adapter( parent ) )

        # Make sure that the editor is a control (and not a layout):
        self._editor = editor
        control      = editor.control
        if not isinstance( control, QWidget ):
            layout  = control
            control = QWidget( parent )
            control.setLayout( layout )
            layout.setContentsMargins( 5, 0, 5, 0 )

        control._editor = editor

        # Adjust the row height of the grid row to fit the editor control:
        height = control.height()
        if height > self.height:
            if (self.height - height) <= 4:
                # If the difference is not too great, then we will just adjust
                # the grid height to accomodate it:
                self.row_height( height )
            else:
                # Otherwise, just adjust the height of this row temporarily:
                control._row = row
                self.control.verticalHeader().resizeSection( row, height )

        # Resize the grid column width to fit the editor if necessary:
        width        = control.width()
        header       = self.control.horizontalHeader()
        column_width = header.sectionSize( column )
        if width > column_width:
            control._column = column
            control._width  = column_width
            header.resizeSection( column, width )

        # Return the editing widget as the result:
        return control
示例#21
0
    def testMoveLayout(self):
        l = QHBoxLayout()
        self.assertEqual(getrefcount(self.widget1), 2)
        l.addWidget(self.widget1)
        self.assertEqual(getrefcount(self.widget1), 3)

        w = QWidget()
        w.setLayout(l)
        self.assertEqual(getrefcount(self.widget1), 3)
示例#22
0
 def show_page(self, page):
     print 'page is ' + page.item.name
     widget = QWidget()
     
     layout = QHBoxLayout()
     widget.setLayout(layout)
     
     pageWidget = pages.get_page_widget(page, layout, self)
     self.tabs.insertTab(0, widget, page.label)
     self.tabs.setCurrentIndex(0)
 def setupUi(self):
     centralWidget = QWidget(self)
     centralWidget.setLayout(QVBoxLayout(centralWidget))
     self.view = QTableView(centralWidget)
     self.view.setSortingEnabled(True)
     centralWidget.layout().addWidget(self.view)
     self.searchBox = QLineEdit(centralWidget)
     centralWidget.layout().addWidget(self.searchBox)
     self.setCentralWidget(centralWidget)
     self.searchBox.setFocus()
示例#24
0
文件: FilterBox.py 项目: LLNL/boxfish
    def createView(self):
        """Creates the module-specific view for the FilterBox module."""
        view = QWidget()

        layout = QGridLayout()
        self.filter_label = QLabel("")
        layout.addWidget(self.filter_label, 0, 0, 1, 1)
        view.setLayout(layout)
        view.resize(20, 20)
        return view
示例#25
0
文件: cli.py 项目: srossross/jaded
    def visit_QCoreApplication(self, elem, cls, children):
        instance = cls.instance()
        widget = None
        for child in children:
            if isinstance(child, QLayout):
                widget = QWidget()
                widget.setLayout(child)
            else:
                raise NotImplementedError(child)

        return widget
示例#26
0
文件: FilterBox.py 项目: LLNL/boxfish
    def __init__(self, parent, mframe, existing_filters):
        """Create a FilterTab with the given parent TabDialog, logical
           parent ModuleFrame mframe, and existing_filters list of Clause
           objects.
        """
        super(FilterTab, self).__init__(parent)

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

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

        self.clause_model = QStringListModel(self.clause_list)

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

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

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

        layout.addWidget(self.sidesplitter)

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

        layout.addWidget(buttonWidget)
        self.setLayout(layout)
示例#27
0
 def __init__(self, qpframe):
     QVBoxLayout.__init__(self)
     scroll = QScrollArea()
     scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     scroll.setWidgetResizable(True)
     subWidget = QWidget()
     subWidget.setLayout(qpframe)
     scroll.setWidget(subWidget)
     self.addWidget(scroll)
     self.scroll = scroll
示例#28
0
 def setCanvas(self):
     ''' set widgets for a tab page
      - left side show image of current frame
      - right side show two plots: raw and rms
      - bot: button to edit triggers and slider to adjust 
             video-emg offset
     '''
     
     ########################
     # set matplotlib plots #
     ########################
     self.fig = Figure(dpi=70)
     self.canvas = FigureCanvas(self.fig)
     self.canvas.setParent(self.ui.mainFrame)
     self.axes = self.fig.add_subplot(211)
     self.axesRMS = self.fig.add_subplot(212)
     self.mpl_toolbar = NavigationToolbar2(self.canvas, self.ui.mainFrame)
     self.canvas.mpl_connect('draw_event', self.onDraw)
     
     ####################################
     # add button to matplotlib toolbar #
     #################################### 
     redb = QPushButton('Edit Triggers')
     redb.setCheckable(True)
     self.mpl_toolbar.addWidget(redb)
     redb.clicked[bool].connect(self.toggleEditMode)
     
     # container for current frame of video 
     layout = pq.GraphicsLayoutWidget()
     vb = layout.addViewBox()
     vb.setAspectLocked(True)
     
     self.ri = pq.ImageItem()
     vb.addItem(self.ri)
     
     # layout to organize elements
     grid = QGridLayout()
     wrapper = QWidget()        
     vbox = QVBoxLayout(wrapper)
     splitter = QSplitter()
     
     vbox.addWidget(self.canvas)
     vbox.addWidget(self.mpl_toolbar)
     wrapper.setLayout(vbox)
     
     splitter.addWidget(layout)
     splitter.addWidget(wrapper)
     
     grid.addWidget(splitter)
     
     self.ri.show()
     layout.show()
     self.ui.mainFrame.setLayout(grid)
	def getParameterWidget(self):
		"""
		Returns a widget with sliders / fields with which properties of this
		volume property can be adjusted.
		:rtype: QWidget
		"""
		layout = QGridLayout()
		layout.setAlignment(Qt.AlignTop)

		widget = QWidget()
		widget.setLayout(layout)
		return widget
示例#30
0
文件: FilterBox.py 项目: LLNL/boxfish
    def buildRelationsWidget(self):
        """Creates the set of draggable relations. These relations are
           whatever is available in the relations dict of Table.
        """
        relations_widget = QWidget()
        layout = QHBoxLayout(relations_widget)

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

        relations_widget.setLayout(layout)
        return relations_widget
示例#31
0
    def _set_widget_buttons(self, row):
        # mainlog.debug("_set_widget_buttons({})".format(row))

        doc = self.model.object_at(row)

        p_download = make_tool_button(
            "appbar.page.download.png",
            "download{}".format(self.button_id_counter))
        p_download.clicked.connect(self.signal_mapper_save_a_copy_button.map)
        self.signal_mapper_save_a_copy_button.setMapping(
            p_download, self.button_id_counter)

        # FIXME Json calls should produce rela objects and not tuples or Frozen,...
        has_reference = False
        try:
            has_reference = doc.reference
        except:
            pass

        # FIXME HAchkish this is really valid for templates, and not super-really-valid for mere documents
        if not has_reference:
            p_delete = make_tool_button("appbar.page.delete.png")
            p_delete.clicked.connect(self.signal_mapper_close_button.map)
            self.signal_mapper_close_button.setMapping(p_delete,
                                                       self.button_id_counter)

        # I've already tested several things here
        # use a qss style, setting strecth, borders, contentsmargins, etc.
        # But for some reasons, when I test the widget in a dialog
        # the space between buttons is wide. If I run the widget in Horse
        # (that is, in normal conditions) then the display works as exepcted
        # (buttons close together and not wide apart)

        z = QWidget()
        layout = QHBoxLayout()
        layout.setSpacing(0)
        # layout.setStretch(0,0)
        # layout.setStretch(1,0)
        layout.setContentsMargins(0, 0, 0, 0)
        # layout.addWidget(p_open)

        p_download.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(p_download)

        if not has_reference:
            p_delete.setContentsMargins(0, 0, 0, 0)
            layout.addWidget(p_delete)
        # z.setMinimumHeight(64)

        z.setLayout(layout)

        # QTableView takes ownership of the widget (see Qt doc.)
        self.view.setIndexWidget(
            self.model.index(row,
                             self.model.columnCount() - 1), z)

        #doc.button_id = self.button_id

        # A bit complicated, but that's the simplest way
        # to tie an in-table button to some data
        self.button_data[self.button_id_counter] = (doc.document_id)
        self.button_id_counter += 1
示例#32
0
    TextLinePrototype('fullname', _('Fullname'), editable=False)
]

filter = PersistentFilter(QueryLineEdit(), 'supply_orders_overview')
service = None


def apply_filter(f):
    if f == '12134':
        objects = service.findByCode(f)
        model.loadObjects(objects)
    else:
        objects = service.findByQueryString(f)
        model.loadObjects(objects)


filter.activated.connect(apply_filter)

model = PrototypedModelView(prototype, None)
list_view = PrototypedQuickView(prototype, None)
detail_view = None

layout = hlayout(SubFrame("Stock items", vlayout(filter, list_view), None),
                 SubFrame("Details", detail_view, None))

w = QWidget()
w.setLayout(l)
w.show()

app.exec_()
示例#33
0
class CfdBoundaryWidget(QWidget):
    """ QWidget for adding fluid boundary """
    def __init__(self,
                 object,
                 boundarySettings,
                 physics_model,
                 material_objs,
                 parent=None):
        super(CfdBoundaryWidget, self).__init__(parent)  # for both py2 and py3

        #todo: add title to the task paenl
        self.obj = object
        if self.obj:
            self.BoundarySettings = self.obj.BoundarySettings
        else:  # None, if it is not used in FreeCADGui mode
            self.BoundarySettings = boundarySettings
        # todo
        thermalSettings = {}
        turbulenceSettings = {}

        if within_FreeCADGui:
            self.physics_model = physics_model  # approx solver_object, but slightly different
            if 'Turbulence' not in self.obj.PropertiesList:  # Qingfeng Xia's Cfd module
                self.turbModel = 'kOmegaSST'  # physics_model.TurbulenceModel
            else:  # CfdOF fork
                self.turbModel = (physics_model.TurbulenceModel
                                  if physics_model.Turbulence == 'RANS' or
                                  physics_model.Turbulence == 'LES' else None)

            # compatibility workaround
            if 'Thermal' in self.physics_model.PropertiesList:
                self.hasHeatTransfer = self.physics_model.Thermal != 'None'
            else:  # Qingfeng's Cfd
                if 'HeatTransfering' in self.physics_model.PropertiesList:
                    self.hasHeatTransfer = self.physics_model.HeatTransfering
                else:
                    self.hasHeatTransfer = True

        self.material_objs = material_objs  # volume faction of multiphase flow, should accept None
        """
        ui_path = os.path.join(os.path.dirname(__file__), "TaskPanelCfdFluidBoundary.ui")
        ui_path = os.path.join(os.path.dirname(__file__), "TaskPanelFemConstraintFluidBoundary.ui")
        #self.form = QtUiTools.QUiLoader().load(ui_path)
        self.form = FreeCADGui.PySideUic.loadUi(ui_path)
        """

        self.comboBoundaryType = QComboBox()
        self.comboSubtype = QComboBox()
        self.form = self

        _layout = QVBoxLayout()
        _layout.addWidget(self.comboBoundaryType)
        _layout.addWidget(self.comboSubtype)
        self.labelHelpText = QLabel(
            self.tr('select a proper subtype and input a value'), self)
        self.labelHelpText.setWordWrap(True)
        _layout.addWidget(self.labelHelpText)

        self.tabWidget = QTabWidget()
        self.tabBasicBoundary = QWidget()
        self.tabWidget.addTab(self.tabBasicBoundary, "Basic")
        self.tabTurbulenceBoundary = InputWidget(turbulenceSettings,
                                                 TURBULENCE_CONFIG)
        self.tabWidget.addTab(self.tabTurbulenceBoundary, "Turbulence")
        self.tabThermalBoundary = InputWidget(thermalSettings, THERMAL_CONFIG)
        self.tabWidget.addTab(self.tabThermalBoundary, "Thermal")

        # these 2 are value widgets
        _valueLayout = QHBoxLayout()
        self.inputBoundaryValue = _createInputField()
        self.labelBoundaryValue = QLabel()
        _valueLayout.addWidget(self.labelBoundaryValue)
        _valueLayout.addWidget(self.inputBoundaryValue)
        self.vectorInputWidget = VectorInputWidget([0, 0, 0], self.obj)
        _widgetLayout = QVBoxLayout()
        _widgetLayout.addLayout(_valueLayout)
        _widgetLayout.addWidget(self.vectorInputWidget)
        self.tabBasicBoundary.setLayout(_widgetLayout)

        _layout.addWidget(self.tabWidget)
        self.setLayout(_layout)

        self.form.comboBoundaryType.currentIndexChanged.connect(
            self.comboBoundaryTypeChanged)
        self.form.comboSubtype.currentIndexChanged.connect(
            self.comboSubtypeChanged)

        self.setBoundarySettings(self.BoundarySettings)

    def _getCurrentValueUnit(self):
        bType = BOUNDARY_TYPES[self.form.comboBoundaryType.currentIndex()]
        si = self.form.comboSubtype.currentIndex()
        return SUBTYPE_UNITS[bType][si]

    def boundarySettings(self):
        self.onValueChange(
        )  # currently value change signal has no slot connected
        bc = self.BoundarySettings.copy()
        return bc

    def onValueChange(self):
        if not self.vectorInputWidget.isVisible():
            self.BoundarySettings['BoundaryValue'] = _getInputField(
                self.inputBoundaryValue, self.BoundarySettings['Unit'])
        else:
            self.BoundarySettings[
                'BoundaryValue'] = self.vectorInputWidget.vector()

    def setBoundarySettings(self, settings):
        """ Populate UI, update view from settings"""
        self.form.comboBoundaryType.addItems(BOUNDARY_NAMES)
        _boundaryType = settings['BoundaryType']
        bi = indexOrDefault(BOUNDARY_TYPES, _boundaryType, 0)
        self.form.comboBoundaryType.setCurrentIndex(bi)

        si = indexOrDefault(SUBTYPES[_boundaryType],
                            settings['BoundarySubtype'], 0)
        self.form.comboSubtype.setCurrentIndex(si)

        if 'BoundaryValue' in settings:
            if not hasattr(
                    settings['BoundaryValue'], "__len__"
            ):  # support numpy.array, array, list, tuple, but also string
                self.inputBoundaryValue.setValue(settings['BoundaryValue'])
        else:
            if 'ValueVector' in settings:  # DirectionVector + BoundaryValue
                self.vectorInputWidget.setVector(settings['ValueVector'])
            else:
                self.vectorInputWidget.setVector(settings['BoundaryValue'])

        self.updateValueUi()

    def updateValueUi(self):
        # set value label and unit
        self.labelBoundaryValue.setVisible(False)
        self.inputBoundaryValue.setVisible(False)
        self.vectorInputWidget.setVisible(False)
        unit = self._getCurrentValueUnit()
        bType = BOUNDARY_TYPES[self.form.comboBoundaryType.currentIndex()]
        si = self.form.comboSubtype.currentIndex()
        unit = SUBTYPE_UNITS[bType][si]
        valueName = SUBTYPE_VALUE_NAMES[bType][si]
        if unit == '':
            pass
        elif unit == 'm/s':
            self.vectorInputWidget.setVisible(True)
        else:  # any scalar
            self.labelBoundaryValue.setText("{} [{}]".format(valueName, unit))
            self.inputBoundaryValue.setVisible(True)

    def comboBoundaryTypeChanged(self):
        index = self.form.comboBoundaryType.currentIndex()
        _bType = BOUNDARY_TYPES[index]
        self.form.comboSubtype.clear()
        self.form.comboSubtype.addItems(SUBTYPE_NAMES[_bType])
        self.form.comboSubtype.setCurrentIndex(0)
        self.BoundarySettings['BoundaryType'] = _bType

        if self.obj:
            # Change the color of the boundary condition as the selection is made
            self.obj.BoundarySettings = self.BoundarySettings.copy()
            doc_name = str(self.obj.Document.Name)
            FreeCAD.getDocument(doc_name).recompute()

    def comboSubtypeChanged(self):
        index = self.form.comboBoundaryType.currentIndex()
        _bType = BOUNDARY_TYPES[index]
        subtype_index = self.form.comboSubtype.currentIndex()
        self.form.labelHelpText.setText(
            SUBTYPES_HELPTEXTS[_bType][subtype_index])
        self.BoundarySettings['BoundarySubtype'] = SUBTYPES[_bType][
            subtype_index]
        self.BoundarySettings['Unit'] = self._getCurrentValueUnit()
        #self.BoundarySettings['QuantityName'] = SUBTYPE_NAMES[_bType][subtype_index]
        self.updateValueUi()
示例#34
0
class ModuleFrame(QMainWindow):
    """This is the parent of what we will think of as a
       agent/extension/plug-in. It has the interface to create the single
       ModuleAgent it represents as well as the GUI elements to handle its
       specific actions. Both need to be written by the inheriting object.

       This class handles the reparenting and docking elements of all such
       modules.
    """

    droppedDataSignal = Signal(list, str)

    def __init__(self, parent, parent_frame, title=None):
        """Construct a ModuleFrame.

           parent
               The GUI parent of this window as necessary for Qt

           parent_frame
               The ModuleFrame that is the logical parent to this one.
        """
        super(ModuleFrame, self).__init__(parent)

        self.title = title
        self.parent_frame = parent_frame
        self.agent = None

        # Only realize if we have a parent and a parent frame
        if self.parent_frame is not None and self.parent() is not None:
            self.realize()

        self.acceptDocks = False  # Set to True to have child windows
        self.dragOverlay = False  # For having a drag overlay window
        self.overlay_dialog = None

        self.setAcceptDrops(True)
        self.setWindowFlags(Qt.Widget)  # Or else it will try to be a window

        # Makes color bar flush with top
        left, top, right, bottom = self.layout().getContentsMargins()
        self.layout().setContentsMargins(0, 0, right, bottom)

        # If we have a parent, set the height hint to be tall
        self.heightHint = self.size().height()
        if self.parent_frame is not None:
            self.heightHint = self.parent_frame.height() - 20

        self.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, \
            QSizePolicy.Preferred))

        # Yellow Boxfishy border
        self.setStyleSheet("QMainWindow::separator { background:"\
            + "rgb(240, 240, 120); width: 2px; height: 2px; }")

    def realize(self):
        """This function is part of initialization where it handles
           ModuleAgent creation and wiring and subclass view placement.
        """
        # Create and wire the Agent into the Boxfish tree
        self.agent = self.agent_type(self.parent_frame.agent,
                                     self.parent_frame.agent.datatree)
        self.agent.module_scene = self.scene_type(self.agent_type,
                                                  self.display_name)
        self.parent_frame.agent.registerChild(self.agent)

        # Create and place the module-specific view elements
        self.view = self.createView()
        self.centralWidget = QWidget()

        layout = QGridLayout()
        if isinstance(self.parent(), BFDockWidget):
            layout.addWidget(DragDockLabel(self.parent()), 0, 0, 1, 2)

        # TODO: Replace magic number with not-magic constant
        layout.addWidget(self.view, 100, 0, 1, 2)  # Add view at bottom
        layout.setRowStretch(100, 5)  # view has most row stretch

        left, top, right, bottom = layout.getContentsMargins()
        layout.setContentsMargins(0, 0, 0, 0)
        self.centralWidget.setLayout(layout)

        self.setCentralWidget(self.centralWidget)

        # Tab Dialog stuff
        self.enable_tab_dialog = True
        self.dialog = list()

    def createView(self):
        """This function should be re-implemented to create and return
           the subclass-specific view/GUI as a single widget. This widget
           will then be placed in the overstructure of the ModelView
           GUI elements.
        """
        raise NotImplementedError("Realize not implemented,"\
            + " cannot create view")

    @classmethod
    def instantiate(cls, module_name, parent, parent_frame, title=None):
        """Creates a module and inserts it into the Boxfish tree.

           module_name
               The display name of the module used to determine the
               specific type of ModuleFrame/ModuleAgent to create.

           parent
               The GUI parent of the module to be created.

           parent_frame
               The ModuleFrame that is the logical parent to the one we
               are creating.
        """
        if hasattr(cls, 'display_name') and cls.display_name == module_name:
            return cls(parent, parent_frame, title)
        else:
            for s in cls.__subclasses__():
                result = s.instantiate(module_name, parent, parent_frame,
                                       title)
                if result is not None:
                    return result
            return None

    @classmethod
    def subclassList(cls, scList=None):
        """Creates a list of modules we can create.
        """
        if scList is None:
            scList = list()
        if hasattr(cls, 'display_name'):
            scList.append(cls.display_name)
        for s in cls.__subclasses__():
            scList.extend(s.subclassList())
        return scList

    def sizeHint(self):
        """Overrides the QWidget method so the initial size of this
           module is sane.
        """
        return QSize(200, self.heightHint)  # TODO: figure out better values
        #return QSize(self.size().width(), self.heightHint)

    def findPosition(self):
        """This finds the absolute position of this particular module
           in screen coordinates.
        """
        if isinstance(self.parent(), BFDockWidget):
            # parent is a dockwidget, so coords are relative
            x, y = self.parent().findPosition()
            return x + self.x(), y + self.y()
        else:  # parent_frame is boxfish main, get absolute coords
            return self.parent_frame.geometry().x() + self.x(),\
                self.parent_frame.geometry().y() + self.y()

    def allowDocks(self, dockable):
        """Sets whether or not the module will accept other modules as
           children.
        """
        self.acceptDocks = dockable

    def createDragOverlay(self, tags, texts, images=None):
        """Creates a DragOverlay for this ModuleFrame with the given
           text and optional images. When DataIndexMimes (DataTree indices)
           are dropped on the text/images of this overlay, they are
           associated with the tag of the same index of the text/image.

           This is a user interface for when a ModuleFrame wants to
           accept drops for multiple purposes.
        """
        self.dragOverlay = True

        self.overlay = OverlayFrame(self)

        layout = QGridLayout(self.overlay)
        layout.setAlignment(Qt.AlignCenter)
        layout.setColumnStretch(0, 5)
        if images is not None:
            for i, tag, text, image in zip(range(len(tags)), tags, texts,
                                           images):
                layout.addWidget(
                    DropPanel(tag, text, self.overlay, self.overlayDroppedData,
                              image), i, 0, 1, 1)
                layout.setRowStretch(i, 5)
        else:
            for i, tag, text in zip(range(len(tags)), tags, texts):
                layout.addWidget(
                    DropPanel(tag, text, self.overlay,
                              self.overlayDroppedData), i, 0, 1, 1)
                layout.setRowStretch(i, 5)

        # Add a Close button to deal with lack of cancel signal
        # for drag/drop
        class CloseLabel(QLabel):

            closeSignal = Signal()

            def __init__(self):
                super(CloseLabel, self).__init__("Close")

                self.setStyleSheet("QLabel { color : white; }")

            def mousePressEvent(self, e):
                self.closeSignal.emit()

        closeButton = CloseLabel()
        closeButton.closeSignal.connect(self.killRogueOverlays)
        layout.addWidget(closeButton, len(tags), 0, 1, 1)
        layout.setRowStretch(len(tags), 0)

        self.overlay.setLayout(layout)

    def killRogueOverlays(self):
        """Sometimes an overlay doesn't close on dragEventLeave.
           This kills any such overlays and is called when someone
           else takes that drop event.
        """
        self.closeOverlay()
        if self.acceptDocks:
            childDocks = self.findChildren(BFDockWidget)
            for dock in childDocks:
                dock.widget().killRogueOverlays()

    def propagateKillRogueOverlayMessage(self):
        """Propagate the message to kill rogue overlays to the
           top of the Boxfish module hierarchy.
        """
        #TODO: Need to also do this when drag operation is aborted
        # (back to the tree view). This is currently unknown
        if isinstance(self.parent(), BFDockWidget):
            self.parent_frame.propagateKillRogueOverlayMessage()
        else:
            self.killRogueOverlays()

    def closeOverlay(self):
        """Close the DragOverlay for this ModuleFrame."""
        if self.overlay_dialog is not None:
            self.overlay_dialog.close()
            self.overlay_dialog = None
            self.overlay.setVisible(False)

    def overlayDroppedData(self, indexList, tag):
        """Called when indexList is dropped on the DragOverlay on widgets
           associated with tag. Handles closing the DragOverlay and
           passing the parameters through the droppedDataSignal.
        """
        self.closeOverlay()
        self.propagateKillRogueOverlayMessage()
        self.droppedDataSignal.emit(indexList, tag)

    def dragLeaveEvent(self, event):
        """Close any DragOverlays when the drag leaves this widget."""
        self.closeOverlay()

    # We only accept events that are of our type, indicating
    # a dock window change
    def dragEnterEvent(self, event):
        """Accept dragged DataTree indices and optionally dragged
           Modules.
        """
        if self.acceptDocks and isinstance(event.mimeData(), ModuleFrameMime):
            event.accept()
        elif isinstance(event.mimeData(), DataIndexMime):
            if self.dragOverlay and self.overlay_dialog is None:
                self.overlay.setVisible(True)
                self.overlay_dialog = OverlayDialog(self, self.overlay)
                self.overlay_dialog.show()
            else:
                event.accept()
        elif self.acceptDocks and isinstance(event.mimeData(), ModuleNameMime):
            event.accept()
        else:
            super(ModuleFrame, self).dragEnterEvent(event)

    # If the event has a DockWidget in it, we check if it is our
    # parent or if we are its widget. If so, do nothing
    # If not, we add it to our dock and change its parent to us
    def dropEvent(self, event):
        """Accepts dragged DataTree indices and optionally dragged
           modules. When a module is dropped (already existing or from
           its name), this handles any creation and parenting needed.
           When indices are dropped, they are passed to droppData unless
           a DragOverlay is present in which case they are ignored.
        """
        # Dropped DockWidget
        if self.acceptDocks and isinstance(event.mimeData(), ModuleFrameMime):
            if event.mimeData().getDockWindow().parent() != self and \
               event.mimeData().getDockWindow().widget() != self:
                self.addDockWidget(Qt.BottomDockWidgetArea, \
                    event.mimeData().getDockWindow())
                event.mimeData().getDockWindow().widget().agent.changeParent(
                    self.agent)
                event.mimeData().getDockWindow().widget().parent_frame = self
                event.mimeData().getDockWindow().changeParent(self)
                event.mimeData().getDockWindow().widget(
                ).agent.refreshSceneInformation()
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
        # Dropped Module Name
        elif self.acceptDocks and isinstance(event.mimeData(), ModuleNameMime):
            mod_name = event.mimeData().getName()
            dock = BFDockWidget(mod_name, self)
            new_mod = ModuleFrame.instantiate(mod_name, dock, self, mod_name)
            new_mod.agent.refreshSceneInformation()
            dock.setWidget(new_mod)
            self.addDockWidget(Qt.BottomDockWidgetArea, dock)
        # Dropped Attribute Data
        elif isinstance(event.mimeData(), DataIndexMime) \
            and not self.dragOverlay:
            # Note, because Qt will let drops fall through if unhandled,
            # we need to check if there's a DragOverlay and ignore if
            # there is.
            indexList = event.mimeData().getDataIndices()
            event.accept()
            self.propagateKillRogueOverlayMessage()
            self.droppedDataSignal.emit(indexList, None)
        else:
            self.propagateKillRogueOverlayMessage()
            super(ModuleFrame, self).dropEvent(event)

    def buildTabDialog(self):
        """Create the TabDialog associated with this ModuleFrame and
           add associated Tabs to it.

           Subclasses adding other Tabs should override this function
           and call super in order to get the Tabs associated with all
           ModuleFrames. Then the Subclasses may construct their own Tabs.
        """
        self.tab_dialog = TabDialog(self)
        self.tab_dialog.addTab(SceneTab(self.tab_dialog, self.agent),
                               "Scene Policy")

    def mouseDoubleClickEvent(self, event):
        """Double-clicking launches the TabDialog if enabled in this
           module. Note that if you disable the TabDialog, the user
           won't have the ability to change the propagation effects
           of the Scene information, so the defaults for that module's
           Agent must be chosen wisely.

           Note this action constructs the TabDialog anew each time.
           This means the Tabs may also be re-created, allowing them
           to be passed the most current values from the ModuleFrame
           and ModuleAgent rather than having to keep the Tabs in
           synch at all times.
        """
        if self.enable_tab_dialog:
            self.buildTabDialog()
            self.tab_dialog.exec_()
    def createElements(self):
        """
		Creates the widgets and docks of which the
		main window is composed.
		"""
        self.mainWindow = QMainWindow()
        projectController = ProjectController.Instance()
        self.transformTool = None

        # Render widgets
        self.fixedDataWidget = RenderWidget()
        self.movingDataWidget = RenderWidget()
        self.multiDataWidget = MultiRenderWidget()

        self.fixedRenderController = RenderController(self.fixedDataWidget,
                                                      "fixed")
        self.movingRenderController = RenderController(self.movingDataWidget,
                                                       "moving")
        self.multiRenderController = MultiRenderController(
            self.multiDataWidget)

        # Give references of the render controllers to the project controller
        projectController.fixedRenderController = self.fixedRenderController
        projectController.movingRenderController = self.movingRenderController
        projectController.multiRenderController = self.multiRenderController

        # Render properties widgets
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)

        self.fixedPropWidget = RenderPropWidget(self.fixedRenderController,
                                                parent=self)
        self.fixedPropWidget.setSizePolicy(sizePolicy)
        self.fixedPropWidget.setFileChangedSignal(
            projectController.fixedFileChanged)
        self.fixedPropWidget.setLoadDataSlot(self.loadFixedDataSetFile)

        self.movingPropWidget = RenderPropWidget(self.movingRenderController,
                                                 parent=self)
        self.movingPropWidget.setSizePolicy(sizePolicy)
        self.movingPropWidget.setFileChangedSignal(
            projectController.movingFileChanged)
        self.movingPropWidget.setLoadDataSlot(self.loadMovingDataSetFile)

        self.multiPropWidget = MultiRenderPropWidget(
            self.multiRenderController, parent=self)
        self.multiPropWidget.setSizePolicy(sizePolicy)

        self.verticalSplitter = QSplitter()
        self.verticalSplitter.setOrientation(Qt.Vertical)

        # Create the layouts

        fixedDataTitleWidget = TitleWidget("Fixed volume")
        multiDataTitleWidget = TitleWidget("Fixed + Moving")
        movingDataTitleWidget = TitleWidget("Moving volume")

        fixedLayout = QGridLayout()
        fixedLayout.setSpacing(0)
        fixedLayout.setContentsMargins(0, 0, 0, 0)
        fixedLayout.addWidget(fixedDataTitleWidget)
        fixedLayout.addWidget(self.fixedDataWidget)
        fixedWidget = QWidget()
        fixedWidget.setLayout(fixedLayout)

        multiLayout = QGridLayout()
        multiLayout.setSpacing(0)
        multiLayout.setContentsMargins(0, 0, 0, 0)
        multiLayout.addWidget(multiDataTitleWidget)
        multiLayout.addWidget(self.multiDataWidget)
        multiWidget = QWidget()
        multiWidget.setLayout(multiLayout)

        movingLayout = QGridLayout()
        movingLayout.setSpacing(0)
        movingLayout.setContentsMargins(0, 0, 0, 0)
        movingLayout.addWidget(movingDataTitleWidget)
        movingLayout.addWidget(self.movingDataWidget)
        movingWidget = QWidget()
        movingWidget.setLayout(movingLayout)

        horizontalSplitter = QSplitter()
        horizontalSplitter.setOrientation(Qt.Horizontal)
        horizontalSplitter.addWidget(fixedWidget)
        horizontalSplitter.addWidget(multiWidget)
        horizontalSplitter.addWidget(movingWidget)

        propsLayout = QHBoxLayout()
        propsLayout.setSpacing(1)
        propsLayout.setContentsMargins(0, 0, 0, 0)
        propsLayout.addWidget(self.fixedPropWidget)
        propsLayout.addWidget(self.multiPropWidget)
        propsLayout.addWidget(self.movingPropWidget)

        propsWidget = QWidget()
        propsWidget.setMinimumHeight(245)
        propsWidget.setMaximumHeight(350)
        propsWidget.setLayout(propsLayout)

        self.verticalSplitter.addWidget(horizontalSplitter)
        self.verticalSplitter.addWidget(propsWidget)
        self.verticalSplitter.setStretchFactor(0, 2)
        self.verticalSplitter.setStretchFactor(1, 1)
        self.setCentralWidget(self.verticalSplitter)
class StatusScrollArea(QScrollArea):
    def __init__(self):
        super(StatusScrollArea, self).__init__()

        self._width = 0
        self._group_count = 0

        self._pan_pos = None

        self.__create_ui()
        self.__init_ui()

    def __create_ui(self):
        self.container = QWidget()
        self.container_layout = QHBoxLayout()

        self.container.setLayout(self.container_layout)
        self.setWidget(self.container)

    def __init_ui(self):
        self.container.setFixedHeight(TOOLBAR_BUTTON_SIZE)
        self.container_layout.setContentsMargins(0, 0, 0, 0)
        self.container_layout.setSpacing(1)
        self.container_layout.setAlignment(Qt.AlignLeft)

        self.setFixedHeight(TOOLBAR_BUTTON_SIZE)
        self.setFocusPolicy(Qt.NoFocus)
        self.setFrameShape(self.NoFrame)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def _update_width(self, expand_value):
        self._width += expand_value
        self.container.setFixedWidth(self._width + self._group_count)

    def mousePressEvent(self, event):
        if event.button() == Qt.MidButton:
            QApplication.setOverrideCursor(QCursor(Qt.SizeHorCursor))
            self._pan_pos = event.globalPos()
            event.accept()
        else:
            event.ignore()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.MidButton:
            QApplication.restoreOverrideCursor()
            self._pan_pos = None
            event.accept()
        else:
            event.ignore()

    def mouseMoveEvent(self, event):
        if self._pan_pos:
            h_bar = self.horizontalScrollBar()
            h_bar_pos = h_bar.sliderPosition()
            cursor_pos = event.globalPos()
            cursor_delta = (cursor_pos - self._pan_pos).x()

            h_bar.setValue(h_bar_pos - cursor_delta)
            self._pan_pos = cursor_pos
            event.accept()
        else:
            event.ignore()

    def wheelEvent(self, event):
        if event.orientation() == Qt.Vertical:
            num_degrees = event.delta() / 8
            h_bar = self.horizontalScrollBar()
            h_bar_pos = h_bar.sliderPosition()

            h_bar.setValue(h_bar_pos - num_degrees)
        else:
            super(StatusScrollArea, self).wheelEvent(event)

    def resizeEvent(self, event):
        max_scroll = max(0, self.container.width() - event.size().width())
        self.horizontalScrollBar().setMaximum(max_scroll)

    def add_widget(self, widget):
        # add widget to layout
        self.container_layout.addWidget(widget)

        # connect widget for future update when user interact with it
        widget.toggled.connect(self._update_width)

        # expand widget layout
        self._width += widget.max_length()
        self._group_count += 1
        self.container.setFixedWidth(self._width)
示例#37
0
    def getParameterWidget(self):
        """
		Returns a widget with sliders / fields with which properties of this
		volume property can be adjusted.
		:rtype: QWidget
		"""
        self.brightnessSlider = QSlider(Qt.Horizontal)
        self.brightnessSlider.setMinimum(0)
        self.brightnessSlider.setMaximum(500)
        self.brightnessSlider.setValue(int(self.brightness))
        self.brightnessSlider.valueChanged.connect(self.valueChanged)
        self.brightnessLabel = QLabel(str(self.brightness / 100.0))

        self.windowSlider = QSlider(Qt.Horizontal)
        self.windowSlider.setMinimum(0)
        self.windowSlider.setMaximum(int(abs(self.maximum - self.minimum)))
        self.windowSlider.setValue(int(self.window))
        self.windowSlider.valueChanged.connect(self.valueChanged)
        self.windowLabel = QLabel(str(self.window))

        self.levelSlider = QSlider(Qt.Horizontal)
        self.levelSlider.setMinimum(int(self.minimum))
        self.levelSlider.setMaximum(int(self.maximum))
        self.levelSlider.setValue(int(self.level))
        self.levelSlider.valueChanged.connect(self.valueChanged)
        self.levelLabel = QLabel(str(self.level))

        self.lowerBoundSlider = QSlider(Qt.Horizontal)
        self.lowerBoundSlider.setMinimum(int(self.minimum))
        self.lowerBoundSlider.setMaximum(int(self.maximum))
        self.lowerBoundSlider.setValue(int(self.lowerBound))
        self.lowerBoundSlider.valueChanged.connect(self.valueChanged)
        self.lowerBoundLabel = QLabel(str(self.lowerBound))

        self.upperBoundSlider = QSlider(Qt.Horizontal)
        self.upperBoundSlider.setMinimum(int(self.minimum))
        self.upperBoundSlider.setMaximum(int(self.maximum))
        self.upperBoundSlider.setValue(int(self.upperBound))
        self.upperBoundSlider.valueChanged.connect(self.valueChanged)
        self.upperBoundLabel = QLabel(str(self.upperBound))

        layout = QGridLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(QLabel("Window"), 0, 0)
        layout.addWidget(self.windowSlider, 0, 1)
        layout.addWidget(self.windowLabel, 0, 2)
        layout.addWidget(QLabel("Level"), 1, 0)
        layout.addWidget(self.levelSlider, 1, 1)
        layout.addWidget(self.levelLabel, 1, 2)
        layout.addWidget(QLabel("Brightness"), 2, 0)
        layout.addWidget(self.brightnessSlider, 2, 1)
        layout.addWidget(self.brightnessLabel, 2, 2)
        layout.addWidget(QLabel("Lower threshold"), 3, 0)
        layout.addWidget(self.lowerBoundSlider, 3, 1)
        layout.addWidget(self.lowerBoundLabel, 3, 2)
        layout.addWidget(QLabel("Upper threshold"), 4, 0)
        layout.addWidget(self.upperBoundSlider, 4, 1)
        layout.addWidget(self.upperBoundLabel, 4, 2)

        widget = QWidget()
        widget.setLayout(layout)
        return widget
示例#38
0
class MainWindow(QMainWindow):
    
    profileCreationMenu_Requested = Signal()
    profileSelectionDialog_Requested = Signal()
    pushupCreationMenu_Requested = Signal()
    
    def __init__(self, athlete, pushups): 
        QMainWindow.__init__(self)
        self.setWindowTitle("Pushup app")       
        
        self.athlete = athlete
        self.pushups = pushups
        
        self._initWidth = 1000
        self._initHeight = 600
        self.resize(QSize(self._initWidth, self._initHeight))
        
        self.createGUI()
        self._centerWindow()        
            
    def createGUI(self):
        self.mainWidget = QWidget()
        self._createMenus()
        
        hLayout = QHBoxLayout()
        vLayout = QVBoxLayout()
        innerVLayout = QVBoxLayout()
        
        self.profileBox = Profile(self.athlete)
        self.addPushupBtn = QPushButton("Add Pushup")
        self.addPushupBtn.setMaximumWidth(100)
        
        self.pushupsListWidget = PushupList(self.pushups) 
        
        self.graphWidget = GraphWidget()
        #self.graphWidget.setMaximumSize(400, 300)
                
        vLayout.addWidget(self.profileBox)
        
        hLayout.addWidget(self.pushupsListWidget)
        innerVLayout.addWidget(self.graphWidget)
        hLayout.addLayout(innerVLayout)
        
        vLayout.addLayout(hLayout)
        
        vLayout.addWidget(self.addPushupBtn)
        
        self.mainWidget.setLayout(vLayout)
        self.setCentralWidget(self.mainWidget)
            
    def _createMenus(self):
        self._createActions()
        
        fileMenu = self.menuBar().addMenu("&File")
        profile = self.menuBar().addMenu("&Profile")
        about = self.menuBar().addMenu("&About")
        
        fileMenu.addAction(self.exit)
        profile.addAction(self._switchProfile)
        profile.addAction(self._createProfile)
        about.addAction(self.aboutQtAction)
        about.addAction(self.aboutApplicationAction)
    
    def _createActions(self):             
        # About Menu
        self.aboutQtAction = QAction("About PySide (Qt)", self)
        self.aboutApplicationAction = QAction("About Pushup App", self)
        
        # Profile Menu
        self._createProfile = QAction("Create new profile", self)
        self._switchProfile = QAction("Profile...", self)
        
        #File Menu
        self.exit = QAction("Exit", self)   
        
        self.exit.triggered.connect(self._actionExit)
        self._createProfile.triggered.connect(self._actionCreateProfile)
        self._switchProfile.triggered.connect(self._actionSwitchProfile)
        self.aboutQtAction.triggered.connect(self._actionAboutQt)
        self.aboutApplicationAction.triggered.connect(self._actionAboutApplication)  
        
    def _actionExit(self):
        self.close()
    
    def _actionCreateProfile(self): 
        self.profileCreationMenu_Requested.emit()        
    
    def _actionSwitchProfile(self):
        self.profileSelectionDialog_Requested.emit()
        
    def _actionAboutApplication(self):
        text = "Pushup app is a work in progress application.<br><br>\
                For development information look at the \
                <a href=\"https://github.com/davcri/Push-up-app\">Github Page</a> <br>"
        QMessageBox.about(self, "About Pushup app", text)   
    
    def _actionAboutQt(self):
        QMessageBox.aboutQt(self)
                        
    def _centerWindow(self):
        displayWidth = QApplication.desktop().width()
        displayHeight = QApplication.desktop().height()
        
        self.move(displayWidth/2.0 - self._initWidth/2.0, 
                  displayHeight/2.0 - self._initHeight/2.0 - 50)        
    
    def cleanUI(self):
        self.profileBox.ageLabel.setText("")
        self.profileBox.nameLabel.setText("")
        self.profileBox.surnameLabel.setText("")
        self.profileBox.bmiLabel.setText("")
        self.profileBox.heightLabel.setText("")
        self.profileBox.massLabel.setText("")
        
        self.pushupsListWidget.pushupsListWidget.clear()
        # the first pushupListWidget is the name of the PushupList instance
        # the second is the name of a property of the PushupList instance
        
        self.addPushupBtn.setDisabled(True)
        self.graphWidget.clear()
示例#39
0
import sys
from PySide.QtGui import QLabel, QWidget, QPushButton, QDesktopServices, QVBoxLayout, QApplication, QPixmap
from datetime import datetime
from upload import *
from auth_server import *
from cherrypy import quickstart

#create a Qt App
date = datetime.now()
app = QApplication(sys.argv)
widget = QWidget()
# set up the QWidget...
widget.setLayout(QVBoxLayout())
label = QLabel()
auth_server = AuthVerificationServer()


def isTokenCollected():
    if (get_credentials() != None):
        return True
    else:
        return False


def receive_verification_code(sender):
    save_credentials(sender)
    auth_server.stop_server()


def redirect_to_permission_page():
    QDesktopServices.openUrl(get_permission_url())
示例#40
0
文件: admin_gui.py 项目: wiz21b/koi
    def __init__(self):
        super(MainWindow, self).__init__()

        self.edit_config = EditConfigurationDialog(self)
        self.edit_config.load_configuration()

        w = QWidget(self)

        big_hlayout = QHBoxLayout()

        layout = QVBoxLayout()
        big_hlayout.addLayout(layout)
        big_hlayout.addWidget(self.edit_config)

        layout.addWidget(
            QLabel("<h1>{} administration</h1>".format(
                configuration.get("Globals", "name"))))

        glayout = QGridLayout()

        row = 0

        HOST = "{} or {}".format(guess_server_public_ip(),
                                 socket.gethostname())
        glayout.addWidget(QLabel("<b>Server's IP address"), row, 0)
        ip_address = configuration.get("DEFAULT", "public_ip")
        if not ip_address:
            ip_address = "<font color='red'><b>NOT DEFINED</b></font>"
        glayout.addWidget(QLabel("{} (guessed: {})".format(ip_address, HOST)),
                          row, 1)

        row += 1
        glayout.addWidget(QLabel("<b>Client database URL"), row, 0)
        db_url = configuration.get("Database", "url")
        self.public_url_edit = QLabel(db_url)
        glayout.addWidget(self.public_url_edit, row, 1)

        row += 1
        glayout.addWidget(QLabel("<b>Client server URL"), row, 0)
        url = configuration.get("DownloadSite", "public_url")
        self.public_web_url_edit = QLabel(url)
        glayout.addWidget(self.public_web_url_edit, row, 1)

        row += 1
        glayout.addWidget(QLabel("Server local DB URL"), row, 0)
        db_url = configuration.get("Database", "admin_url")
        self.url_edit = QLabel(db_url)
        glayout.addWidget(self.url_edit, row, 1)

        row += 1
        glayout.addWidget(QLabel("Backup directory"), row, 0)
        db_url = configuration.get("Backup", "backup_directory")
        self.backup_directory_edit = QLabel(db_url)
        glayout.addWidget(self.backup_directory_edit, row, 1)

        row += 1
        glayout.addWidget(QLabel("Data/logs directory"), row, 0)
        self.data_directory_edit = QLabel(get_data_dir())
        glayout.addWidget(self.data_directory_edit, row, 1)

        qgb = QGroupBox("Life data")
        qgb.setLayout(glayout)
        layout.addWidget(qgb)

        hlayout = QHBoxLayout()
        b = QPushButton("Check database")
        b.clicked.connect(self.check_database)
        hlayout.addWidget(b)

        b = QPushButton("Check web server")
        b.clicked.connect(self.check_server)
        hlayout.addWidget(b)

        b = QPushButton("Show delivery_slips download page")
        b.clicked.connect(self.show_client_dowload_page)
        hlayout.addWidget(b)

        qgb = QGroupBox("Checks")
        qgb.setLayout(hlayout)
        layout.addWidget(qgb)

        hlayout = QHBoxLayout()
        # b = QPushButton("Set backup directory")
        # b.clicked.connect(self.set_backup_directory)
        # hlayout.addWidget( b)

        b = QPushButton("Restore backup")
        b.clicked.connect(self.restore_backup)
        hlayout.addWidget(b)

        b = QPushButton("Reset admin account")
        b.clicked.connect(self.create_root_account)
        hlayout.addWidget(b)

        # b = QPushButton("Set public IP")
        # b.clicked.connect(self.set_public_ip)
        # hlayout.addWidget( b)

        # Please use the command line, this is not for the faint hearted.

        # b = QPushButton("Clear database")
        # b.clicked.connect(self.create_database)
        # hlayout.addWidget( b)

        qgb = QGroupBox("Actions")
        qgb.setLayout(hlayout)
        layout.addWidget(qgb)

        vlayout = QVBoxLayout()

        # if platform.system() == 'Windows':
        #     # when running on Linux, it's expected that the
        #     # whole server configuration is set up by us
        #
        #     hlayout = QHBoxLayout()
        #     b = QPushButton("Start server manually")
        #     b.clicked.connect(self.start_server_manually)
        #     hlayout.addWidget( b)
        #
        #     b = QPushButton("Stop server manually")
        #     b.clicked.connect(self.stop_server_manually)
        #     hlayout.addWidget( b)
        #     vlayout.addLayout(hlayout)
        #
        #     hlayout = QHBoxLayout()
        #     b = QPushButton("Install services")
        #     b.clicked.connect(self.install_service)
        #     hlayout.addWidget( b)
        #
        #     b = QPushButton("Uninstall services")
        #     b.clicked.connect(self.uninstall_service)
        #     hlayout.addWidget( b)
        #     vlayout.addLayout(hlayout)
        #
        #     b = QPushButton("Install scheduled services")
        #     b.clicked.connect(self.install_on_start_tasks)
        #     vlayout.addWidget( b)
        #
        #     # b = QPushButton("Upgrade delivery_slips")
        #     # b.clicked.connect(self.upgrade_client)
        #     # layout.addWidget( b)
        #
        #     qgb = QGroupBox("Service & installation")
        #     qgb.setLayout(vlayout)
        #     layout.addWidget(qgb)

        self.log_view = QTextEdit()
        layout.addWidget(self.log_view)

        self.url_edit.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.public_url_edit.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.public_web_url_edit.setTextInteractionFlags(
            Qt.TextSelectableByMouse)
        self.backup_directory_edit.setTextInteractionFlags(
            Qt.TextSelectableByMouse)

        self.log_view.setReadOnly(True)

        w.setLayout(big_hlayout)

        self.setCentralWidget(w)
	def setFile(self, fileName):
		"""
		Slot that reads properties of the dataset and displays them in a few widgets.
		"""
		if fileName is None:
			return

		self.fileName = fileName

		# Read info from dataset
		# TODO: read out the real world dimensions in inch or cm
		# TODO: scalar type (int, float, short, etc.)
		imageReader = DataReader()
		imageData = imageReader.GetImageData(fileName)

		directory, name = os.path.split(fileName)
		dimensions = imageData.GetDimensions()
		minimum, maximum = imageData.GetScalarRange()
		scalarType = imageData.GetScalarTypeAsString()

		bins = DataAnalyzer.histogramForData(imageData, 256)

		self.histogram = Histogram()
		self.histogram.bins = bins
		self.histogram.enabled = True

		self.histogramWidget = HistogramWidget()
		self.histogramWidget.setMinimumHeight(100)
		self.histogramWidget.setHistogram(self.histogram)
		self.histogramWidget.setAxeMode(bottom=HistogramWidget.AxeClear,
			left=HistogramWidget.AxeLog)
		Style.styleWidgetForTab(self.histogramWidget)

		nameText = name
		dimsText = "(" + str(dimensions[0]) + ", " + str(dimensions[1]) + ", " + str(dimensions[2]) + ")"
		voxsText = str(dimensions[0] * dimensions[1] * dimensions[2])
		rangText = "[" + str(minimum) + " : " + str(maximum) + "]"
		typeText = scalarType

		layout = self.layout()
		if not layout:
			# Create a new layout
			layout = QGridLayout()
			layout.setAlignment(Qt.AlignTop)

			# Create string representations
			nameLabels = []
			nameLabels.append(QLabel("File name:"))
			nameLabels.append(QLabel("Dimensions:"))
			nameLabels.append(QLabel("Voxels:"))
			nameLabels.append(QLabel("Range:"))
			nameLabels.append(QLabel("Data type:"))

			for label in nameLabels:
				label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

			# Create 'dynamic' labels
			self.labelTitle = QLabel(nameText)
			self.labelDimensions = QLabel(dimsText)
			self.labelVoxels = QLabel(voxsText)
			self.labelRange = QLabel(rangText)
			self.labelType = QLabel(typeText)

			index = 0
			for label in nameLabels:
				layout.addWidget(label, index, 0)
				index += 1

			layout.addWidget(self.labelTitle, 0, 1)
			layout.addWidget(self.labelDimensions, 1, 1)
			layout.addWidget(self.labelVoxels, 2, 1)
			layout.addWidget(self.labelRange, 3, 1)
			layout.addWidget(self.labelType, 4, 1)
			layout.addWidget(self.histogramWidget, 5, 0, 1, 2)

			widget = QWidget()
			widget.setLayout(layout)
			Style.styleWidgetForTab(widget)
			self.scrollArea.setWidget(widget)

			scrollLayout = QGridLayout()
			scrollLayout.setSpacing(0)
			scrollLayout.setContentsMargins(0, 0, 0, 0)
			scrollLayout.addWidget(self.scrollArea)
			self.setLayout(scrollLayout)
		else:
			# Just update the text for the 'dynamic' labels
			self.labelTitle.setText(nameText)
			self.labelDimensions.setText(dimsText)
			self.labelVoxels.setText(voxsText)
			self.labelRange.setText(rangText)
			self.labelType.setText(typeText)
示例#42
0
class MainWindow(QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Cobaya input generator for Cosmology")
        self.setGeometry(0, 0, 1500, 1000)
        self.move(
            QApplication.desktop().screenGeometry().center() - self.rect().center())
        self.show()
        # Main layout
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)
        self.layout_left = QVBoxLayout()
        self.layout.addLayout(self.layout_left)
        self.layout_output = QVBoxLayout()
        self.layout.addLayout(self.layout_output)
        # LEFT: Options
        self.options = QWidget()
        self.layout_options = QVBoxLayout()
        self.options.setLayout(self.layout_options)
        self.options_scroll = QScrollArea()
        self.options_scroll.setWidget(self.options)
        self.options_scroll.setWidgetResizable(True)
        self.layout_left.addWidget(self.options_scroll)
        titles = odict([
            ["Presets", odict([["preset", "Presets"]])],
            ["Cosmological Model", odict([
                ["theory", "Theory code"],
                ["primordial", "Primordial perturbations"],
                ["geometry", "Geometry"],
                ["hubble", "Hubble parameter constraint"],
                ["matter", "Matter sector"],
                ["neutrinos", "Neutrinos and other extra matter"],
                ["dark_energy", "Lambda / Dark energy"],
                ["bbn", "BBN"],
                ["reionization", "Reionization history"]])],
            ["Data sets", odict([
                ["like_cmb", "CMB experiments"],
                ["like_bao", "BAO experiments"],
                ["like_sn", "SN experiments"],
                ["like_H0", "Local H0 measurements"]])],
            ["Sampler", odict([["sampler", "Samplers"]])]])
        self.combos = odict()
        for group, fields in titles.items():
            group_box = QGroupBox(group)
            self.layout_options.addWidget(group_box)
            group_layout = QVBoxLayout(group_box)
            for a, desc in fields.items():
                self.combos[a] = QComboBox()
                if len(fields) > 1:
                    label = QLabel(desc)
                    group_layout.addWidget(label)
                group_layout.addWidget(self.combos[a])
                self.combos[a].addItems(
                    [text(k, v) for k, v in getattr(input_database, a).items()])
        # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED
        #                if a == "theory":
        #                    # Add Planck-naming checkbox
        #                    self.planck_names = QCheckBox(
        #                        "Keep common parameter names "
        #                        "(useful for fast CLASS/CAMB switching)")
        #                    group_layout.addWidget(self.planck_names)
        # Connect to refreshers -- needs to be after adding all elements
        for field, combo in self.combos.items():
            if field == "preset":
                combo.currentIndexChanged.connect(self.refresh_preset)
            else:
                combo.currentIndexChanged.connect(self.refresh)
        #        self.planck_names.stateChanged.connect(self.refresh_keep_preset)
        # RIGHT: Output + buttons
        self.display_tabs = QTabWidget()
        self.display = {}
        for k in ["yaml", "python", "citations"]:
            self.display[k] = QTextEdit()
            self.display[k].setLineWrapMode(QTextEdit.NoWrap)
            self.display[k].setFontFamily("mono")
            self.display[k].setCursorWidth(0)
            self.display[k].setReadOnly(True)
            self.display_tabs.addTab(self.display[k], k)
        self.layout_output.addWidget(self.display_tabs)
        # Buttons
        self.buttons = QHBoxLayout()
        self.save_button = QPushButton('Save', self)
        self.copy_button = QPushButton('Copy to clipboard', self)
        self.buttons.addWidget(self.save_button)
        self.buttons.addWidget(self.copy_button)
        self.save_button.released.connect(self.save_file)
        self.copy_button.released.connect(self.copy_clipb)
        self.layout_output.addLayout(self.buttons)
        self.save_dialog = QFileDialog()
        self.save_dialog.setFileMode(QFileDialog.AnyFile)
        self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)

    def create_input(self):
        return create_input(
            get_comments=True,
            #           planck_names=self.planck_names.isChecked(),
            **{field: list(getattr(input_database, field).keys())[combo.currentIndex()]
               for field, combo in self.combos.items() if field is not "preset"})

    @Slot()
    def refresh_keep_preset(self):
        self.refresh_display(self.create_input())

    @Slot()
    def refresh(self):
        self.combos["preset"].blockSignals(True)
        self.combos["preset"].setCurrentIndex(0)
        self.combos["preset"].blockSignals(False)
        self.refresh_display(self.create_input())

    @Slot()
    def refresh_preset(self):
        preset = list(getattr(input_database, "preset").keys())[
            self.combos["preset"].currentIndex()]
        info = create_input(
            get_comments=True,
            #            planck_names=self.planck_names.isChecked(),
            preset=preset)
        self.refresh_display(info)
        # Update combo boxes to reflect the preset values, without triggering update
        for k, v in input_database.preset[preset].items():
            if k in [input_database._desc]:
                continue
            self.combos[k].blockSignals(True)
            self.combos[k].setCurrentIndex(
                self.combos[k].findText(
                    text(v, getattr(input_database, k).get(v))))
            self.combos[k].blockSignals(False)

    def refresh_display(self, info):
        try:
            comments = info.pop(input_database._comment, None)
            comments_text = "\n# " + "\n# ".join(comments)
        except (TypeError,  # No comments
                AttributeError):  # Failed to generate info (returned str instead)
            comments_text = ""
        self.display["python"].setText(
            "from collections import OrderedDict\n\ninfo = " +
            pformat(info) + comments_text)
        self.display["yaml"].setText(yaml_dump(info) + comments_text)
        self.display["citations"].setText(prettyprint_citation(citation(info)))

    @Slot()
    def save_file(self):
        ftype = next(k for k, w in self.display.items()
                     if w is self.display_tabs.currentWidget())
        ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)",
                   "citations": "(*.txt)"}[ftype]
        fsuffix = {"yaml": ".yaml", "python": ".py", "citations": ".txt"}[ftype]
        fname, path = self.save_dialog.getSaveFileName(
            self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd())
        if not fname.endswith(fsuffix):
            fname += fsuffix
        with open(fname, "w+") as f:
            f.write(self.display_tabs.currentWidget().toPlainText())

    @Slot()
    def copy_clipb(self):
        self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())
示例#43
0
class SettingsWindow(QDialog):
    def __init__(self, parent):
        super(self.__class__, self).__init__(parent)
        self.parent = parent
        self.lib = libserial.InitApp(self)
        if self.parent.receive is not None:
            self.boolean_config_is_ok = True
        else:
            self.boolean_config_is_ok = False

        self.config_parser = ConfigParser.ConfigParser()
        self.config_parser.read("config/profiles/profiles.ini")

        self.settings_parser = ConfigParser.ConfigParser()
        self.settings_parser.read('config/settings.ini')

        self.setWindowTitle(SERIAL_CHAT_SETTINGS_TITLE)

        self.button_box_dialog = QDialogButtonBox(QDialogButtonBox.Cancel
                                                  | QDialogButtonBox.Ok)
        self.button_box_dialog.button(QDialogButtonBox.Ok).setText(CONNECT)
        self.button_box_dialog.button(QDialogButtonBox.Cancel).setText(CANCEL)
        self.button_box_dialog.accepted.connect(self.accept)
        self.accepted.connect(self.apply_setting_changes)
        self.button_box_dialog.rejected.connect(self.reject)
        self.serial_dropdown = QComboBox()

        self.lib.init__serial()
        self.serial_values = self.lib.get_serials()
        for serials in self.serial_values:
            self.serial_dropdown.addItem(serials)

        if self.parent.serial_port is not None:
            self.serial_dropdown.setCurrentIndex(
                self.serial_dropdown.findText(self.parent.serial_port.name))

        self.profiles_combobox = QComboBox()
        self.profiles_combobox.addItem("None")
        if self.parent.choosen_profile == "Custom":
            self.profiles_combobox.addItem("Custom")
        for profile in self.config_parser.sections():
            self.profiles_combobox.addItem(profile)
        if self.parent.custom_settings:
            self.profiles_combobox.setCurrentIndex(
                self.profiles_combobox.findText('Custom'))
        elif self.parent.choosen_profile != 'None':
            self.profiles_combobox.setCurrentIndex(
                self.profiles_combobox.findText(self.parent.choosen_profile))
        else:
            self.profiles_combobox.setCurrentIndex(
                self.profiles_combobox.findText('None'))

        self.profiles_combobox.currentIndexChanged.connect(
            self.change_custom_settings_on_profile)

        self.custom_settings_checkbox = QCheckBox()
        self.custom_settings_checkbox.stateChanged.connect(
            self.custom_settings_enable_disable)

        self.interval_time_lineedit = QLineEdit(str(self.parent.interval_time))
        self.interval_time_lineedit.editingFinished.connect(
            self.check_if_digit)
        self.interval_time_lineedit.setDisabled(True)

        self.serial_speed_combobox = QComboBox()
        for sp in serial_speeds:
            self.serial_speed_combobox.addItem(str(sp))
        if self.boolean_config_is_ok:
            self.serial_speed_combobox.setCurrentIndex(
                self.serial_speed_combobox.findText(
                    str(self.parent.serial_port.baudrate)))
        else:
            self.serial_speed_combobox.setCurrentIndex(
                self.serial_speed_combobox.findText('9600'))
        self.serial_speed_combobox.setDisabled(True)

        self.databits_combobox = QComboBox()
        for db in bytesize_values:
            self.databits_combobox.addItem(str(db))
        if self.boolean_config_is_ok:
            self.databits_combobox.setCurrentIndex(
                self.databits_combobox.findText(
                    str(self.parent.serial_port.bytesize)))
        else:
            self.databits_combobox.setCurrentIndex(
                self.databits_combobox.findText('8'))
        self.databits_combobox.setDisabled(True)

        self.stopbits_combobox = QComboBox()
        for sb in stop_values:
            self.stopbits_combobox.addItem(str(sb))
        if self.boolean_config_is_ok:
            sb = str(self.parent.serial_port.stopbits).replace('.', ',')
            self.stopbits_combobox.setCurrentIndex(
                self.stopbits_combobox.findText(str(sb)))
        else:
            self.stopbits_combobox.setCurrentIndex(
                self.stopbits_combobox.findText('1'))
        self.stopbits_combobox.setDisabled(True)

        self.parity_combobox = QComboBox()
        for par in parity_values:
            self.parity_combobox.addItem(str(par))
        if self.boolean_config_is_ok:
            table = {'O': 'Odd', 'E': 'Even', 'N': 'None'}
            xxx = [
                item for key, item in table.items()
                if self.parent.serial_port.parity == key
            ]
            self.parity_combobox.setCurrentIndex(parity_values.index(xxx[0]))
        else:
            self.parity_combobox.setCurrentIndex(
                self.parity_combobox.findText("None"))
        self.parity_combobox.setDisabled(True)

        self.flowcontrol_combobox = QComboBox()
        for fc in flow_control_values:
            self.flowcontrol_combobox.addItem(str(fc))
        if self.boolean_config_is_ok:
            if self.parent.serial_port.xonxoff:
                self.flowcontrol_combobox.setCurrentIndex(
                    self.flowcontrol_combobox.findText("XON/XOFF"))
            elif self.parent.serial_port.rtscts:
                self.flowcontrol_combobox.setCurrentIndex(
                    self.flowcontrol_combobox.findText("RTS/CTS"))
            else:
                self.flowcontrol_combobox.setCurrentIndex(
                    self.flowcontrol_combobox.findText("None"))
        else:
            self.flowcontrol_combobox.setCurrentIndex(
                self.flowcontrol_combobox.findText("None"))
        self.flowcontrol_combobox.setDisabled(True)

        self.nickname_lineedit = QLineEdit()
        if self.settings_parser.has_option('default', 'nickname'):
            nickname = self.settings_parser.get('default', 'nickname')
            if type(nickname) == str:
                nickname = nickname.decode('utf-8')
            self.nickname_lineedit.setText(
                self.settings_parser.get('default', 'nickname'))
        else:
            if self.parent.nickname is None:
                self.nickname_lineedit.setText("Guest_" + MD5.new(
                    str(datetime.datetime.now())).digest().encode('hex')[:5])
            else:
                self.nickname_lineedit.setText(self.parent.nickname)

        self.save_folder_editline = QLineEdit(self.parent.default_save_folder)
        self.save_folder_editline.editingFinished.connect(
            self.check_if_folder_exists)
        if self.settings_parser.has_option('default', 'default_save_folder'):
            folder = self.settings_parser.get('default', 'default_save_folder')
            if type(folder) == str:
                folder = folder.decode('utf-8')
            self.save_folder_editline.setText(folder)
            self.check_if_folder_exists()

        self.dir_browser_button = QPushButton()
        self.dir_browser_button.setIcon(QIcon(icons_folder + 'folder.png'))
        self.dir_browser_button.clicked.connect(self.choose_save_dir)

        self.horizontal_box_hboxlayout = QHBoxLayout()
        self.horizontal_box_hboxlayout.addWidget(self.save_folder_editline)
        self.horizontal_box_hboxlayout.addWidget(self.dir_browser_button)
        self.horizontal_box_container_widget = QWidget()
        self.horizontal_box_container_widget.setLayout(
            self.horizontal_box_hboxlayout)

        self.enable_ACP127 = QCheckBox()
        self.enable_ACP127.stateChanged.connect(
            self.enable_functionality_ACP127)
        if self.parent.acp127:
            self.enable_ACP127.setChecked(True)

        self.encryption_password_lineedit = QLineEdit()
        self.enable_encryption_checkbox = QCheckBox()
        self.enable_encryption_checkbox.stateChanged.connect(
            self.enable_functionality_encryption)
        if self.parent.isEncryptionEnabled:
            self.enable_encryption_checkbox.setChecked(True)

        self.encryption_password_lineedit.setEchoMode(
            QLineEdit.EchoMode.PasswordEchoOnEdit)
        if self.parent.encryption_key is not None:
            self.encryption_password_lineedit.setText(
                self.parent.encryption_key)
        if self.enable_encryption_checkbox.isChecked():
            self.encryption_password_lineedit.setDisabled(False)
        else:
            self.encryption_password_lineedit.setDisabled(True)

        self.grid_form_layout = QFormLayout()
        self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_TITLE + ":",
                                     self.serial_dropdown)
        self.grid_form_layout.addRow(FORMLAYOUT_PROFILE_TITLE + ":",
                                     self.profiles_combobox)
        self.grid_form_layout.addRow(FORMLAYOUT_CUSTOM_SERIAL_SETTINGS_TITLE,
                                     self.custom_settings_checkbox)
        self.grid_form_layout.addRow(FORMLAYOUT_INTERVAL_TIME_TITLE + ":",
                                     self.interval_time_lineedit)
        self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_SPEED_TITLE + "(baud):",
                                     self.serial_speed_combobox)
        self.grid_form_layout.addRow(FORMLAYOUT_DATA_BITS_TITLE + ":",
                                     self.databits_combobox)
        self.grid_form_layout.addRow(FORMLAYOUT_STOP_BITS_TITLE + ":",
                                     self.stopbits_combobox)
        self.grid_form_layout.addRow(FORMLAYOUT_PARITY_TITLE + ":",
                                     self.parity_combobox)
        self.grid_form_layout.addRow(FORMLAYOUT_FLOWCONTROL_TITLE + ":",
                                     self.flowcontrol_combobox)
        self.grid_form_layout.addRow(
            FORMLAYOUT_ENABLE_ACP127_TITLE + " ACP-127", self.enable_ACP127)
        self.grid_form_layout.addRow(FORMLAYOUT_ENABLE_ENCRYPTION_TITLE,
                                     self.enable_encryption_checkbox)
        self.grid_form_layout.addRow(FORMLAYOUT_ENCRYPTION_KEY_TITLE,
                                     self.encryption_password_lineedit)
        self.grid_form_layout.addRow(FORMLAYOUT_NICKNAME_TITLE + ":",
                                     self.nickname_lineedit)
        self.grid_form_layout.addRow(FORMLAYOUT_SAVE_FOLDER_FILE_TITLE + ":",
                                     self.horizontal_box_container_widget)
        self.grid_form_layout.addRow("", self.button_box_dialog)
        self.setLayout(self.grid_form_layout)
        self.show()

    def enable_functionality_encryption(self):
        if self.enable_encryption_checkbox.isChecked():
            self.encryption_password_lineedit.setDisabled(False)
        else:
            self.encryption_password_lineedit.setDisabled(True)

    def check_if_folder_exists(self):

        if not os.path.isdir(self.save_folder_editline.text()):
            msgBox = QMessageBox(icon=QMessageBox.Warning,
                                 text=ERROR_NO_DIR_MESSAGE)
            msgBox.setWindowTitle(ERROR_NO_DIR_TITLE)
            msgBox.exec_()
            self.save_folder_editline.setText(self.parent.default_save_folder)

    def check_if_digit(self):

        try:
            int(self.interval_time_lineedit.text())
        except:
            msgBox = QMessageBox(icon=QMessageBox.Warning,
                                 text=ERROR_NO_INT_MESSAGE)
            msgBox.setWindowTitle(ERROR_NO_INT_TITLE)
            msgBox.exec_()
            self.interval_time_lineedit.setText(str(self.parent.interval_time))

    def choose_save_dir(self):
        fname = QFileDialog(self, FILEBROWSER_SAVE_FOLDER_TITLE)
        fname.setFileMode(QFileDialog.Directory)
        looking_label = QFileDialog.DialogLabel(QFileDialog.LookIn)
        filename_label = QFileDialog.DialogLabel(QFileDialog.FileName)
        filetype_label = QFileDialog.DialogLabel(QFileDialog.FileType)
        fname.setLabelText(looking_label, FILEBROWSER_SAVE_FOLDER_LOOKIN)
        fname.setLabelText(filename_label, FILEBROWSER_SAVE_FOLDER_FOLDERNAME)
        fname.setLabelText(filetype_label, FILEBROWSER_SAVE_FOLDER_FOLDERTYPE)
        fname.setOption(QFileDialog.ShowDirsOnly)

        if fname.exec_():
            filename = fname.selectedFiles()[0]
            self.save_folder_editline.setText(filename)

    def enable_functionality_ACP127(self):
        if self.enable_ACP127.isChecked():
            self.parent.acp127 = True
        else:
            self.parent.acp127 = False

    def apply_setting_changes(self):

        res = None
        self.parent.custom_settings_enable_disable = self.custom_settings_checkbox.isChecked(
        )
        self.parent.choosen_profile = self.profiles_combobox.currentText()
        if self.parent.custom_settings_enable_disable:
            self.parent.choosen_profile = "Custom"

        if self.enable_encryption_checkbox.isChecked():
            self.parent.isEncryptionEnabled = True
            self.parent.encryption_key = self.encryption_password_lineedit.text(
            )
        else:
            self.parent.isEncryptionEnabled = False
            self.parent.encryption_key = None

        if self.nickname_lineedit.text() != "":
            nick = self.nickname_lineedit.text().rstrip()
            nick = nick.replace(" ", "_")
            self.parent.nickname = nick
        if self.save_folder_editline.text() != "":
            if os.path.isdir(self.save_folder_editline.text()):
                self.parent.default_save_folder = self.save_folder_editline.text(
                )
        self.parent.interval_time = int(self.interval_time_lineedit.text())
        if self.flowcontrol_combobox.currentText() == "XON/XOFF":
            x_control = True
        else:
            x_control = False

        if self.flowcontrol_combobox.currentText() == "RTS/CTS":
            r_control = True
        else:
            r_control = False
        if self.parent.receive is None:
            res = self.lib.set_serial(
                port=self.serial_dropdown.currentText(),
                baudrate=self.serial_speed_combobox.currentText(),
                bytesize=self.databits_combobox.currentText(),
                stopbits=self.stopbits_combobox.currentText(),
                parity=self.parity_combobox.currentText(),
                xonxoff=x_control,
                rtscts=r_control)
        else:
            self.parent.receive.loop_run = False
            self.parent.receive.wait()
            self.parent.receive = None
            res = self.lib.set_serial(
                port=self.serial_dropdown.currentText(),
                baudrate=self.serial_speed_combobox.currentText(),
                bytesize=self.databits_combobox.currentText(),
                stopbits=self.stopbits_combobox.currentText(),
                parity=self.parity_combobox.currentText(),
                xonxoff=x_control,
                rtscts=r_control)
        if type(res) == OSError:
            self.parent.status_bar_widget.showMessage(str(res), 5000)
            msgBox = QMessageBox(icon=QMessageBox.Critical, text=str(res))
            msgBox.setWindowTitle(ERROR_INTERFACE_TITLE)
            msgBox.exec_()
        if type(res) is not None and type(res) != OSError:
            self.parent.serial_port = res
            self.parent.start_threads()
            self.parent.status_bar_widget.showMessage(
                MSG_SERIAL_INT_STARTED % self.parent.serial_port.port)

    def change_custom_settings_on_profile(self):
        if self.profiles_combobox.currentText() != 'None':

            section = self.profiles_combobox.currentText()
            self.interval_time_lineedit.setText(
                self.config_parser.get(section, "interval"))
            self.serial_speed_combobox.setCurrentIndex(
                self.serial_speed_combobox.findText(
                    self.config_parser.get(section, "serialspeed")))
            self.databits_combobox.setCurrentIndex(
                self.databits_combobox.findText(
                    self.config_parser.get(section, "bytesize")))
            self.stopbits_combobox.setCurrentIndex(
                self.stopbits_combobox.findText(
                    self.config_parser.get(section, "stopbits")))
            self.parity_combobox.setCurrentIndex(
                self.parity_combobox.findText(
                    self.config_parser.get(section, "parity")))
            if self.config_parser.get(section, "xonxoff") == 'True':
                self.flowcontrol_combobox.setCurrentIndex(
                    self.flowcontrol_combobox.findText("XON/XOFF"))
            elif self.config_parser.get(section, "rtscts") == 'True':
                self.flowcontrol_combobox.setCurrentIndex(
                    self.flowcontrol_combobox.findText("RTS/CTS"))
            else:
                self.flowcontrol_combobox.setCurrentIndex(
                    self.flowcontrol_combobox.findText("None"))
            if self.config_parser.get(section, "acp127") == "True":
                self.enable_ACP127.setChecked(True)
            else:
                self.enable_ACP127.setChecked(False)
        elif self.profiles_combobox.currentText() == "None":
            self.serial_speed_combobox.setCurrentIndex(
                self.serial_speed_combobox.findText('9600'))
            self.interval_time_lineedit.setText(str(self.parent.intervaltime))
            self.databits_combobox.setCurrentIndex(
                self.databits_combobox.findText('8'))
            self.stopbits_combobox.setCurrentIndex(
                self.stopbits_combobox.findText('1'))
            self.parity_combobox.setCurrentIndex(
                self.parity_combobox.findText('None'))
            self.flowcontrol_combobox.setCurrentIndex(
                self.flowcontrol_combobox.findText('None'))
            self.enable_ACP127.setChecked(False)

    def custom_settings_enable_disable(self):
        if self.custom_settings_checkbox.isChecked():
            self.interval_time_lineedit.setDisabled(False)
            self.serial_speed_combobox.setDisabled(False)
            self.databits_combobox.setDisabled(False)
            self.stopbits_combobox.setDisabled(False)
            self.parity_combobox.setDisabled(False)
            self.flowcontrol_combobox.setDisabled(False)
        else:
            self.interval_time_lineedit.setDisabled(True)
            self.serial_speed_combobox.setDisabled(True)
            self.databits_combobox.setDisabled(True)
            self.stopbits_combobox.setDisabled(True)
            self.parity_combobox.setDisabled(True)
            self.flowcontrol_combobox.setDisabled(True)
	def _getHorizontalContainerFor(self, tooltip, main_window):
		container = QWidget(main_window)
		container.setLayout(QHBoxLayout())
		container.layout().setContentsMargins(0, 0, 0, 0)
		container.layout().setSpacing(0)
		return container
示例#45
0
    def __init__(self):

        url = QLineEdit()
        quality = QLineEdit()
        urlLabel = QLabel('Url')
        qualityLabel = QLabel('Quality')
        messages = QTextEdit()
        messagesLabel = QLabel('Messages')
        links = QTableWidget(0, 2)
        linksLabel = QLabel('Links')
        clearMessages = QPushButton('Clear Messages')
        checkIfOnline = QPushButton('Check If Online')
        addSelectedLink = QPushButton('Add Link')
        removeSelectedLink = QPushButton('Remove Selected Link')

        messages.setReadOnly(True)

        links.setHorizontalHeaderLabels(['Url', 'Status'])
        links.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        links.horizontalHeader().setResizeMode(1, QHeaderView.Fixed)

        # set the events

        url.returnPressed.connect(self.select_stream_from_entry)
        quality.returnPressed.connect(self.select_stream_from_entry)
        links.itemDoubleClicked.connect(self.select_stream_from_link)
        clearMessages.clicked.connect(self.clear_messages)
        checkIfOnline.clicked.connect(self.check_if_online)
        addSelectedLink.clicked.connect(self.add_selected_link)
        removeSelectedLink.clicked.connect(self.remove_selected_link)

        #set shortcut
        checkIfOnline.setShortcut(QKeySequence(Qt.Key_F5))

        # set the layouts

        mainLayout = QGridLayout()

        # first row
        mainLayout.addWidget(urlLabel, 0, 0, 1, 1)  # spans 1 column
        mainLayout.addWidget(qualityLabel, 0, 1, 1, 1)  # spans 1 column
        mainLayout.addWidget(linksLabel, 0, 2, 1, 3)  # spans 3 columns

        # second row  (links widget occupies 2 rows and 2 columns)
        mainLayout.addWidget(url, 1, 0, 1, 1)  # spans 1 column
        mainLayout.addWidget(quality, 1, 1, 1, 1)  # spans 1 column
        mainLayout.addWidget(links, 1, 2, 2, 3)  # spans 3 columns

        # third row (messages widget occupies 2 columns)
        mainLayout.addWidget(messages, 2, 0, 1, 2)

        # fourth row
        mainLayout.addWidget(messagesLabel, 3, 0)
        mainLayout.addWidget(clearMessages, 3, 1)
        mainLayout.addWidget(checkIfOnline, 3, 2)
        mainLayout.addWidget(addSelectedLink, 3, 3)
        mainLayout.addWidget(removeSelectedLink, 3, 4)

        window = QWidget()

        window.setLayout(mainLayout)
        window.setWindowTitle('Live Streamer')
        window.resize(700, 350)
        window.show()

        self.url_ui = url
        self.quality_ui = quality
        self.messages_ui = messages
        self.links_ui = links
        self.window_ui = window

        self.links = set()

        self.data_file = os.path.join(os.path.expanduser("~"), ".config",
                                      "livestreamer-ui", "data.txt")
        folder = os.path.dirname(self.data_file)
        if not os.path.exists(folder):
            os.makedirs(folder)
示例#46
0
    def __init__(self):
        QMainWindow.__init__(self)

        # the user interface, consisting of a progress bar above a plain
        # text edit, which logs all actions.
        container = QWidget(self)
        container.setLayout(QVBoxLayout(container))
        self.setCentralWidget(container)
        progressbar = QProgressBar(container)
        container.layout().addWidget(progressbar)
        log = QPlainTextEdit(container)
        container.layout().addWidget(log)

        # the actual worker thread
        counter = Counter(100, self)

        # an action to quit the windows
        exit = QAction(QIcon.fromTheme('application-exit'), 'exit', self)

        # add two actions to start and stop the worker to the toolbar of the
        # main window
        start_counting = QAction(QIcon.fromTheme('media-playback-start'),
                                 'Start counting', self)
        stop_counting = QAction(QIcon.fromTheme('media-playback-stop'),
                                'Stop counting', self)
        # initially no counter runs, so we can disable the stop action
        stop_counting.setEnabled(False)

        # add all actions to a toolbar
        actions = self.addToolBar('Actions')
        actions.addAction(exit)
        actions.addSeparator()
        actions.addAction(start_counting)
        actions.addAction(stop_counting)

        # quit the application, if the quit action is triggered
        exit.triggered.connect(QApplication.instance().quit)

        # start and stop the counter, if the corresponding actions are
        # triggered.
        start_counting.triggered.connect(counter.start)
        stop_counting.triggered.connect(counter.stop)

        # adjust the minimum and the maximum of the progress bar, if
        # necessary.  Not really required in this snippet, but added for the
        # purpose of demonstrating it
        counter.minimumChanged.connect(progressbar.setMinimum)
        counter.maximumChanged.connect(progressbar.setMaximum)

        # switch the enabled states of the actions according to whether the
        # worker is running or not
        counter.started.connect(partial(start_counting.setEnabled, False))
        counter.started.connect(partial(stop_counting.setEnabled, True))
        counter.finished.connect(partial(start_counting.setEnabled, True))
        counter.finished.connect(partial(stop_counting.setEnabled, False))

        # update the progess bar continuously
        counter.progress.connect(progressbar.setValue)

        # log all actions in our logging widget
        counter.started.connect(
            partial(self.statusBar().showMessage, 'Counting'))
        counter.finished.connect(partial(self.statusBar().showMessage, 'Done'))
        # log a forced stop
        stop_counting.triggered.connect(partial(log.appendPlainText,
                                                'Stopped'))
        # log all counted values
        counter.progress.connect(lambda v: log.appendPlainText(str(v)))

        # and finally show the current state in the status bar.
        counter.started.connect(partial(log.appendPlainText, 'Counting'))
        counter.finished.connect(partial(log.appendPlainText, 'Done'))
示例#47
0
    def setupUi(self):

        scene = QGraphicsScene(self)
        self.view = QGraphicsView(scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVisible(True)
        self.view.setInteractive(True)

        self.createPixmapIcon()

        self.mapWidget = MapWidget(self.mapManager)
        scene.addItem(self.mapWidget)
        self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95))
        self.mapWidget.setZoomLevel(5)

        #...
        self.slider = QSlider(Qt.Vertical, self)
        self.slider.setTickInterval(1)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setMaximum(self.mapManager.maximumZoomLevel())
        self.slider.setMinimum(self.mapManager.minimumZoomLevel())

        self.slider.valueChanged[int].connect(self.sliderValueChanged)
        self.mapWidget.zoomLevelChanged.connect(self.mapZoomLevelChanged)

        mapControlLayout = QVBoxLayout()

        self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged)

        for mapType in self.mapWidget.supportedMapTypes():
            radio = QRadioButton(self)
            if mapType == QGraphicsGeoMap.StreetMap:
                radio.setText('Street')
            elif mapType == QGraphicsGeoMap.SatelliteMapDay:
                radio.setText('Sattelite')
            elif mapType == QGraphicsGeoMap.SatelliteMapNight:
                radio.setText('Sattelite - Night')
            elif mapType == QGraphicsGeoMap.TerrainMap:
                radio.setText('Terrain')

            if mapType == self.mapWidget.mapType():
                radio.setChecked(True)

            radio.toggled[bool].connect(self.mapTypeToggled)

            self.mapControlButtons.append(radio)
            self.mapControlTypes.append(mapType)
            mapControlLayout.addWidget(radio)

        self.latitudeEdit = QLineEdit()
        self.longitudeEdit = QLineEdit()

        formLayout = QFormLayout()
        formLayout.addRow('Latitude', self.latitudeEdit)
        formLayout.addRow('Longitude', self.longitudeEdit)

        self.captureCoordsButton = QToolButton()
        self.captureCoordsButton.setText('Capture coordinates')
        self.captureCoordsButton.setCheckable(True)

        self.captureCoordsButton.toggled[bool].connect(
            self.mapWidget.setMouseClickCoordQuery)
        self.mapWidget.coordQueryResult.connect(self.updateCoords)

        self.setCoordsButton = QPushButton()
        self.setCoordsButton.setText('Set coordinates')
        self.setCoordsButton.clicked.connect(self.setCoordsClicked)

        buttonLayout = QHBoxLayout()

        buttonLayout.addWidget(self.captureCoordsButton)
        buttonLayout.addWidget(self.setCoordsButton)

        coordControlLayout = QVBoxLayout()
        coordControlLayout.addLayout(formLayout)
        coordControlLayout.addLayout(buttonLayout)

        widget = QWidget(self)
        layout = QGridLayout()
        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, 0)

        topLayout = QGridLayout()
        bottomLayout = QGridLayout()

        topLayout.setColumnStretch(0, 0)
        topLayout.setColumnStretch(1, 1)

        bottomLayout.setColumnStretch(0, 0)
        bottomLayout.setColumnStretch(1, 1)

        topLayout.addWidget(self.slider, 0, 0)
        topLayout.addWidget(self.view, 0, 1)

        bottomLayout.addLayout(mapControlLayout, 0, 0)
        bottomLayout.addLayout(coordControlLayout, 0, 1)

        layout.addLayout(topLayout, 0, 0)
        layout.addLayout(bottomLayout, 1, 0)

        self.layout = layout
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)

        self.view.customContextMenuRequested.connect(
            self.customContextMenuRequest)
示例#48
0
class RenderPropWidget(QWidget):
    """
	RenderPropWidget is a widget that is displayed under the render widgets. It
	contains a tabwidget in which information of the data can be displayed and
	in which visualization parameters can be shown. One of the tabs is a
	RenderParameterWidget object.
	"""
    def __init__(self, renderController, parent=None):
        super(RenderPropWidget, self).__init__(parent=parent)

        # Three tabs: Visualization, data info and slices
        self.visParamTabWidget = RenderParameterWidget(renderController)
        self.dataInfoTabWidget = RenderInfoWidget()
        self.slicesTabWidget = RenderSlicerParamWidget(renderController)

        # Create the load dataset widget
        self.loadDataWidget = QWidget()
        self.loadDataButton = QPushButton()
        self.loadDataButton.setText("Load a dataset")

        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(self.loadDataButton)
        self.loadDataWidget.setLayout(layout)

        # Create the tab widget
        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.visParamTabWidget, "Visualization")
        self.tabWidget.addTab(self.slicesTabWidget, "Slices")
        self.tabWidget.addTab(self.dataInfoTabWidget, "Data info")

        self.currentTabIndex = 0
        self.extraTabWidget = None
        self.tabWidget.currentChanged.connect(self.tabIndexChanged)

        layout = QVBoxLayout()
        layout.addWidget(self.loadDataWidget)
        self.setLayout(layout)

    def setFileChangedSignal(self, signal):
        """
		:param signal: Signal that is connected to some file-loading slots.
		:type signal: SIGNAL
		"""
        self.signal = signal
        self.signal.connect(self.setFile)
        self.signal.connect(self.dataInfoTabWidget.setFile)

    def setLoadDataSlot(self, slot):
        """
		The button is connected to the given slot. The slot action should load
		a dataset from disk.

		:type slot: Slot
		"""
        self.loadDataButton.clicked.connect(slot)

    @Slot(basestring)
    def setFile(self, fileName):
        """
		When a file is loaded, the 'load data' button is removed from the widget
		and the actual tabs with parameters are put on screen.
		"""
        layout = self.layout()
        if fileName is None:
            if layout.indexOf(self.tabWidget) != -1:
                # Remove the parameter widgets
                layout.removeWidget(self.tabWidget)
                self.tabWidget.setParent(None)
                # Show the load data button
                layout.addWidget(self.loadDataWidget)
                self.setLayout(layout)
        else:
            if layout.indexOf(self.loadDataWidget) != -1:
                # Remove the load data button
                layout.removeWidget(self.loadDataWidget)
                self.loadDataWidget.setParent(None)
                # Add the parameter widgets
                layout.addWidget(self.tabWidget)
                self.setLayout(layout)

    @Slot(int)
    def tabIndexChanged(self, index):
        transformIndex = self.tabWidget.indexOf(self.extraTabWidget)
        if index != transformIndex:
            self.currentTabIndex = index

    def addTabWidget(self, widget, name):
        self.extraTabWidget = widget
        self.tabWidget.addTab(widget, name)
        self.tabWidget.setCurrentWidget(self.extraTabWidget)

    def removeTabWidget(self):
        if self.extraTabWidget is None:
            return

        index = self.tabWidget.indexOf(self.extraTabWidget)
        if index >= 0:
            # Restore the last tab index that wasn't the transform tab
            self.tabWidget.setCurrentIndex(self.currentTabIndex)
            self.tabWidget.removeTab(index)

        self.extraTabWidget = None
示例#49
0
class Ui_MainView(QMainWindow):

    gui_methods_sig = Signal(int, )

    def __init__(self, ):
        super(Ui_MainView, self).__init__()

        self.output_folder = os.getcwd()
        self.usr = ''
        self.psw = ''

        self.save_username_checked = False

        self.right_base_layout_v = QtGui.QVBoxLayout()
        self.msgBox = QtGui.QMessageBox()

        self.validations = validate_inputs.validate_controls(
            self
        )  # instance for input validations  and we are passing self to validate class for model updations

    def gifUI(self, gui_slate):

        self.gui = gui_slate
        self.gif_widget = QWidget()
        self.gif_layout = QVBoxLayout()

        self.movie_screen = QLabel()
        self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Expanding)
        self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        self.gif_layout.addWidget(self.movie_screen)

        ag_file = "GIF-180704_103026.gif"

        self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(),
                                  self.gif_widget)
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie.setSpeed(75)
        self.movie_screen.setMovie(self.movie)
        #         self.movie_screen.setFixedWidth(500)

        self.gif_widget.setLayout(self.gif_layout)
        self.gui.setCentralWidget(self.gif_widget)
        #         self.gui.addDockWidget(self.gif_widget)
        self.movie.start()
        #         self.movie.setPaused(True)
        self.gif_widget.show()
#         time.sleep(2)
#         self.movie.stop()

    def setupUi(self, gui_slate):

        self.gui = gui_slate
        self.gui.get_option_selected = False
        self.gui.push_option_selected = False
        self.gui.extract_opt_selected = False
        self.gui.compare_opt_selected = False

        #Outer most Main Layout

        self.widget = QWidget()
        self.widget.setMinimumSize(850, 600)

        self.main_layout_h = QHBoxLayout()
        self.main_layout_h.setAlignment(QtCore.Qt.AlignTop)

        self.widget.setLayout(self.main_layout_h)

        self.gui.setCentralWidget(self.widget)

        self.left_base_widget = QWidget()
        #         self.left_base_widget.setMaximumWidth(600)
        #         self.left_base_widget.setMinimumWidth(450)
        #         self.left_base_widget.setMaximumHeight(700)

        self.right_base_widget = QWidget()

        #3 Sub main Layouts

        self.left_base_layout_v = QVBoxLayout()
        #         self.right_base_layout_v = QVBoxLayout()
        self.corner_logo_layout_v = QVBoxLayout()
        self.left_base_layout_v.setAlignment(QtCore.Qt.AlignTop)

        self.right_base_layout_v.setAlignment(QtCore.Qt.AlignTop)

        #Added Widgets and layouts to the outermost layout

        self.main_layout_h.addWidget(self.left_base_widget)
        self.main_layout_h.addWidget(self.right_base_widget)
        self.main_layout_h.addLayout(self.corner_logo_layout_v)

        #         , QtGui.QFont.Normal
        self.grp_heading_font = QtGui.QFont("Verdana", 10)
        self.grp_heading_font.setItalic(True)

        #Radio buttons layout

        self.radio_groupBox = QtGui.QGroupBox()
        self.radio_option_layout_lb_h = QHBoxLayout()

        self.radio_groupBox.setLayout(self.radio_option_layout_lb_h)

        self.radio_groupBox.setMinimumWidth(450)
        self.left_base_layout_v.addWidget(self.radio_groupBox)

        #Credentials layouts

        self.credentials_groupbox = QtGui.QGroupBox("GTAC Credentials")
        self.credentials_groupbox.setFont(self.grp_heading_font)
        self.credentials_layout_lb_v = QVBoxLayout()

        self.username_layout_lb_h = QHBoxLayout()
        self.password_layout_lb_h = QHBoxLayout()
        self.cr_layout_lb_h = QHBoxLayout()
        self.password_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)
        self.credentials_layout_lb_v.addLayout(self.username_layout_lb_h)
        self.credentials_layout_lb_v.addLayout(self.password_layout_lb_h)
        self.credentials_layout_lb_v.addLayout(self.cr_layout_lb_h)

        self.credentials_groupbox.setLayout(self.credentials_layout_lb_v)
        self.left_base_layout_v.addWidget(self.credentials_groupbox)
        self.credentials_groupbox.setAlignment(QtCore.Qt.AlignLeft)
        self.credentials_groupbox.hide()

        #IP group box layouts

        self.IP_groupBox = QtGui.QGroupBox("IP Inputs")
        self.IP_groupBox.setFont(self.grp_heading_font)
        self.ip_file_layout_lb_v = QVBoxLayout()

        self.ip_file_select_layout_lb_h = QHBoxLayout()
        self.ip_file_select_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)
        self.ip_file_layout_lb_v.addLayout(self.ip_file_select_layout_lb_h)

        self.IP_groupBox.setMaximumHeight(135)
        self.IP_groupBox.setLayout(self.ip_file_layout_lb_v)
        self.left_base_layout_v.addWidget(self.IP_groupBox)

        self.IP_groupBox.hide()

        # Commands  group box selection

        self.Commands_groupBox = QtGui.QGroupBox("Commands Inputs")
        self.Commands_groupBox.setFont(self.grp_heading_font)
        self.commands_label_layout_lb_v = QVBoxLayout()

        self.default_chkbx_layout_lb_h = QHBoxLayout()
        self.commands_file_layout_lb_h = QHBoxLayout()
        self.commands_file_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)
        self.commands_custom_box_layout_lb_h = QHBoxLayout()
        self.none_radio_btn_layout_lb_h = QHBoxLayout()

        self.commands_label_layout_lb_v.addLayout(
            self.default_chkbx_layout_lb_h)
        self.commands_label_layout_lb_v.addLayout(
            self.commands_file_layout_lb_h)
        self.commands_label_layout_lb_v.addLayout(
            self.commands_custom_box_layout_lb_h)
        self.commands_label_layout_lb_v.addLayout(
            self.none_radio_btn_layout_lb_h)

        self.Commands_groupBox.setMaximumHeight(225)
        self.Commands_groupBox.setAlignment(QtCore.Qt.AlignLeft)
        self.Commands_groupBox.setLayout(self.commands_label_layout_lb_v)
        self.left_base_layout_v.addWidget(self.Commands_groupBox)

        self.Commands_groupBox.hide()

        # results group box

        self.results_groupBox = QtGui.QGroupBox("Results")
        self.results_groupBox.setFont(self.grp_heading_font)
        self.results_layout_lb_v = QVBoxLayout()

        self.output_layout_lb_h = QHBoxLayout()
        self.output_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)

        self.results_layout_lb_v.addLayout(self.output_layout_lb_h)

        self.results_groupBox.setLayout(self.results_layout_lb_v)
        self.left_base_layout_v.addWidget(self.results_groupBox)

        self.results_groupBox.hide()

        # Go Button

        self.go_btn_layout_lb_h = QHBoxLayout()
        self.left_base_layout_v.addLayout(self.go_btn_layout_lb_h)

        # Right and Left Widget on individual layouts

        self.left_base_widget.setLayout(self.left_base_layout_v)
        self.right_base_widget.setLayout(self.right_base_layout_v)

        #### just to see right base layout

        self.right_base = QtGui.QTextEdit(self.gui)
        self.right_base.setStyleSheet(
            """QToolTip { background-color: #00bfff; color: black; border: black solid 2px  }"""
        )
        self.right_base.setObjectName("IP_Address")
        self.right_base_layout_v.addWidget(self.right_base)
        #         self.right_base.setMaximumHeight(500)
        self.right_base.hide()

        self.snap_gif = QtGui.QLabel(self.gui)
        self.snap_gif.setText("")
        self.snap_gif.setStyleSheet("background-color: None")
        self.snap_gif.setPixmap(QtGui.QPixmap("Capture.png"))
        self.snap_gif.setObjectName("logo_corner")
        self.right_base_layout_v.addWidget(self.snap_gif)

        ######

        self.gui.setWindowTitle('SPEED +  3.0')
        self.gui.setWindowIcon(QtGui.QIcon(":/logo/Wind_icon.png"))
        self.gui.setAutoFillBackground(True)

        self.corner_logolabel = QtGui.QLabel(self.gui)
        self.corner_logolabel.setText("")
        self.corner_logolabel.setStyleSheet("background-color: None")
        self.corner_logolabel.setPixmap(QtGui.QPixmap(":/logo/ATT-LOGO-2.png"))
        self.corner_logolabel.setObjectName("logo_corner")
        #         self.corner_logo_layout_v.setAlignment(QtCore.Qt.AlignTop)
        self.corner_logo_layout_v.setAlignment(
            int(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight))
        self.corner_logo_layout_v.addWidget(self.corner_logolabel)

        self.msgBox.setWindowIcon(QtGui.QIcon(":/logo/Wind_icon.png"))
        self.msgBox.setFont(QtGui.QFont("Verdana", 8, QtGui.QFont.Normal))
        self.make_menu()
        ## gif at&t logo
        #         self.movie_screen = QLabel()
        #         self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        #         self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        #         self.right_base_layout_v.addWidget(self.movie_screen)
        #
        #         ag_file = "C:/Users/rg012f/eclipse-workspace/poojan_try/giphy.gif"
        #         self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), None)
        #         self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        #         self.movie.setSpeed(75)
        #         self.movie_screen.setMovie(self.movie)
        #
        #
        #         self.movie.setPaused(True)
        #         self.movie.start()
        #         self.right_base_widget.show()
        #         time.sleep(2)

        ######################### order of the below funtion calls is importnant change them wisely#####################
        self.check_save_username()
        self.create_views()
        self.left_radio_controls()
        self.connect_child_views()

    def make_menu(self):
        self.myMenu = self.gui.menuBar()

        self.file = self.myMenu.addMenu('&File')

        self.file.addAction("&Select Output Folder...",
                            self.select_destination, "Ctrl+O")
        self.file.addAction("&Exit", self.closewindow, "Ctrl+X")

        self.file = self.myMenu.addMenu('&Help')

        self.file.addAction("&About...", self.about_tool, "Ctrl+H")

    def check_save_username(self):
        print("Yo reached save username")
        try:
            f = open('Username.txt', 'r')
            lines = f.readlines()
            if len(lines):
                self.save_username_checked = True
            else:
                self.save_username_checked = False
        except Exception as ex:
            print(ex)

    def select_destination(self, ):

        fld = QtGui.QFileDialog.getExistingDirectory(self.gui,
                                                     'Select Output Folder')
        self.output_folder = str(fld)

    def closewindow(self):
        self.gui.close()

    def about_tool(self):
        abouttool = "Speed + v3.0 \n\nThis tool is useful to fetch, push, extract, compare device configs \n"

        self.msgBox.setText(abouttool)
        self.msgBox.setWindowTitle("About Speed +")
        self.msgBox.show()

    def left_radio_controls(self):

        # ============================    main radio options selection :
        radio_font = QtGui.QFont("Verdana", 10, QtGui.QFont.Normal)

        self.get_radio_option = QtGui.QRadioButton(self.gui)
        self.get_radio_option.setFont(radio_font)
        self.get_radio_option.setText("Get")
        self.radio_option_layout_lb_h.addWidget(self.get_radio_option)

        self.push_radio_option = QtGui.QRadioButton(self.gui)
        self.push_radio_option.setFont(radio_font)
        self.push_radio_option.setText("Push")
        self.radio_option_layout_lb_h.addWidget(self.push_radio_option)

        self.extract_radio_option = QtGui.QRadioButton(self.gui)
        self.extract_radio_option.setFont(radio_font)
        self.extract_radio_option.setText("Extract")
        self.radio_option_layout_lb_h.addWidget(self.extract_radio_option)

        self.compare_radio_option = QtGui.QRadioButton(self.gui)
        self.compare_radio_option.setFont(radio_font)
        self.compare_radio_option.setText("Compare")
        self.radio_option_layout_lb_h.addWidget(self.compare_radio_option)

    def disp_get_options(self):

        self.snap_gif.show()
        self.push_view.hide_push()
        self.excel_view.userOptionextract.hide()
        self.compare_view.main_widget.hide()
        self.get_view.display_get()

    def disp_push_options(self):

        self.snap_gif.show()
        self.get_view.hide_get()
        self.excel_view.userOptionextract.hide()
        self.compare_view.main_widget.hide()
        self.push_view.display_push()
        self.validations.hide_right_common()

    def disp_ext_options(self):

        self.get_view.hide_get()
        self.push_view.hide_push()
        self.compare_view.main_widget.hide()
        self.excel_view.display_excel_portion()
        self.validations.hide_right_common()

    def disp_comp_options(self):

        self.get_view.hide_get()
        self.push_view.hide_push()
        self.excel_view.userOptionextract.hide()
        self.compare_view.display_comapre_portion()
        self.validations.hide_right_common()

    def connect_child_views(self):

        self.get_radio_option.clicked.connect(self.disp_get_options)
        self.push_radio_option.clicked.connect(self.disp_push_options)
        self.extract_radio_option.clicked.connect(self.disp_ext_options)
        self.compare_radio_option.clicked.connect(self.disp_comp_options)

        self.base_left.go_button.clicked.connect(self.connect_validate_option)

    def connect_validate_option(self):

        self.validations.validate_user_inputs(
        )  # passing self to validation class method , other end this self is last_parent

    def create_views(self):

        self.base_left = left_base(
            self
        )  # we are passing main GUI and also local self as 'last_parent' to left base view to update variables

        self.get_view = get_controls(self.gui, self.base_left)
        self.push_view = push_controls(self.gui, self.base_left)
        self.excel_view = extract_excel(self.gui, self.base_left)
        self.compare_view = compare_op_results(self)

    def show_gif_right_base(self, path, layout):
        print("ui parent view show_gif_right_base line 394")
        self.movie_screen = QLabel()
        self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Expanding)
        self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        layout.addWidget(self.movie_screen)

        ag_file = path
        self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), None)
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie.setSpeed(75)
        self.movie_screen.setMovie(self.movie)

        #"C:/Users/rg012f/eclipse-workspace/poojan_try/giphy.gif"
        self.movie.setPaused(True)
        self.movie.start()
#         self.right_base_widget.setLayout(layout)
#         self.right_base_widget.show()

    def hide_gif_right_base(self):
        self.movie_screen.hide()
示例#50
0
  def initUI(self):
    '''
    Method to setup the buttons/entries of the Gui
    '''
    self.dateFrame    = dateFrame( );                                           # Initialize the dateFrame
    self.iopLabel     = QLabel('IOP Number');                                   # Initialize Entry widget for the IOP name
    self.iopName      = QLineEdit();                                            # Initialize Entry widget for the IOP name
    self.stationLabel = QLabel('Station Name');                                 # Initialize Entry widget for the IOP name
    self.stationName  = QLineEdit();                                            # Initialize Entry widget for the IOP name
    self.sourceButton = QPushButton('Source Directory');                        # Initialize button for selecting the source directory
    self.destButton   = QPushButton('Destination Directory');                   # Initialize button for selecting the destination directory
    self.sourcePath   = QLineEdit('');                                          # Initialize entry widget that will display the source directory path
    self.destPath     = QLineEdit('');                                          # Initialize entry widget that will display the destination directory path
    self.sourceSet    = indicator();                                            # Initialize an indictor that will appear when the source path is set
    self.destSet      = indicator();                                            # Initialize an indictor that will appear when the destination path is set
    
    self.sourcePath.setEnabled( False );                                        # Disable the sourcePath widget; that way no one can manually edit it
    self.destPath.setEnabled(   False );                                        # Disable the destPath widget; that way no one can manually edit it

    self.sourcePath.hide();                                                     # Hide the source directory path
    self.destPath.hide();                                                       # Hide the destination directory path
    self.sourceSet.hide();                                                      # Hide the source directory indicator
    self.destSet.hide();                                                        # Hide the destination directory indicator

    self.sourceButton.clicked.connect( self.select_source );                    # Set method to run when the source button is clicked 
    self.destButton.clicked.connect(   self.select_dest   );                    # Set method to run when the destination button is clicked

    self.copyButton = QPushButton( 'Copy Files' );                              # Create 'Copy Files' button
    self.copyButton.clicked.connect( self.copy_files );                         # Set method to run when 'Copy Files' button is clicked
    self.copyButton.setEnabled(False);                                          # Set enabled state to False; cannot click until after the source and destination directories set
    self.copySucces = indicator();                                              # Initialize an indictor that will appear when the copy complete successfuly
    self.copySucces.hide();

    self.procButton = QPushButton( 'Process Files' );                           # Create 'Process Files' button
    self.procButton.clicked.connect( self.proc_files );                         # Set method to run when 'Process Files' button is clicked
    self.procButton.setEnabled(False);                                          # Set enabled state to False; cannot click until after 'Copy Files' completes
    self.procSucces = indicator();                                              # Initialize an indictor that will appear when the processing complete successfuly
    self.procSucces.hide();

    self.genButton = QPushButton( 'Generate Sounding' );                        # Create 'Generate Sounding' button
    self.genButton.clicked.connect( self.gen_sounding );                        # Set method to run when 'Generate Sounding' button is clicked
    self.genButton.setEnabled(False);                                           # Set enabled state to False; cannot click until after 'Process Files' completes
    self.genSucces = indicator();                                               # Initialize an indictor that will appear when the sounding generation complete successfuly
    self.genSucces.hide();

    self.uploadButton = QPushButton( 'FTP Upload' );                            # Create 'FTP Upload' button
    self.uploadButton.clicked.connect( self.ftp_upload );                       # Set method to run when 'FTP Upload' button is clicked
    self.uploadButton.setEnabled(False);                                        # Set enabled state to False; cannot click until after 'Generate Sounding' completes
    self.uploadSucces = indicator();                                            # Initialize an indictor that will appear when the ftp upload complete successfuly
    self.uploadSucces.hide();

    self.checkButton = QPushButton( 'Check website' );                          # Create 'Check website' button
    self.checkButton.clicked.connect( self.check_site );                        # Set method to run when 'Check website' button is clicked
    self.checkButton.setEnabled(False);                                         # Set enabled state to False; cannot click until after 'FTP Upload' completes

    self.resetButton = QPushButton( 'Reset' );                                  # Create 'Check website' button
    self.resetButton.clicked.connect( self.reset_values );                      # Set method to run when 'Check website' button is clicked
    
    versionLabel = QLabel( 'version: {}'.format(__version__) );                 # Version label
    versionLabel.setAlignment( Qt.AlignHCenter );                               # Set alignment to center
    log_handler  = QLogger( );                                                  # Initialize a QLogger logging.Handler object
    logging.getLogger('Meso1819').addHandler( log_handler );                    # Get the Meso1819 root logger and add the handler to it

    grid = QGridLayout();                                                       # Initialize grid layout
    grid.setSpacing(10);                                                        # Set spacing to 10
    for i in range(4): 
      grid.setColumnStretch(i,  0);                                             # Set column stretch for ith column
      grid.setColumnMinimumWidth(i,  60);                                       # Set column min width for ith column
    grid.setColumnStretch(4,  0);                                               # Set column stretch for 5th column
    grid.setColumnMinimumWidth(4,  20);                                         # Set column min width for 5th column

    grid.setRowStretch(1,  0);                                                  # Set column stretch for 5th column
    grid.setRowStretch(3,  0);                                                  # Set column stretch for 5th column
    grid.setRowMinimumHeight(1,  25);                                           # Set column min width for 5th column
    grid.setRowMinimumHeight(3,  25);                                           # Set column min width for 5th column
    
    grid.addWidget( self.sourceButton,  0, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.sourceSet,     0, 4, 1, 1 );                           # Place a widget in the grid
    grid.addWidget( self.sourcePath,    1, 0, 1, 5 );                           # Place a widget in the grid

    grid.addWidget( self.destButton,    2, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.destSet,       2, 4, 1, 1 );                           # Place a widget in the grid
    grid.addWidget( self.destPath,      3, 0, 1, 5 );                           # Place a widget in the grid

    grid.addWidget( self.iopLabel,      4, 0, 1, 2 );                           # Place a widget in the grid
    grid.addWidget( self.iopName,       5, 0, 1, 2 );                           # Place a widget in the grid

    grid.addWidget( self.stationLabel,  4, 2, 1, 2 );                           # Place a widget in the grid
    grid.addWidget( self.stationName,   5, 2, 1, 2 );                           # Place a widget in the grid

    grid.addWidget( self.dateFrame,     6, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.copyButton,    7, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.copySucces,    7, 4, 1, 1 );                           # Place a widget in the grid
    grid.addWidget( self.procButton,    8, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.procSucces,    8, 4, 1, 1 );                           # Place a widget in the grid
    grid.addWidget( self.genButton,     9, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.genSucces,     9, 4, 1, 1 );                           # Place a widget in the grid
    grid.addWidget( self.uploadButton, 10, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.uploadSucces, 10, 4, 1, 1 );                           # Place a widget in the grid
    grid.addWidget( self.checkButton,  11, 0, 1, 4 );                           # Place a widget in the grid
    grid.addWidget( self.resetButton,  12, 0, 1, 4 );                           # Place a widget in the grid

    grid.addWidget( log_handler.frame, 0, 6, 13, 1);
    grid.addWidget( versionLabel, 20, 0, 1, 7)
    centralWidget = QWidget();                                                  # Create a main widget
    centralWidget.setLayout( grid );                                            # Set the main widget's layout to the grid
    self.setCentralWidget(centralWidget);                                       # Set the central widget of the base class to the main widget
    
    self.show( );                                                               # Show the main widget
示例#51
0
 def initLayout(self):
     layout = QGridLayout()
     layout.addWidget(self.tabWidget)
     centralWidget = QWidget()
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
示例#52
0
class DeviceList(QScrollArea):
    def __init__(self, programming_handler, info_handler, reset_handler):
        super(DeviceList, self).__init__()

        self.deviceWidgets = []
        self.programming_handler = programming_handler
        self.info_handler = info_handler
        self.reset_handler = reset_handler
        self.updateCounter = 0

        self.initUI()

    def initUI(self):
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        self.listWidget = QWidget()
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.listWidget.setLayout(self.layout)
        self.setWidgetResizable(True)

        self.setWidget(self.listWidget)

        self.updateList()

    # def updateLabels(self):
    #     for dev in self.deviceWidgets:
    #         dev.updateLabels()

    def updateList(self):
        self.updateCounter += 1

        deviceInfoList = list(
            filter(is_supported_device,
                   easyhid.Enumeration().find()))

        deleteList = []
        deviceIds = [dev.path for dev in deviceInfoList]
        oldDevices = []
        newDevices = []

        # look at the list of connected devices and find out which devices are
        # no longer connected and remove them
        i = 0
        while i < self.layout.count():
            devItem = self.layout.itemAt(i).widget()
            if hasattr(devItem, "device") and (devItem.device.path
                                               in deviceIds):
                oldDevices.append(devItem.device)
                i += 1
            else:
                self.layout.takeAt(i).widget().deleteLater()

        # Now find the list of new devices
        oldDeviceIds = [dev.path for dev in oldDevices]
        for dev in deviceInfoList:
            if dev.path in oldDeviceIds:
                continue
            else:
                newDevices.append(dev)

        for devInfo in newDevices:
            devWidget = DeviceWidget(devInfo)
            if devWidget.label:
                self.deviceWidgets.append(devWidget)
                self.layout.addWidget(devWidget)
                devWidget.program.connect(self.programming_handler)
                devWidget.show_info.connect(self.info_handler)
                devWidget.reset.connect(self.reset_handler)

        # if len(self.deviceWidgets) == 0:
        if len(oldDevices) == 0 and len(newDevices) == 0:
            n = self.updateCounter % 4
            label = QLabel("Scanning for devices" + "." * n + " " * (4 - n))
            self.layout.setAlignment(Qt.AlignCenter)
            self.layout.addWidget(label)
            self.deviceWidgets = []
        else:
            self.layout.setAlignment(Qt.AlignTop)
            self.updateCounter = 0
示例#53
0
class RobocompDslGui(QMainWindow):
    def __init__(self, parent=None):
        super(RobocompDslGui, self).__init__(parent)
        self.setWindowTitle("Create new component")
        # self._idsl_paths = []
        self._communications = {
            "implements": [],
            "requires": [],
            "subscribesTo": [],
            "publishes": []
        }
        self._interfaces = {}
        self._cdsl_doc = CDSLDocument()
        self._command_process = QProcess()

        self._main_widget = QWidget()
        self._main_layout = QVBoxLayout()
        self.setCentralWidget(self._main_widget)

        self._name_layout = QHBoxLayout()
        self._name_line_edit = QLineEdit()
        self._name_line_edit.textEdited.connect(self.update_component_name)
        self._name_line_edit.setPlaceholderText("New component name")
        self._name_layout.addWidget(self._name_line_edit)
        self._name_layout.addStretch()

        # DIRECTORY SELECTION
        self._dir_line_edit = QLineEdit()
        # self._dir_line_edit.textEdited.connect(self.update_completer)
        self._dir_completer = QCompleter()
        self._dir_completer_model = QFileSystemModel()
        if os.path.isdir(ROBOCOMP_COMP_DIR):
            self._dir_line_edit.setText(ROBOCOMP_COMP_DIR)
            self._dir_completer_model.setRootPath(ROBOCOMP_COMP_DIR)
        self._dir_completer.setModel(self._dir_completer_model)
        self._dir_line_edit.setCompleter(self._dir_completer)

        self._dir_button = QPushButton("Select directory")
        self._dir_button.clicked.connect(self.set_output_directory)
        self._dir_layout = QHBoxLayout()
        self._dir_layout.addWidget(self._dir_line_edit)
        self._dir_layout.addWidget(self._dir_button)

        # LIST OF ROBOCOMP INTERFACES
        self._interface_list = QListWidget()
        self._interface_list.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self._interface_list.itemSelectionChanged.connect(
            self.set_comunication)

        # LIST OF CONNECTION TyPES
        self._type_combo_box = QComboBox()
        self._type_combo_box.addItems(
            ["publishes", "implements", "subscribesTo", "requires"])
        self._type_combo_box.currentIndexChanged.connect(
            self.reselect_existing)

        # BUTTON TO ADD A NEW CONNECTION
        # self._add_connection_button = QPushButton("Add")
        # self._add_connection_button.clicked.connect(self.add_new_comunication)
        self._add_connection_layout = QHBoxLayout()
        # self._add_connection_layout.addWidget(self._add_connection_button)
        self._language_combo_box = QComboBox()
        self._language_combo_box.addItems(["Python", "Cpp", "Cpp11"])
        self._language_combo_box.currentIndexChanged.connect(
            self.update_language)
        self._add_connection_layout.addWidget(self._language_combo_box)
        self._add_connection_layout.addStretch()
        self._gui_check_box = QCheckBox()
        self._gui_check_box.stateChanged.connect(self.update_gui_selection)
        self._gui_label = QLabel("Use Qt GUI")
        self._add_connection_layout.addWidget(self._gui_label)
        self._add_connection_layout.addWidget(self._gui_check_box)

        # WIDGET CONTAINING INTERFACES AND TYPES
        self._selection_layout = QVBoxLayout()
        self._selection_layout.addWidget(self._type_combo_box)
        self._selection_layout.addWidget(self._interface_list)
        self._selection_layout.addLayout(self._add_connection_layout)
        self._selection_widget = QWidget()
        self._selection_widget.setLayout(self._selection_layout)

        # TEXT EDITOR WITH THE RESULTING CDSL CODE
        self._editor = QTextEdit(self)
        self._editor.setHtml("")

        self._document = self._editor.document()
        self._component_directory = None

        # SPLITTER WITH THE SELECTION AND THE CODE
        self._body_splitter = QSplitter(Qt.Horizontal)
        self._body_splitter.addWidget(self._selection_widget)
        self._body_splitter.addWidget(self._editor)
        self._body_splitter.setStretchFactor(0, 2)
        self._body_splitter.setStretchFactor(1, 9)

        # CREATION BUTTONS
        self._create_button = QPushButton("Create .cdsl")
        self._create_button.clicked.connect(self.write_cdsl_file)
        self._creation_layout = QHBoxLayout()
        self._creation_layout.addStretch()
        self._creation_layout.addWidget(self._create_button)

        self._console = QConsole()
        self._command_process.readyReadStandardOutput.connect(
            self._console.standard_output)
        self._command_process.readyReadStandardError.connect(
            self._console.error_output)

        # ADDING WIDGETS TO MAIN LAYOUT
        self._main_widget.setLayout(self._main_layout)
        self._main_layout.addLayout(self._name_layout)
        self._main_layout.addLayout(self._dir_layout)
        self._main_layout.addWidget(self._body_splitter)
        self._main_layout.addLayout(self._creation_layout)
        self._main_layout.addWidget(self._console)
        self.setMinimumSize(800, 500)
        self._editor.setText(self._cdsl_doc.generate_doc())

    # self.editor->show();

    # def update_completer(self, path):
    # 	print "update_completer %s"%path
    # 	info = QFileInfo(path)
    # 	if info.exists() and info.isDir():
    # 			if not path.endswith(os.path.pathsep):
    # 				new_path = os.path.join(path, os.sep)
    # 				# self._dir_line_edit.setText(new_path)
    # 			all_dirs_output = [dI for dI in os.listdir(path) if os.path.isdir(os.path.join(path, dI))]
    # 			print all_dirs_output
    # 			self._dir_completer.complete()

    def load_idsl_files(self, fullpath=None):
        if fullpath is None:
            fullpath = ROBOCOMP_INTERFACES
        idsls_dir = os.path.join(ROBOCOMP_INTERFACES, "IDSLs")
        if os.path.isdir(idsls_dir):
            for full_filename in os.listdir(idsls_dir):
                file_name, file_extension = os.path.splitext(full_filename)
                if "idsl" in file_extension.lower():
                    full_idsl_path = os.path.join(idsls_dir, full_filename)
                    # self._idsl_paths.append(os.path.join(idsls_dir,full_filename))
                    self.parse_idsl_file(full_idsl_path)
        self._interface_list.addItems(self._interfaces.keys())

    def parse_idsl_file(self, fullpath):

        with open(fullpath, 'r') as fin:
            interface_name = None
            for line in fin:
                result = re.findall(r'^\s*interface\s+(\w+)\s*\{?\s*$',
                                    line,
                                    flags=re.MULTILINE)
                if len(result) > 0:
                    interface_name = result[0]
            print("%s for idsl %s" % (interface_name, fullpath))
            if interface_name is not None:
                self._interfaces[interface_name] = fullpath

    def add_new_comunication(self):
        interface_names = self._interface_list.selectedItems()
        com_type = str(self._type_combo_box.currentText())
        for iface_name_item in interface_names:
            iface_name = str(iface_name_item.text())
            self._communications[com_type].append(iface_name)
            idsl_full_path = self._interfaces[iface_name]
            idsl_full_filename = os.path.basename(idsl_full_path)
            self._cdsl_doc.add_comunication(com_type, iface_name)
            self._cdsl_doc.add_import(idsl_full_filename)
        self.update_editor()

    def set_comunication(self):
        interface_names = self._interface_list.selectedItems()
        com_type = str(self._type_combo_box.currentText())
        self._communications[com_type] = []
        self._cdsl_doc.clear_comunication(com_type)
        for iface_name_item in interface_names:
            iface_name = str(iface_name_item.text())
            self._communications[com_type].append(iface_name)
            self._cdsl_doc.add_comunication(com_type, iface_name)
        self.update_imports()
        self.update_editor()

    def update_imports(self):
        self._cdsl_doc.clear_imports()
        for com_type in self._communications:
            for iface_name in self._communications[com_type]:
                idsl_full_path = self._interfaces[iface_name]
                idsl_full_filename = os.path.basename(idsl_full_path)
                self._cdsl_doc.add_import(idsl_full_filename)

    def update_language(self):
        language = self._language_combo_box.currentText()
        self._cdsl_doc.set_language(str(language))
        self.update_editor()

    def update_gui_selection(self):
        checked = self._gui_check_box.isChecked()
        if checked:
            self._cdsl_doc.set_qui(True)
        else:
            self._cdsl_doc.set_qui(False)
        self.update_editor()

    def update_component_name(self, name):
        self._cdsl_doc.set_name(name)
        self.update_editor()

    def update_editor(self):
        self._editor.setText(self._cdsl_doc.generate_doc())

    def set_output_directory(self):
        dir_set = False
        while not dir_set:
            dir = QFileDialog.getExistingDirectory(
                self, "Select Directory", ROBOCOMP_COMP_DIR,
                QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
            if self.check_dir_is_empty(str(dir)):
                self._dir_line_edit.setText(dir)
                dir_set = True

    def write_cdsl_file(self):
        component_dir = str(self._dir_line_edit.text())
        text = self._cdsl_doc.generate_doc()
        if not self._name_line_edit.text():
            component_name, ok = QInputDialog.getText(self,
                                                      'No component name set',
                                                      'Enter component name:')
            if ok:
                self.update_component_name(component_name)
                self._name_line_edit.setText(component_name)
            else:
                return False

        if not os.path.exists(component_dir):
            if QMessageBox.Yes == QMessageBox.question(
                    self, "Directory doesn't exist.",
                    "Do you want create the directory %s?" % component_dir,
                    QMessageBox.Yes | QMessageBox.No):
                os.makedirs(component_dir)
            else:
                QMessageBox.question(
                    self, "Directory not exist",
                    "Can't create a component witout a valid directory")
                return False

        file_path = os.path.join(component_dir,
                                 str(self._name_line_edit.text()) + ".cdsl")
        if os.path.exists(file_path):
            if QMessageBox.No == QMessageBox.question(
                    self, "File already exists", "Do you want to overwrite?",
                    QMessageBox.Yes | QMessageBox.No):
                return False

        with open(file_path, 'w') as the_file:
            the_file.write(text)
        self.execute_robocomp_cdsl()
        return True

    def execute_robocomp_cdsl(self):
        cdsl_file_path = os.path.join(
            str(self._dir_line_edit.text()),
            str(self._name_line_edit.text()) + ".cdsl")
        command = "python -u %s/robocompdsl.py %s %s" % (
            ROBOCOMPDSL_DIR, cdsl_file_path,
            os.path.join(str(self._dir_line_edit.text())))
        self._console.append_custom_text("%s\n" % command)
        self._command_process.start(command,
                                    QProcess.Unbuffered | QProcess.ReadWrite)

    def reselect_existing(self):
        com_type = self._type_combo_box.currentText()
        selected = self._communications[com_type]
        self._interface_list.clearSelection()
        for iface in selected:
            items = self._interface_list.findItems(iface,
                                                   Qt.MatchFlag.MatchExactly)
            if len(items) > 0:
                item = items[0]
                item.setSelected(True)

    def check_dir_is_empty(self, dir_path):
        if len(os.listdir(dir_path)) > 0:
            msgBox = QMessageBox()
            msgBox.setWindowTitle("Directory not empty")
            msgBox.setText(
                "The selected directory is not empty.\n"
                "For a new Component you usually want a new directory.\n"
                "Do you want to use this directory anyway?")
            msgBox.setStandardButtons(QMessageBox.Yes)
            msgBox.addButton(QMessageBox.No)
            msgBox.setDefaultButton(QMessageBox.No)
            if msgBox.exec_() == QMessageBox.Yes:
                return True
            else:
                return False
        else:
            return True
    def createMainWidget(self):
        """
        TOWRITE

        :return: TOWRITE
        :rtype: `QScrollArea`_
        """
        widget = QWidget(self)

        # Misc
        groupBoxMisc = QGroupBox(self.tr("General Information"), widget)

        labelStitchesTotal = QLabel(self.tr("Total Stitches:"), self)
        labelStitchesReal = QLabel(self.tr("Real Stitches:"), self)
        labelStitchesJump = QLabel(self.tr("Jump Stitches:"), self)
        labelStitchesTrim = QLabel(self.tr("Trim Stitches:"), self)
        labelColorTotal = QLabel(self.tr("Total Colors:"), self)
        labelColorChanges = QLabel(self.tr("Color Changes:"), self)
        labelRectLeft = QLabel(self.tr("Left:"), self)
        labelRectTop = QLabel(self.tr("Top:"), self)
        labelRectRight = QLabel(self.tr("Right:"), self)
        labelRectBottom = QLabel(self.tr("Bottom:"), self)
        labelRectWidth = QLabel(self.tr("Width:"), self)
        labelRectHeight = QLabel(self.tr("Height:"), self)

        fieldStitchesTotal = QLabel(u'%s' % (self.stitchesTotal), self)
        fieldStitchesReal = QLabel(u'%s' % (self.stitchesReal), self)
        fieldStitchesJump = QLabel(u'%s' % (self.stitchesJump), self)
        fieldStitchesTrim = QLabel(u'%s' % (self.stitchesTrim), self)
        fieldColorTotal = QLabel(u'%s' % (self.colorTotal), self)
        fieldColorChanges = QLabel(u'%s' % (self.colorChanges), self)
        fieldRectLeft = QLabel(u'%s' % (str(self.boundingRect.left()) + " mm"),
                               self)
        fieldRectTop = QLabel(u'%s' % (str(self.boundingRect.top()) + " mm"),
                              self)
        fieldRectRight = QLabel(
            u'%s' % (str(self.boundingRect.right()) + " mm"), self)
        fieldRectBottom = QLabel(
            u'%s' % (str(self.boundingRect.bottom()) + " mm"), self)
        fieldRectWidth = QLabel(
            u'%s' % (str(self.boundingRect.width()) + " mm"), self)
        fieldRectHeight = QLabel(
            u'%s' % (str(self.boundingRect.height()) + " mm"), self)

        gridLayoutMisc = QGridLayout(groupBoxMisc)
        gridLayoutMisc.addWidget(labelStitchesTotal, 0, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelStitchesReal, 1, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelStitchesJump, 2, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelStitchesTrim, 3, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelColorTotal, 4, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelColorChanges, 5, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectLeft, 6, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectTop, 7, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectRight, 8, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectBottom, 9, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectWidth, 10, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(labelRectHeight, 11, 0, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesTotal, 0, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesReal, 1, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesJump, 2, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldStitchesTrim, 3, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldColorTotal, 4, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldColorChanges, 5, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectLeft, 6, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectTop, 7, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectRight, 8, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectBottom, 9, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectWidth, 10, 1, Qt.AlignLeft)
        gridLayoutMisc.addWidget(fieldRectHeight, 11, 1, Qt.AlignLeft)
        gridLayoutMisc.setColumnStretch(1, 1)
        groupBoxMisc.setLayout(gridLayoutMisc)

        # TODO: Color Histogram

        # Stitch Distribution
        # groupBoxDist = QGroupBox(self.tr("Stitch Distribution"), widget)

        # TODO: Stitch Distribution Histogram

        # Widget Layout
        vboxLayoutMain = QVBoxLayout(widget)
        vboxLayoutMain.addWidget(groupBoxMisc)
        # vboxLayoutMain.addWidget(groupBoxDist)
        vboxLayoutMain.addStretch(1)
        widget.setLayout(vboxLayoutMain)

        scrollArea = QScrollArea(self)
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(widget)
        return scrollArea
示例#55
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('Tiny BLE Monitor')
        self.resize(800, 500)
        self.cwidget = QWidget()
        self.setCentralWidget(self.cwidget)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.cwidget.setLayout(layout)
        self.pwidget = pg.PlotWidget()
        layout.addWidget(self.pwidget)

        self.pwidget.setTitle(title="press 'space' to freeze/resume")
        self.pwidget.setLabel('left', 'I', units='mA')
        self.pwidget.setLabel('bottom', 't')
        self.pwidget.showButtons()
        self.pwidget.setXRange(0, 3000)
        self.pwidget.setYRange(0, 16)
        # self.pwidget.enableAutoRange(axis=pg.ViewBox.YAxis)
        line = pg.InfiniteLine(pos=1.0, angle=0, movable=True, bounds=[0, 200])
        self.pwidget.addItem(line)
        self.pwidget.showGrid(x=True, y=True, alpha=0.5)
        self.plot = self.pwidget.plot()
        self.plot.setPen((0, 255, 0))

        # plotitem = self.pwidget.getPlotItem()
        # plotitem.setLimits(xMin=-1, yMin=-1, minXRange=-1, minYRange=-1) # require pyqtgraph 0.9.9+

        self.thread = SerialThread()
        self.thread.error.connect(self.handle_error)
        self.thread.start()
        self.freeze = False
        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(50)

    @Slot(int)
    def handle_error(self, error):
        flags = QMessageBox.Abort | QMessageBox.StandardButton.Retry
        message = 'No device available!'
        if error > 1:
            message = 'Failed to read data!'

        result = QMessageBox.critical(self, 'ERROR', message, flags)
        if result == QMessageBox.StandardButton.Retry:
            self.thread.start()
        else:
            self.close()

    def update(self):
        global data, data_index

        if not self.freeze:
            r = self.pwidget.viewRange()
            if data_index >= r[0][1]:
                self.pwidget.setXRange(data_index,
                                       data_index + r[0][1] - r[0][0])
            self.plot.setData(data[:data_index])

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Escape:
            self.pwidget.setXRange(0, data_index + 1000)
            self.pwidget.enableAutoRange(axis=pg.ViewBox.YAxis)
        elif key == Qt.Key_Space:
            self.freeze = not self.freeze

        return True

    def closeEvent(self, event):
        if self.thread.isRunning():
            self.thread.exit = True
            while self.thread.isRunning():
                pass

        event.accept()
示例#56
0
import arrow
from PySide.QtCore import QTimer
from PySide.QtGui import QApplication, QWidget, QHBoxLayout, QFileDialog, QListWidgetItem, QPushButton, QListWidget, \
    QInputDialog

FILENAME_FORMAT = 'YYYY-MM-DD HH-mm-ss'
AUTOSAVE_TIMEOUT = 5*60*1000

app = QApplication(sys.argv)

main_window = QWidget()
main_window.resize(640, 480)
main_window.setWindowTitle('Save manager')

box = QHBoxLayout()
main_window.setLayout(box)


def load_config():
    _config = {}

    if os.path.exists("config.json"):
        with open("config.json") as f:
            _config = json.loads(f.read())

    return _config


config = load_config()

class PointsWidget(QWidget):
	"""
	PointsWidget
	"""

	activeLandmarkChanged = Signal(int)
	landmarkDeleted = Signal(int)

	def __init__(self):
		super(PointsWidget, self).__init__()

		self.landmarkWidgets = []
		self.activeIndex = 0

		self.scrollArea = QScrollArea(self)
		self.scrollArea.setFrameShape(QFrame.NoFrame)
		self.scrollArea.setAutoFillBackground(False)
		self.scrollArea.setAttribute(Qt.WA_TranslucentBackground)
		self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
		self.scrollArea.setWidgetResizable(True)

		landmarkLocationsLayout = QGridLayout()
		landmarkLocationsLayout.setSpacing(0)
		landmarkLocationsLayout.setContentsMargins(0, 0, 0, 0)
		landmarkLocationsLayout.setAlignment(Qt.AlignTop)

		self.landmarkLocationsWidget = QWidget()
		Style.styleWidgetForTab(self.landmarkLocationsWidget)
		self.landmarkLocationsWidget.setLayout(landmarkLocationsLayout)
		self.scrollArea.setWidget(self.landmarkLocationsWidget)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.addWidget(self.scrollArea)
		self.setLayout(layout)

	@Slot(list)
	def setPoints(self, points):
		self._clearLandmarkWidgets()
		layout = self.landmarkLocationsWidget.layout()
		for index in range(len(points)):
			landmarkWidget = LandmarkLocationWidget()
			landmarkWidget.setIndex(index)
			landmarkWidget.active = (index == self.activeIndex)
			landmarkWidget.activated.connect(self.activateLandmark)
			landmarkWidget.deleted.connect(self.deleteLandmark)
			landmarkWidget.setLandmarkSet(points[index])
			layout.addWidget(landmarkWidget, index, 0)
			self.landmarkWidgets.append(landmarkWidget)

	def _clearLandmarkWidgets(self):
		layout = self.landmarkLocationsWidget.layout()
		for widget in self.landmarkWidgets:
			widget.activated.disconnect()
			layout.removeWidget(widget)
			widget.deleteLater()
		self.landmarkWidgets = []

	@Slot(int, object)
	def activateLandmark(self, index, state):
		if not state:
			self.activeIndex = len(self.landmarkWidgets)
		else:
			self.activeIndex = index
		self.activeLandmarkChanged.emit(self.activeIndex)

	@Slot(int)
	def deleteLandmark(self, index):
		self.activateLandmark(index, False)
		self.landmarkDeleted.emit(index)
示例#58
0
        x = size.width() / 2.0 - (sizeCircle / 2.0)
        y = size.height() / 2.0 - (sizeCircle / 2.0)
        rect = QRectF(x, y, sizeCircle, sizeCircle)
        painter.setPen(pen)
        painter.setBrush(QColor.fromRgbF(color[0], color[1], color[2]))
        painter.drawEllipse(rect)


if __name__ == '__main__':
    from PySide.QtGui import QApplication
    from PySide.QtGui import QVBoxLayout
    app = QApplication([])

    colorWidget = ColorPickerWidget()
    colorWidget.setName("Color")

    colorChooser = ColorChoiceWidget()
    colorChooser.setName("Pick a color:")
    colorChooser.setColors([[1.0, 1.0, 1.0], [0.3, 0.7, 0.9], [0.9, 0.3, 0.8],
                            [0, 0, 0]])

    layout = QVBoxLayout()
    layout.addWidget(QLabel("Test color widget"))
    layout.addWidget(colorWidget)
    layout.addWidget(colorChooser)

    widget = QWidget()
    widget.setLayout(layout)
    widget.show()
    app.exec_()
示例#59
0
class ConfiguratorWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.statusBar().showMessage('Ready')

        self.saveButton = QPushButton(self.tr("Save"))
        self.saveButton.setDefault(True)
        self.quitButton = QPushButton(self.tr("Quit"))
        self.quitButton.setAutoDefault(False)
        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.saveButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)
        self.connect(self.saveButton, SIGNAL('clicked()'), self.save_file)
        self.connect(self.quitButton, SIGNAL('clicked()'), self.close)
        """
        bbox = QDialogButtonBox(QDialogButtonBox.Apply
                                |QDialogButtonBox.Cancel)
        self.apply_btn = bbox.button(QDialogButtonBox.Apply)
        self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()"))
        self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()"))
        self.connect(bbox, SIGNAL("clicked(QAbstractButton*)"),
                     self.button_clicked)
        """
        self.lineedits = {}
        self.comboboxes = {}
        self.spinboxes = {}
        self.availability_label = None

        self.job_name_widget = self.create_lineedit('Job Name', 'job_name')
        self.job_script_widget = self.create_lineedit('Job Script',
                                                      'job_script')
        self.job_output_widget = self.create_lineedit('Job Output',
                                                      'job_output')
        self.project_name_widget = self.create_lineedit(
            'Project/Account', 'project_name')
        self.queue_widget = self.create_combobox('Queue', [], 'queues')
        self.availability_label = QLabel('Available:')
        self.num_tasks_widget = self.create_spinbox('Number tasks', '',
                                                    'ntasks', NoDefault, 1, 1,
                                                    1, 'total number of tasks')
        self.task_per_node_widget = self.create_spinbox(
            'Task per node', '', 'task_per_node', NoDefault, 1, 2, 1,
            'tasks per node')
        self.runtime_widget = self.create_spinbox('Runtime', 'hrs', 'runtime',
                                                  NoDefault, 1, 36, 1,
                                                  'runtime in hrs')
        self.app_script_widget = self.create_combobox(
            'Application Script',
            [('mycluster-zcfd.bsh', 'mycluster-zcfd.bsh'),
             ('mycluster-paraview.bsh', 'mycluster-paraview.bsh'),
             ('mycluster-fluent.bsh', 'mycluster-fluent.bsh')], 'app_script')

        # hsplitter = QSplitter()
        # hsplitter.addWidget(self.pages_widget)

        btnlayout = QHBoxLayout()
        btnlayout.addStretch(1)
        btnlayout.addWidget(buttonBox)

        vlayout = QVBoxLayout()
        # vlayout.addWidget(hsplitter)

        vlayout.addWidget(self.job_name_widget)
        vlayout.addWidget(self.job_script_widget)
        vlayout.addWidget(self.job_output_widget)
        vlayout.addWidget(self.project_name_widget)
        hlayout = QHBoxLayout()
        hlayout.addWidget(self.queue_widget)
        hlayout.addWidget(self.availability_label)
        vlayout.addLayout(hlayout)
        vlayout.addWidget(self.num_tasks_widget)
        vlayout.addWidget(self.task_per_node_widget)
        vlayout.addWidget(self.runtime_widget)
        vlayout.addWidget(self.app_script_widget)
        vlayout.addSpacing(10)
        vlayout.addLayout(btnlayout)

        self.widget = QWidget()
        self.widget.setLayout(vlayout)

        self.setCentralWidget(self.widget)

        # self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle("MyCluster Job Configurator")

        self.lineedits['job_name'].textChanged.connect(self.job_name_changed)
        self.lineedits['job_script'].textChanged.connect(
            self.job_script_changed)
        self.lineedits['job_name'].setText('myjob')
        self.lineedits['project_name'].setText('default')
        #self.lineedits['app_script'].setText('myscript.bsh')
        self.comboboxes['app_script'].setEditable(True)
        self.comboboxes['app_script'].lineEdit().editingFinished.connect(
            self.check_app_script)

        from mycluster import mycluster
        mycluster.init()

        self.init_queue_info()

    def save_file(self):
        from mycluster import mycluster
        if mycluster.scheduler:
            index = self.comboboxes['queues'].currentIndex()
            data = self.comboboxes['queues'].itemData(index)
            jobqueue = data.split(' ')[0]

            index = self.comboboxes['app_script'].currentIndex()
            data = self.comboboxes['app_script'].itemData(index)
            app_script = data.split(' ')[0]

            # Add checks

            mycluster.create_submit(
                jobqueue,
                script_name=self.lineedits['job_script'].text() + '.job',
                my_script=app_script,
                my_name=self.lineedits['job_name'].text(),
                my_output=self.lineedits['job_output'].text() + '.out',
                num_tasks=self.spinboxes['ntasks'].value(),
                project_name=self.lineedits['project_name'].text(),
                wall_clock=self.spinboxes['runtime'].value(),
                tasks_per_node=self.spinboxes['task_per_node'].value(),
            )

    def init_queue_info(self):
        from mycluster import mycluster
        if mycluster.scheduler:
            for q in mycluster.queues():
                # nc = mycluster.scheduler.node_config(q)
                tpn = mycluster.scheduler.tasks_per_node(q)
                avail = mycluster.scheduler.available_tasks(q)
                self.comboboxes['queues'].addItem(
                    q + ' max task: ' + str(avail['max tasks']),
                    q + ' ' + str(avail['max tasks']) + ' ' + str(tpn) + ' ' +
                    str(avail['available']))

        self.comboboxes['queues'].currentIndexChanged.connect(
            self.queue_changed)
        self.queue_changed()

    def queue_changed(self):
        if self.comboboxes['queues'].count():
            index = self.comboboxes['queues'].currentIndex()
            data = self.comboboxes['queues'].itemData(index)
            self.spinboxes['ntasks'].setMaximum(int(data.split(' ')[1]))
            self.spinboxes['task_per_node'].setMaximum(int(data.split(' ')[2]))
            self.spinboxes['task_per_node'].setValue(int(data.split(' ')[2]))
            self.availability_label.setText('Available: ' +
                                            data.split(' ')[3] + ' tasks')

    def job_name_changed(self, text):
        # print 'job name changed'
        self.lineedits['job_script'].setText(text)
        self.lineedits['job_output'].setText(text)

    def job_script_changed(self, text):
        # Check for file exist
        if os.path.isfile(text + '.job'):
            self.statusBar().showMessage('Warning file: ' + text +
                                         '.job already exists')
        else:
            self.statusBar().showMessage('Ready')

    def check_app_script(self):
        text = self.comboboxes['app_script'].lineEdit().text()
        if not os.path.isfile(text):
            self.statusBar().showMessage('Warning file: ' + text +
                                         ' does not exists')
        else:
            self.statusBar().showMessage('Ready')
        pass

    def show_and_raise(self):
        self.show()
        self.raise_()

    def button_clicked(self, button):
        if button is self.apply_btn:
            # Apply button was clicked
            pass

    def create_lineedit(self,
                        text,
                        option,
                        default=NoDefault,
                        tip=None,
                        alignment=Qt.Horizontal):
        label = QLabel(text)
        label.setWordWrap(True)
        edit = QLineEdit()
        layout = QVBoxLayout() if alignment == Qt.Vertical else QHBoxLayout()
        layout.addWidget(label)
        layout.addWidget(edit)
        layout.setContentsMargins(0, 0, 0, 0)
        if tip:
            edit.setToolTip(tip)
        self.lineedits[option] = edit
        widget = QWidget(self)
        widget.setLayout(layout)
        return widget

    def create_spinbox(self,
                       prefix,
                       suffix,
                       option,
                       default=NoDefault,
                       min_=None,
                       max_=None,
                       step=None,
                       tip=None):
        if prefix:
            plabel = QLabel(prefix)
        else:
            plabel = None
        if suffix:
            slabel = QLabel(suffix)
        else:
            slabel = None
        spinbox = QSpinBox()
        if min_ is not None:
            spinbox.setMinimum(min_)
        if max_ is not None:
            spinbox.setMaximum(max_)
        if step is not None:
            spinbox.setSingleStep(step)
        if tip is not None:
            spinbox.setToolTip(tip)
        self.spinboxes[option] = spinbox
        layout = QHBoxLayout()
        for subwidget in (plabel, spinbox, slabel):
            if subwidget is not None:
                layout.addWidget(subwidget)
        layout.addStretch(1)
        layout.setContentsMargins(0, 0, 0, 0)
        widget = QWidget(self)
        widget.setLayout(layout)
        return widget

    def create_combobox(self,
                        text,
                        choices,
                        option,
                        default=NoDefault,
                        tip=None):
        """choices: couples (name, key)"""
        label = QLabel(text)
        combobox = QComboBox()
        if tip is not None:
            combobox.setToolTip(tip)
        # combobox.setEditable(True)
        for name, key in choices:
            combobox.addItem(name, key)  # to_qvariant(key))
        self.comboboxes[option] = combobox
        layout = QHBoxLayout()
        for subwidget in (label, combobox):
            layout.addWidget(subwidget)
        layout.addStretch(1)
        layout.setContentsMargins(0, 0, 0, 0)
        widget = QWidget(self)
        widget.setLayout(layout)
        return widget