def makeContent(self):
        layout = QHBoxLayout()

        layout.addLayout(self._welcomeAreaControls())
        layout.addLayout(self._modeControls())

        return layout
Exemple #2
0
 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)
Exemple #3
0
    def createLayouts(self):
        """Put widgets into layouts, thus creating the widget"""
        
        mainLayout = QHBoxLayout()
        fieldsLayout = QVBoxLayout()
        pathLayout = QHBoxLayout()
        buttonLayout = QHBoxLayout()
        
        mainLayout.addStretch(10)
        
        fieldsLayout.addStretch(50)
        fieldsLayout.addWidget(self.linkLabel)
        fieldsLayout.addWidget(self.line)
        
        fieldsLayout.addWidget(self.localdirLabel) 
        pathLayout.addWidget(self.localdirEdit)
        pathLayout.addWidget(self.browseButton)
        fieldsLayout.addLayout(pathLayout)

        buttonLayout.addStretch(50)
        buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight)
        
        fieldsLayout.addLayout(buttonLayout)
        fieldsLayout.addStretch(10)
        fieldsLayout.addWidget(self.statusLabel)
        fieldsLayout.addWidget(self.status)
        fieldsLayout.addStretch(80)

        mainLayout.addLayout(fieldsLayout, 60)
        mainLayout.addStretch(10)
        
        self.setLayout(mainLayout)
Exemple #4
0
    def makeContent(self):
        layout = QHBoxLayout()

        prefs = PreferencesWidget(self.controller, self.transition)
        layout.addWidget(prefs, 1)

        rhs = QVBoxLayout()

        lblVersion = QLabel()
        lblVersion.setText("av-control version {0} (avx version {1})".format(_ui_version, _avx_version))
        rhs.addWidget(lblVersion)

        self.lv = LogViewer(self.controller, self.mainWindow)

        log = ExpandingButton()
        log.setText("Log")
        log.clicked.connect(self.showLog)
        rhs.addWidget(log)

        btnQuit = ExpandingButton()
        btnQuit.setText("Exit AV Control")
        btnQuit.clicked.connect(self.mainWindow.close)
        rhs.addWidget(btnQuit)

        layout.addLayout(rhs, 1)

        return layout
    def _welcomeAreaControls(self):
        def onOff(presetString):
            @handlePyroErrors
            def inner(isOn):
                if isOn:
                    self.lights.activate(presetString)
                else:
                    self.lights.deactivate(presetString)
            return inner

        layout = QHBoxLayout()

        gallery_ext = QVBoxLayout()

        gallery_ext.addWidget(TitleLabel("Gallery and External"))

        gallery = ExpandingButton()
        gallery.setText("Gallery")
        gallery.setCheckable(True)
        gallery.toggled.connect(onOff("St Aldate's.Welcome Area.gall on"))
        gallery_ext.addWidget(gallery)

        external = ExpandingButton()
        external.setText("External Lights")
        external.setCheckable(True)
        external.toggled.connect(onOff("EXTERIOR.Section Zero.ENTRA ONLY ON"))
        gallery_ext.addWidget(external)

        layout.addLayout(gallery_ext)

        welcomeArea = QVBoxLayout()

        welcomeArea.addWidget(TitleLabel("Welcome Area"))

        full = OptionButton()
        full.setText("100%")
        _safelyConnect(full.clicked, lambda: self.lights.activate("St Aldate's.Welcome Area.Welcome100%"))
        welcomeArea.addWidget(full)

        std = OptionButton()
        std.setText("70%")
        _safelyConnect(std.clicked, lambda: self.lights.activate("St Aldate's.Welcome Area.Welcome70%"))
        welcomeArea.addWidget(std)

        off = OptionButton()
        off.setText("Off")
        _safelyConnect(off.clicked, lambda: self.lights.activate("St Aldate's.Welcome Area.Ent&GalOFF"))
        welcomeArea.addWidget(off)

        self.welcomeArea = QButtonGroup()
        self.welcomeArea.addButton(full, 1)
        self.welcomeArea.addButton(std, 2)
        self.welcomeArea.addButton(off, 3)

        layout.addLayout(welcomeArea)

        return layout
Exemple #6
0
                def __init__(self):
                    super().__init__()
                    if separate_colorbars:
                        if rescale_colorbars:
                            self.vmins = tuple(np.min(u[0]) for u in U)
                            self.vmaxs = tuple(np.max(u[0]) for u in U)
                        else:
                            self.vmins = tuple(np.min(u) for u in U)
                            self.vmaxs = tuple(np.max(u) for u in U)
                    else:
                        if rescale_colorbars:
                            self.vmins = (min(np.min(u[0]) for u in U),) * len(U)
                            self.vmaxs = (max(np.max(u[0]) for u in U),) * len(U)
                        else:
                            self.vmins = (min(np.min(u) for u in U),) * len(U)
                            self.vmaxs = (max(np.max(u) for u in U),) * len(U)

                    layout = QHBoxLayout()
                    plot_layout = QGridLayout()
                    self.colorbarwidgets = [cbar_widget(self, vmin=vmin, vmax=vmax) if cbar_widget else None
                                            for vmin, vmax in zip(self.vmins, self.vmaxs)]
                    plots = [widget(self, grid, vmin=vmin, vmax=vmax, bounding_box=bounding_box, codim=codim)
                             for vmin, vmax in zip(self.vmins, self.vmaxs)]
                    if legend:
                        for i, plot, colorbar, l in zip(range(len(plots)), plots, self.colorbarwidgets, legend):
                            subplot_layout = QVBoxLayout()
                            caption = QLabel(l)
                            caption.setAlignment(Qt.AlignHCenter)
                            subplot_layout.addWidget(caption)
                            if not separate_colorbars or backend == 'matplotlib':
                                subplot_layout.addWidget(plot)
                            else:
                                hlayout = QHBoxLayout()
                                hlayout.addWidget(plot)
                                if colorbar:
                                    hlayout.addWidget(colorbar)
                                subplot_layout.addLayout(hlayout)
                            plot_layout.addLayout(subplot_layout, int(i/columns), (i % columns), 1, 1)
                    else:
                        for i, plot, colorbar in zip(range(len(plots)), plots, self.colorbarwidgets):
                            if not separate_colorbars or backend == 'matplotlib':
                                plot_layout.addWidget(plot, int(i/columns), (i % columns), 1, 1)
                            else:
                                hlayout = QHBoxLayout()
                                hlayout.addWidget(plot)
                                if colorbar:
                                    hlayout.addWidget(colorbar)
                                plot_layout.addLayout(hlayout, int(i/columns), (i % columns), 1, 1)
                    layout.addLayout(plot_layout)
                    if not separate_colorbars:
                        layout.addWidget(self.colorbarwidgets[0])
                        for w in self.colorbarwidgets[1:]:
                            w.setVisible(False)
                    self.setLayout(layout)
                    self.plots = plots
Exemple #7
0
  def buildDataDisplays(self):
    hbox = QHBoxLayout()
    hbox.addStretch(1)

    for widget in self.buildLeftDataDisplays():
      hbox.addWidget(widget)
      hbox.addStretch(1)

    hbox.addLayout(self.buildRightDataDisplays())

    return hbox
Exemple #8
0
 def __init__(self):
     super(MainWindow, self).__init__()
     buttonsLayout = QVBoxLayout()
     celsiusButton = QRadioButton('Celsius')
     fahrenheitButton = QRadioButton('Fahrenheit')
     buttonsLayout.addWidget(celsiusButton)
     buttonsLayout.addWidget(fahrenheitButton)
     dataEntry = QLineEdit()
     applicationLayout = QHBoxLayout()
     applicationLayout.addLayout(buttonsLayout)
     applicationLayout.addWidget(dataEntry)
     self.setLayout(applicationLayout)
     self.setWindowTitle('Temperature Converter')
     self.show()
Exemple #9
0
 def initUI(self):
     '''Lays out the widgets'''
     radios = QVBoxLayout()
     radios.addWidget(self.rate)
     radios.addWidget(self.lifetime)
     rate = QGridLayout()
     rate.addWidget(QLabel("Unit: "), 1, 1)
     rate.addWidget(self.unit, 1, 2)
     rate.addWidget(QLabel("Value: "), 2, 1)
     rate.addWidget(self.rate_value, 2, 2)
     total = QHBoxLayout()
     total.addLayout(radios)
     total.addStretch()
     total.addLayout(rate)
     self.setLayout(total)
Exemple #10
0
    def _initialize_view(self):
        presenter = self._presenter

        self.widget = window = QWidget()
        window.setWindowTitle(LEMMA)

        self._layout = window_layout = QStackedLayout()
        window.setLayout(window_layout)

        self._main_menu = main_menu = QWidget(window)
        window_layout.addWidget(main_menu)
        main_menu_v_layout = QHBoxLayout()
        main_menu.setLayout(main_menu_v_layout)

        main_menu_v_layout.addStretch(20)
        main_menu_v_layout.addWidget(QLabel(LEMMA))

        main_menu_layout = QVBoxLayout()
        main_menu_v_layout.addLayout(main_menu_layout)
        main_menu_v_layout.addStretch(20)

        main_menu_layout.addStretch()
        self._main_menu_buttons = buttons = {}

        buttons[MainWindowView.CONTINUE_GAME] = continue_game = QPushButton(
            'Continue game')
        main_menu_layout.addWidget(continue_game)
        continue_game.clicked.connect(presenter.continue_game_clicked)

        buttons[MainWindowView.NEW_GAME] = new_game = QPushButton('New game')
        main_menu_layout.addWidget(new_game)
        new_game.clicked.connect(presenter.new_game_clicked)

        buttons[MainWindowView.LOAD_GAME] = load_game = QPushButton(
            'Load game')
        main_menu_layout.addWidget(load_game)
        load_game.clicked.connect(presenter.load_game_clicked)

        buttons[MainWindowView.SAVE_GAME] = save_game = QPushButton(
            'Save Game')
        main_menu_layout.addWidget(save_game)
        save_game.clicked.connect(presenter.save_game_clicked)

        buttons[MainWindowView.QUIT] = quit_button = QPushButton('Quit')
        main_menu_layout.addWidget(quit_button)
        quit_button.clicked.connect(presenter.quit_clicked)

        main_menu_layout.addStretch()
Exemple #11
0
 def __init__(self, parent = None):
     super(StackedPage, self).__init__(parent)
     layout = QHBoxLayout(self)
     leftpane = QVBoxLayout()
     self.buttongroup = QButtonGroup(self)
     self.buttongroup.setExclusive(True)
     self.groupbox = QGroupBox(self)
     self.groupbox.setMinimumWidth(200)
     QVBoxLayout(self.groupbox)
     leftpane.addWidget(self.groupbox)
     leftpane.addStretch(1)
     layout.addLayout(leftpane)
     self.rightpane = QStackedWidget(self)
     layout.addWidget(self.rightpane)
     self.buttongroup.buttonClicked[int].connect(self.rightpane.setCurrentIndex)
     self.rightpane.currentChanged[int].connect(self.activate)
    def makeContent(self):
        layout = QHBoxLayout()

        # self.exposureControls = ExposureControl(self.camera)
        # layout.addWidget(self.exposureControls)

        whiteBalanceGrid = QGridLayout()
        wbTitle = QLabel("White Balance")
        wbTitle.setAlignment(Qt.AlignCenter)
        whiteBalanceGrid.addWidget(wbTitle, 0, 0, 1, 2)

        btnAuto = OptionButton()
        btnAuto.setText("Auto")
        _safelyConnect(btnAuto.clicked, self.camera.whiteBalanceAuto)
        whiteBalanceGrid.addWidget(btnAuto, 1, 0)

        btnIndoor = OptionButton()
        btnIndoor.setText("Indoor")
        _safelyConnect(btnIndoor.clicked, self.camera.whiteBalanceIndoor)
        whiteBalanceGrid.addWidget(btnIndoor, 2, 0)

        btnOutdoor = OptionButton()
        btnOutdoor.setText("Outdoor")
        _safelyConnect(btnOutdoor.clicked, self.camera.whiteBalanceOutdoor)
        whiteBalanceGrid.addWidget(btnOutdoor, 3, 0)

        btnOnePush = OptionButton()
        btnOnePush.setText("One Push")
        _safelyConnect(btnOnePush.clicked, self.camera.whiteBalanceOnePush)
        whiteBalanceGrid.addWidget(btnOnePush, 4, 0)

        btnOnePushTrigger = ExpandingButton()
        btnOnePushTrigger.setText("Set")
        _safelyConnect(btnOnePushTrigger.clicked, self.camera.whiteBalanceOnePushTrigger)
        btnOnePushTrigger.setEnabled(False)
        whiteBalanceGrid.addWidget(btnOnePushTrigger, 4, 1)

        self.wbOpts = QButtonGroup()
        self.wbOpts.addButton(btnAuto, 1)
        self.wbOpts.addButton(btnIndoor, 2)
        self.wbOpts.addButton(btnOutdoor, 3)
        self.wbOpts.addButton(btnOnePush, 4)
        self.wbOpts.buttonClicked.connect(lambda: btnOnePushTrigger.setEnabled(self.wbOpts.checkedId() == 4))

        layout.addLayout(whiteBalanceGrid)

        return layout
Exemple #13
0
class OpenDialog(Popup):

    def __init__(self, parent):
        self.parent = parent
        super(OpenDialog, self).__init__()
        self.title = "Open Dialog"
        self.resize(400, 200)

    def _refresh(self):
        self._setup()

    def _setup(self):
        self.choicelist = [(0, "Choose Me!"), (1, "No, Me!")]
        self.buttonlist = [{"type": "button", "text": "Open", "callback": self.on_open}]

    def _header(self):
        label = QtGui.QLabel("Select Item to Open: ")
        self.layout.addWidget(label)

    def _center(self):
        self.hbox = QHBoxLayout()
        self.layout.addLayout(self.hbox)

        vbox = ButtonVBox(self.buttonlist)
        self.hbox.addLayout(vbox)

        self.listbox = ListBox(self.choicelist, self.on_open)
        self.hbox.addWidget(self.listbox)

    def _footer(self):
        hbox2 = QHBoxLayout()
        self.layout.addLayout(hbox2)

        cancelbut = QtGui.QPushButton("Close")
        cancelbut.released.connect(self.close)
        hbox2.addStretch(1)
        hbox2.addWidget(cancelbut)

    def on_open(self):
        myid = self.listbox.getId()
        print self.choicelist[myid]
        self.parent.PageManager.ThisPage("ButtonGridPage")
        self.close()
Exemple #14
0
    def __init__(self, parent=None, data=None, labels=None, options = {}):
        '''
        Rather large init method that does all the plotting directly.
        
        @todo: Put all the options (labels, showLegend, etc.) into properties.
        @todo: Refactor init, split into sub-methods, make everything cleaner.
        '''
        super(PlotWidget, self).__init__(parent)  # standard init call to Qt base class
        
        self.setMinimumSize(400, 300)  
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        self.data = data 
        self.labels = labels
        self.options = options
        
        
        self.dpi = self.logicalDpiX()
        logging.debug("Plotting at %s dpi." % self.dpi)
        #self.fig = Figure((4.0, 4.0), dpi=self.dpi)
        self.fig = Figure(dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        
        self.axes = self.fig.add_subplot(111)

        if os.name != "nt":
            self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        
        
        left_vbox = QVBoxLayout()
        left_vbox.addWidget(self.canvas)
        left_vbox.addWidget(self.mpl_toolbar)
        
        hbox = QHBoxLayout()
        hbox.addLayout(left_vbox)
        self.setLayout(hbox)
        
        self.setAxes()
        
        self.setData()
            
        self.canvas.draw()
Exemple #15
0
    def __init__(self, parent=None, data=None, labels=None, options={}):
        '''
        Rather large init method that does all the plotting directly.
        
        @todo: Put all the options (labels, showLegend, etc.) into properties.
        @todo: Refactor init, split into sub-methods, make everything cleaner.
        '''
        super(PlotWidget,
              self).__init__(parent)  # standard init call to Qt base class

        self.setMinimumSize(400, 300)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.data = data
        self.labels = labels
        self.options = options

        self.dpi = self.logicalDpiX()
        logging.debug("Plotting at %s dpi." % self.dpi)
        #self.fig = Figure((4.0, 4.0), dpi=self.dpi)
        self.fig = Figure(dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.axes = self.fig.add_subplot(111)

        if os.name != "nt":
            self.mpl_toolbar = NavigationToolbar(self.canvas, self)

        left_vbox = QVBoxLayout()
        left_vbox.addWidget(self.canvas)
        left_vbox.addWidget(self.mpl_toolbar)

        hbox = QHBoxLayout()
        hbox.addLayout(left_vbox)
        self.setLayout(hbox)

        self.setAxes()

        self.setData()

        self.canvas.draw()
Exemple #16
0
    def setup_ui(self):
        main_layout = QHBoxLayout(self)

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

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

        layout2 = QVBoxLayout()
        layout2.addLayout(layout)

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

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

        main_layout.addLayout(layout2)

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

        self.btn = btn
        self.edt = edt
        self.image = image
        self.list = list
        self.proxy = proxy
        self.model = model
        self.selection_model = selection_model
Exemple #17
0
    def layoutWidgets(self):
        vbox = QVBoxLayout()
        vbox.addLayout(self.topForm)
        hbox = QHBoxLayout()
        hbox.addLayout(self.startForm)
        hbox.addLayout(self.endForm)
        vbox.addLayout(hbox)

        self.setLayout(vbox)
        self.setTabOrder(self.documentStartEdit, self.documentEndEdit)
        self.setTabOrder(self.sectionStartEdit, self.sectionEndEdit)
        self.setTabOrder(self.mainStartEdit, self.mainEndEdit)
        self.setTabOrder(self.sub1StartEdit, self.sub1EndEdit)
        self.setTabOrder(self.sub2StartEdit, self.sub2EndEdit)
        self.setTabOrder(self.sub3StartEdit, self.sub3EndEdit)
        self.setTabOrder(self.sub4StartEdit, self.sub4EndEdit)
        self.setTabOrder(self.sub5StartEdit, self.sub5EndEdit)
        self.setTabOrder(self.sub6StartEdit, self.sub6EndEdit)
        self.setTabOrder(self.sub7StartEdit, self.sub7EndEdit)
        self.setTabOrder(self.sub8StartEdit, self.sub8EndEdit)
        self.setTabOrder(self.sub9StartEdit, self.sub9EndEdit)
Exemple #18
0
 def __init__(self):
     super(PlotWidget, self).__init__()
     if separate_colorbars:
         vmins = tuple(np.min(u) for u in U)
         vmaxs = tuple(np.max(u) for u in U)
     else:
         vmins = (min(np.min(u) for u in U),) * len(U)
         vmaxs = (max(np.max(u) for u in U),) * len(U)
     layout = QHBoxLayout()
     plot_layout = QGridLayout()
     plots = [widget(self, grid, vmin=vmin, vmax=vmax, bounding_box=bounding_box, codim=codim)
              for vmin, vmax in izip(vmins, vmaxs)]
     if legend:
         for i, plot, l in izip(xrange(len(plots)), plots, legend):
             subplot_layout = QVBoxLayout()
             caption = QLabel(l)
             caption.setAlignment(Qt.AlignHCenter)
             subplot_layout.addWidget(caption)
             if not separate_colorbars or backend == 'matplotlib':
                 subplot_layout.addWidget(plot)
             else:
                 hlayout = QHBoxLayout()
                 hlayout.addWidget(plot)
                 hlayout.addWidget(ColorBarWidget(self, vmin=vmins[i], vmax=vmaxs[i]))
                 subplot_layout.addLayout(hlayout)
             plot_layout.addLayout(subplot_layout, int(i/2), (i % 2), 1, 1)
     else:
         for i, plot in enumerate(plots):
             if not separate_colorbars or backend == 'matplotlib':
                 plot_layout.addWidget(plot, int(i/2), (i % 2), 1, 1)
             else:
                 hlayout = QHBoxLayout()
                 hlayout.addWidget(plot)
                 hlayout.addWidget(ColorBarWidget(self, vmin=vmins[i], vmax=vmaxs[i]))
                 plot_layout.addLayout(plot, int(i/2), (i % 2), 1, 1)
     layout.addLayout(plot_layout)
     if not separate_colorbars:
         layout.addWidget(ColorBarWidget(self, vmin=vmin, vmax=vmax))
     self.setLayout(layout)
     self.plots = plots
Exemple #19
0
 def layoutWidgets(self):
     grid = QGridLayout()
     grid.addWidget(self.romanStartLabel, 0, 0)
     grid.addWidget(self.romanStartSpinBox, 0, 1)
     grid.addWidget(self.romanEndLabel, 0, 2)
     grid.addWidget(self.romanEndSpinBox, 0, 3)
     grid.addWidget(self.romanChangeLabel, 0, 4)
     grid.addWidget(self.romanChangeSpinBox, 0, 5)
     grid.addWidget(self.decimalStartLabel, 1, 0)
     grid.addWidget(self.decimalStartSpinBox, 1, 1)
     grid.addWidget(self.decimalEndLabel, 1, 2)
     grid.addWidget(self.decimalEndSpinBox, 1, 3)
     grid.addWidget(self.decimalChangeLabel, 1, 4)
     grid.addWidget(self.decimalChangeSpinBox, 1, 5)
     hbox = QHBoxLayout()
     hbox.addLayout(grid)
     hbox.addStretch()
     layout = QVBoxLayout()
     layout.addLayout(hbox)
     layout.addStretch()
     layout.addWidget(self.buttonBox)
     self.setLayout(layout)
Exemple #20
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self._text_edit = QTextEdit()
        self._open_button = QPushButton(self.tr("&Open"))
        self._save_button = QPushButton(self.tr("&Save"))
        self._exit_button = QPushButton(self.tr("&Exit"))

        button_layout = QVBoxLayout()
        button_layout.addWidget(self._open_button)
        button_layout.addWidget(self._save_button)
        button_layout.addWidget(self._exit_button)
        button_layout.addStretch()

        main_layout = QHBoxLayout()
        main_layout.addWidget(self._text_edit)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)

        self.setWindowTitle(self.tr('Notepad'))
        self._save_button.clicked.connect(self.save)
        self._open_button.clicked.connect(self.open)
        self._exit_button.clicked.connect(self.exit)
Exemple #21
0
    def __init__(self, parent):
        super(SupplierPlateWidget, self).__init__(parent)

        # w.setMaximumWidth(600)
        # w.setMinimumWidth(600)
        self.setStyleSheet("background:white")
        self.setFrameShape(QFrame.Panel)
        self.setFrameShadow(QFrame.Sunken)

        self.supplier_name_label = QLabel()
        self.supplier_name_label.setTextInteractionFlags(
            Qt.TextSelectableByMouse)
        self.supplier_name_label.setObjectName("HorseCustomerPlateTitle")
        self.supplier_address1_label = QLabel()
        self.supplier_address2_label = QLabel()
        self.supplier_phone_label = QLabel(_("Phone : /"))
        self.supplier_phone2_label = QLabel()
        self.supplier_fax_label = QLabel(_("Fax : /"))
        self.supplier_notes_label = QLabel("")

        supplier_data_layout = QVBoxLayout()
        # supplier_data_layout.addWidget(self.supplier_address1_label)
        # supplier_data_layout.addWidget(self.supplier_address2_label)
        supplier_data_layout.addWidget(self.supplier_phone_label)
        supplier_data_layout.addWidget(self.supplier_phone2_label)
        supplier_data_layout.addWidget(self.supplier_fax_label)
        supplier_data_layout.addStretch()

        supplier_plate_hlayout = QHBoxLayout()
        self.supplier_notes_label.setAlignment(Qt.AlignTop)
        supplier_plate_hlayout.addLayout(supplier_data_layout)
        supplier_plate_hlayout.addWidget(self.supplier_notes_label)

        supplier_plate_layout = QVBoxLayout()
        supplier_plate_layout.addWidget(self.supplier_name_label)
        supplier_plate_layout.addLayout(supplier_plate_hlayout)

        self.setLayout(supplier_plate_layout)
        self.supplier_id = None
Exemple #22
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self._text_edit = QTextEdit()
        self._open_button = QPushButton(self.tr("&Open"))
        self._save_button = QPushButton(self.tr("&Save"))
        self._exit_button = QPushButton(self.tr("&Exit"))

        button_layout = QVBoxLayout()
        button_layout.addWidget(self._open_button)
        button_layout.addWidget(self._save_button)
        button_layout.addWidget(self._exit_button)
        button_layout.addStretch()

        main_layout = QHBoxLayout()
        main_layout.addWidget(self._text_edit)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)
        
        self.setWindowTitle(self.tr('Notepad'))
        self._save_button.clicked.connect(self.save)
        self._open_button.clicked.connect(self.open)
        self._exit_button.clicked.connect(self.exit)
Exemple #23
0
 def createLayouts(self):
     """Put widgets into layouts, thus creating the widget"""
     
     mainLayout = QHBoxLayout()
     fieldsLayout = QVBoxLayout()
     ftpInfoLayout = QHBoxLayout()
     buttonLayout = QHBoxLayout()
     
     mainLayout.addStretch(20)
     
     fieldsLayout.addStretch(80)
     fieldsLayout.addWidget(self.linkLabel)
     fieldsLayout.addWidget(self.line)
     fieldsLayout.addStretch(20)
     
     ftpInfoLayout.addWidget(self.hostLabel, 50, Qt.AlignLeft)
     ftpInfoLayout.addStretch(20)
     ftpInfoLayout.addWidget(self.sslLabel, 20, Qt.AlignRight)
     ftpInfoLayout.addWidget(self.sslCheck, 10, Qt.AlignRight)
     
     fieldsLayout.addLayout(ftpInfoLayout)
     fieldsLayout.addWidget(self.hostEdit)
     fieldsLayout.addWidget(self.usernameLabel)
     fieldsLayout.addWidget(self.usernameEdit)
     fieldsLayout.addWidget(self.passwdLabel)
     fieldsLayout.addWidget(self.passwdEdit)
     fieldsLayout.addStretch(30)
     
     buttonLayout.addStretch(50)
     buttonLayout.addWidget(self.loginButton, 50, Qt.AlignRight)
     
     fieldsLayout.addLayout(buttonLayout)
     fieldsLayout.addStretch(20)
     
     mainLayout.addLayout(fieldsLayout, 30)
     mainLayout.addStretch(20)
     
     self.setLayout(mainLayout)
Exemple #24
0
    def createLayouts(self):
        """Put widgets into layouts, thus creating the widget"""

        mainLayout = QHBoxLayout()
        fieldsLayout = QVBoxLayout()
        ftpInfoLayout = QHBoxLayout()
        buttonLayout = QHBoxLayout()

        mainLayout.addStretch(20)

        fieldsLayout.addStretch(80)
        fieldsLayout.addWidget(self.linkLabel)
        fieldsLayout.addWidget(self.line)
        fieldsLayout.addStretch(20)

        ftpInfoLayout.addWidget(self.hostLabel, 50, Qt.AlignLeft)
        ftpInfoLayout.addStretch(20)
        ftpInfoLayout.addWidget(self.sslLabel, 20, Qt.AlignRight)
        ftpInfoLayout.addWidget(self.sslCheck, 10, Qt.AlignRight)

        fieldsLayout.addLayout(ftpInfoLayout)
        fieldsLayout.addWidget(self.hostEdit)
        fieldsLayout.addWidget(self.usernameLabel)
        fieldsLayout.addWidget(self.usernameEdit)
        fieldsLayout.addWidget(self.passwdLabel)
        fieldsLayout.addWidget(self.passwdEdit)
        fieldsLayout.addStretch(30)

        buttonLayout.addStretch(50)
        buttonLayout.addWidget(self.loginButton, 50, Qt.AlignRight)

        fieldsLayout.addLayout(buttonLayout)
        fieldsLayout.addStretch(20)

        mainLayout.addLayout(fieldsLayout, 30)
        mainLayout.addStretch(20)

        self.setLayout(mainLayout)
Exemple #25
0
 def layoutWidgets(self):
     form = QFormLayout()
     grid = QGridLayout()
     grid.addWidget(self.indexViewOnLeft, 0, 0)
     grid.addWidget(self.alwaysShowSortAsCheckBox, 1, 0)
     grid.addWidget(self.showNotesCheckBox, 2, 0)
     grid.addWidget(self.showMenuToolTipsCheckBox, 0, 1)
     grid.addWidget(self.showMainWindowToolTipsCheckBox, 1, 1)
     grid.addWidget(self.showDialogToolTipsCheckBox, 2, 1)
     grid.addWidget(self.keepHelpOnTopCheckBox, 3, 1)
     grid.addWidget(self.showSplashCheckBox, 4, 1)
     hbox = QHBoxLayout()
     hbox.addLayout(grid)
     hbox.addStretch()
     form.addRow(hbox)
     hbox = QHBoxLayout()
     hbox.addWidget(self.displaystdFontComboBox, 1)
     hbox.addWidget(self.displaystdFontSizeSpinBox)
     hbox.addStretch()
     label = QLabel("&Std. Font")
     label.setBuddy(self.displaystdFontComboBox)
     form.addRow(label, hbox)
     hbox = QHBoxLayout()
     hbox.addWidget(self.displayaltFontComboBox, 1)
     hbox.addWidget(self.displayaltFontSizeSpinBox)
     hbox.addStretch()
     label = QLabel("&Alt. Font")
     label.setBuddy(self.displayaltFontComboBox)
     form.addRow(label, hbox)
     hbox = QHBoxLayout()
     hbox.addWidget(self.displaymonoFontComboBox, 1)
     hbox.addWidget(self.displaymonoFontSizeSpinBox)
     hbox.addStretch()
     label = QLabel("&Mono. Font")
     label.setBuddy(self.displaymonoFontComboBox)
     form.addRow(label, hbox)
     self.setLayout(form)
    def _initUI(self):
        # Widgets
        self._lbl_left = QLabel('Left substrate')
        self._lbl_left.setStyleSheet('color: blue')
        self._lst_left = MaterialListWidget(_VerticalLeftSubstrateBody.material)

        self._lbl_layer = QLabel('Layer')
        self._lbl_layer.setStyleSheet('color: blue')
        self._lst_layer = LayerListWidget(VerticalLayers.layers)
        self._lst_layer.setRequired(False)

        self._lbl_right = QLabel('Right substrate')
        self._lbl_right.setStyleSheet('color: blue')
        self._lst_right = MaterialListWidget(_VerticalRightSubstrateBody.material)

        self._lbl_depth = QLabel('Depth')
        self._lbl_depth.setStyleSheet('color: blue')
        self._txt_depth = UnitParameterWidget(VerticalLayers.depth_m)
        self._txt_depth.setValues(['inf'])

        # Layouts
        layout = _GeometryWidget._initUI(self)

        sublayout = QHBoxLayout()

        subsublayout = QVBoxLayout()
        subsublayout.addWidget(self._lbl_left)
        subsublayout.addWidget(self._lst_left)
        sublayout.addLayout(subsublayout)

        subsublayout = QVBoxLayout()
        subsublayout.addWidget(self._lbl_layer)
        subsublayout.addWidget(self._lst_layer)
        sublayout.addLayout(subsublayout)

        subsublayout = QVBoxLayout()
        subsublayout.addWidget(self._lbl_right)
        subsublayout.addWidget(self._lst_right)
        sublayout.addLayout(subsublayout)

        layout.insertRow(0, sublayout)
        layout.insertRow(1, self._lbl_depth, self._txt_depth)

        return layout
Exemple #27
0
    def __init__(self, parent, find_order_action_slot):
        super(PresenceOverviewWidget, self).__init__(parent)

        self.set_panel_title(_("Presence overview"))
        self.base_date = date.today()

        headers = QStandardItemModel(1, 31 + 3)
        self._table_model = QStandardItemModel(1, 31 + 3, None)

        self.headers_view = QHeaderView(Qt.Orientation.Horizontal, self)
        self.header_model = headers
        self.headers_view.setResizeMode(QHeaderView.ResizeToContents)
        self.headers_view.setModel(
            self.header_model)  # qt's doc : The view does *not* take ownership

        self.table_view = TableViewSignaledEvents(None)
        self.table_view.setModel(self._table_model)

        self.table_view.setHorizontalHeader(self.headers_view)
        self.table_view.verticalHeader().hide()
        self.table_view.setAlternatingRowColors(True)
        self.table_view.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.table_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table_view.customContextMenuRequested.connect(
            self.popup_context_menu)

        self.copy_action = QAction(_("Copy order parts"), self.table_view)
        self.copy_action.triggered.connect(self.copy_slot)
        self.copy_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_C))
        self.copy_action.setShortcutContext(Qt.WidgetWithChildrenShortcut)
        self.table_view.addAction(self.copy_action)

        self.select_all_action = QAction(_("Select all"), self.table_view)
        self.select_all_action.triggered.connect(self.select_all_slot)
        self.select_all_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_A))
        self.select_all_action.setShortcutContext(
            Qt.WidgetWithChildrenShortcut)
        self.table_view.addAction(self.select_all_action)

        # self.table_view.setSelectionBehavior(QAbstractItemView.SelectItems)
        # self.table_view.setSelectionMode(QAbstractItemView.SingleSelection)

        navbar = NavBar(self, [(_("Month before"), self.month_before),
                               (_("Today"), self.month_today),
                               (_("Action"), self.show_actions),
                               (_("Month after"), self.month_after),
                               (_("Find"), find_order_action_slot)])

        self.action_menu = QMenu(navbar.buttons[2])
        navbar.buttons[2].setObjectName("specialMenuButton")
        navbar.buttons[4].setObjectName("specialMenuButton")

        self._make_days_off_menu_and_action_group()

        list_actions = [  # (_("Edit"),self.edit_tars, None, None),
            (_("Edit"), self.edit_timetrack_no_ndx, None, None),
            (_("Month correction"), self.edit_month_correction, None,
             [RoleType.modify_monthly_time_track_correction]),
            (self.days_off_menu, None), (self.copy_action, None),
            (self.select_all_action, None)
        ]

        # (_("Insert holidays"),self.create_holidays, None, None),
        # (_("Delete holidays"),self.delete_holidays, None, None) ]

        populate_menu(self.action_menu, self, list_actions)

        # mainlog.debug("tile widget")
        self.title_box = TitleWidget(_("Presence Overview"), self, navbar)
        self.vlayout = QVBoxLayout(self)
        self.vlayout.setObjectName("Vlayout")
        self.vlayout.addWidget(self.title_box)

        self.hours_per_pers_subframe = SubFrame(_("Overview"), self.table_view,
                                                self)
        self.vlayout.addWidget(self.hours_per_pers_subframe)

        self.time_report_view = TimeReportView(self)

        self.days_off_panel = self._make_total_days_off_panel()
        vbox = QVBoxLayout()
        vbox.addWidget(self.days_off_panel)
        vbox.addStretch()
        vbox.setStretch(0, 0)
        vbox.setStretch(1, 1)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.time_report_view)
        hlayout.addLayout(vbox)
        hlayout.setStretch(0, 1)
        self.detail_subframe = SubFrame(_("Day"), hlayout, self)

        self.vlayout.addWidget(self.detail_subframe)

        self.setLayout(self.vlayout)

        # dbox = QVBoxLayout()
        # dbox.addWidget(QLabel("kjkljkj"))

        # self.total_active_hours = LabeledValue(_("Total activity"))
        # dbox.addWidget(self.total_active_hours)

        # hbox = QHBoxLayout()
        # hbox.addWidget(self.table_view)
        # hbox.addLayout(dbox)

        # self.selection_model = self.table_view.selectionModel()
        # mainlog.debug(m)
        #sm = QItemSelectionModel(self.table_view.model())
        #sm.setModel(self.table_view.model())
        # self.table_view.setSelectionModel(self.selection_model)

        self.table_view.selectionModel().currentChanged.connect(
            self.cell_entered)

        self.table_view.doubleClickedCell.connect(self.edit_timetrack)
Exemple #28
0
    def setupUI(self):
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignHCenter)

        self.setContentsMargins(20, 10, 20, 5)
        banner = QHBoxLayout()
        banner.addWidget(self.logo)
        bannerText = QVBoxLayout()
        text = QLabel("Salary Management System")
        text.setStyleSheet("font-size: 30px;")
        bannerText.addWidget(text)
        bannerText.setAlignment(text, Qt.AlignBottom)
        text2 = QLabel("Indian Institute of Information Technology Kalyani")
        text2.setStyleSheet("font-size: 20px;")
        bannerText.addWidget(text2)
        bannerText.setAlignment(text2, Qt.AlignTop)
        banner.addLayout(bannerText)
        banner.addStretch()
        layout.addLayout(banner)
        layout.addSpacing(30)

        bttnList = [
            self.bttnAddDesignation, self.bttnDelDesg, self.bttnEditDesg,
            self.bttnShowDesg, self.bttnShowEmp, self.bttnEditEmp,
            self.bttnAddEmployee, self.bttnDelEmp, self.bttnSettings,
            self.bttnCalcSalary
        ]
        for bttn in bttnList:
            bttn.setObjectName("HomeBttn")
            bttn.setIconSize(QSize(55, 55))

        employeeGroup = QGroupBox("Employee")
        employeeGroupLayout = QVBoxLayout()
        employeeGroupLayout.addWidget(self.bttnAddEmployee)
        employeeGroupLayout.addWidget(self.bttnEditEmp)
        employeeGroupLayout.addWidget(self.bttnDelEmp)
        employeeGroupLayout.addWidget(self.bttnShowEmp)
        employeeGroup.setLayout(employeeGroupLayout)

        designationGroup = QGroupBox("Designation")
        designationGroupLayout = QVBoxLayout()
        designationGroupLayout.addWidget(self.bttnAddDesignation)
        designationGroupLayout.addWidget(self.bttnEditDesg)
        designationGroupLayout.addWidget(self.bttnDelDesg)
        designationGroupLayout.addWidget(self.bttnShowDesg)
        designationGroup.setLayout(designationGroupLayout)

        groups = QHBoxLayout()
        groups.addWidget(employeeGroup)
        groups.addWidget(designationGroup)

        otherBttns = QGroupBox()
        otherBttnsLayout = QVBoxLayout()
        otherBttnsLayout.addWidget(self.bttnCalcSalary)
        otherBttnsLayout.addWidget(self.bttnSettings)
        otherBttnsLayout.addStretch()
        otherBttns.setLayout(otherBttnsLayout)
        groups.addWidget(otherBttns)

        groups.addStretch()

        layout.addLayout(groups)

        layout.addStretch()

        version = QLabel(version_text)
        layout.addWidget(version)

        centerLayout = QHBoxLayout()
        centerLayout.addStretch()
        centerLayout.addLayout(layout)
        centerLayout.addStretch()
        self.setLayout(centerLayout)
    def __init__(self):
        QMainWindow.__init__(self)
        # filename = QFileDialog.getOpenFileName(self, "Open File")[0]
        # self.setWindowTitle(os.path.basename(filename))
        # self.transcript = StepperTranscript(filename)
        self.transcript = None
        self.outer_widget = QWidget()
        self.setCentralWidget(self.outer_widget)
        outer_layout = QHBoxLayout()
        self.outer_widget.setLayout(outer_layout)
        self.setLayout(outer_layout)
        left_layout = QVBoxLayout()
        outer_layout.addLayout(left_layout)

        display_widget = QWidget()
        left_layout.addWidget(display_widget)
        self.display_layout = QHBoxLayout()

        # self.turn = self.transcript.current_turn()
        self.time_field = qHotField("time", str, "00:00:00", min_size=75, max_size=75, pos="top", handler=self.update_time)
        self.display_layout.addWidget(self.time_field)
        self.speaker_field = qHotField("speaker", str, " ", min_size=75, max_size=75, pos="top", handler=self.update_speaker)
        self.display_layout.addWidget(self.speaker_field)
        self.utt_field = qHotField("utterance", str, " ", min_size=350, pos="top", handler=self.update_utterance, multiline=True)
        self.utt_field.setStyleSheet("font: 14pt \"Courier\";")
        # self.utt_field.efield.setFont(QFont('SansSerif', 12))
        self.display_layout.addWidget(self.utt_field)

        display_widget.setLayout(self.display_layout)
        self.display_layout.setStretchFactor(self.speaker_field, 0)
        self.display_layout.setStretchFactor(self.utt_field, 1)

        self.transcript_slider = QSlider(QtCore.Qt.Horizontal, self)
        self.display_layout.addWidget(self.transcript_slider)
        self.transcript_slider.setMaximum(100)
        self.connect(self.transcript_slider,
                     QtCore.SIGNAL("sliderMoved(int)"), self.position_transcript)
        left_layout.addWidget(self.transcript_slider)

        button_widget = TranscriptButtons(self)

        left_layout.addWidget(button_widget)
        left_layout.addWidget(QWidget())
        left_layout.setStretch(0, 0)
        left_layout.setStretch(1, 0)
        left_layout.setStretch(2, 0)
        left_layout.setStretch(3, 1)

        # video_buttons = VideoButtons(self)
        # outer_layout.addWidget(video_buttons)

        self.createKeypadButtons(self)
        left_layout.addWidget(self.keypadWidget)

        self.player = Player()
        outer_layout.addWidget(self.player)

        outer_layout.setStretch(0, 0)
        outer_layout.setStretch(1, 1)
        self.save_file_name = None

        command_list = [
            [self.open_video, "Open Video", {}, "Ctrl+o"],
            [self.open_transcript, "Open Transcript", {}, "Ctrl+t"],
            [self.play_or_pause, "Play/Pause", {}, Qt.CTRL + Qt.Key_P],
            [self.save_file, "Save", {}, "Ctrl+s"],
            [self.player.jump_video_backward, "Jump Back", {}, Qt.CTRL + Qt.Key_4],
            [self.player.jump_video_forward, "Jump Forward", {}, Qt.CTRL + Qt.Key_6],
            [self.go_to_previous_turn, "Previous", {}, "Ctrl+["],
            [self.go_to_next_turn, "Next", {}, "Ctrl+]"],
            ]

        menubar = self.menuBar()
        create_menu(self, menubar, "Stepper", command_list)

        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_0), self, self.play_or_pause)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_5), self, self.play_or_pause)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_7), self, self.go_to_previous_turn)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_9), self, self.go_to_next_turn)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_4), self, self.player.jump_video_backward)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_6), self, self.player.jump_video_forward)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_2), self, self.player.reset_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_1), self, self.player.decrease_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_3), self, self.player.increase_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_G), self, self.sync_video_and_play)
Exemple #30
0
class MainWindow(QMainWindow):
    '''The main window of the program'''

    def __init__(self):
        '''Initialize the main window and it's parents'''
        super(MainWindow, self).__init__()
        self._createtWidgets()
        self._initUI()
        self._makeMenu()
        self._makeConnections()
        self.fileName = None
        self.pdfName = None
        self.scriptName = None
        self.expName = None
        self.rawName = None
        self.rawExpName = None

        # Set initial number of peaks
        self.exchange.setNumPeaks(2)
        # Set matrix to symmetric by default
        self.exchange.setMatrixSymmetry(True)
        # Set the initial window.  
        self.scale.setValue(1900, 2100, False)
        # Default to rate in units of THz
        self.rate.setUnit('THz')
        # Clear button starts off inactive
        self.clear.setEnabled(False)

    def _createtWidgets(self):
        '''Creates all the widgets'''

        # Make the views
        self.plot = Plot(self)
        self.rate = RateView(parent=self)
        self.exchange = ExchangeView(parent=self)
        self.peak = PeakView(parent=self)
        self.scale = ScaleView(parent=self)

        # Create the model controller
        self.control = Controller(self)

        # Attach models to the views
        self.rate.setModel(self.control.rate)
        self.exchange.setModel(self.control.exchange, self.control.numpeaks)
        self.peak.setModel(self.control.peak)
        self.scale.setModel(self.control.scale)

        # Init the UI of all the views
        self.rate.initUI()
        self.exchange.initUI()
        self.peak.initUI()
        self.scale.initUI()

        # Last, make inter-view connections
        self.rate.makeConnections()
        self.exchange.makeConnections()
        self.peak.makeConnections()
        self.scale.makeConnections()
        self.plot.makeConnections()

        # The window will own a button to clear raw data
        self.clear = QPushButton('Clear Raw Data', self)
        self.clear.setToolTip(ttt('Remove raw data from the plot '
                                  'if there is any'))

    def _initUI(self):
        '''Sets up the layout of the window'''

        # Define a central widget and a layout for the window
        self.setCentralWidget(QWidget())
        self.mainLayout = QHBoxLayout()
        self.setWindowTitle('Spectral Exchange')

        # Make a layout for all the parameter views
        params = QVBoxLayout()
        params.addWidget(self.rate)
        params.addWidget(self.exchange)
        params.addWidget(self.peak)

        # Add the parameter dialog
        self.mainLayout.addLayout(params)

        # Add the plot 
        plot_lim = QVBoxLayout()
        plot_lim.addWidget(self.plot)
        lim_clear = QHBoxLayout()
        lim_clear.addWidget(self.scale)
        lim_clear.addWidget(self.clear)
        plot_lim.addLayout(lim_clear)
        self.mainLayout.addLayout(plot_lim)

        # Add the widgets to the central widget
        self.centralWidget().setLayout(self.mainLayout)

    def _makeConnections(self):
        '''Connect the widgets to each other'''

        # When the controller says plot, plot
        self.control.plotSpectrum.connect(self.plot.plotCalculatedData)

        # When the controller says resize x limits, do so
        self.control.newXLimits.connect(self.plot.changeScale)

        # Clear raw data if pushed
        self.clear.clicked.connect(self.clearRawData)

        # If the plot is clicked, send info to the scale widget
        self.plot.pointPicked.connect(self.scale.setSelection)

    def _makeMenu(self):
        '''Makes the menu bar for this widget'''
        # Get the menu bar object
        self.menu = self.menuBar()
        self.fileMenu = self.menu.addMenu('&File')

        # Open action
        open = QAction('&Open', self)
        open.setShortcuts(QKeySequence.Open)
        open.triggered.connect(self.openFromInput)
        open.setToolTip('Open an already made input file')
        self.fileMenu.addAction(open)

        # Save action
        save = QAction('&Save', self)
        save.setShortcuts(QKeySequence.Save)
        save.triggered.connect(self.saveToInput)
        save.setToolTip('Save settings to an input file')
        self.fileMenu.addAction(save)

        # Save action
        saveas = QAction('Save As', self)
        saveas.triggered.connect(self.saveToInputAs)
        save.setToolTip('Save settings to an input file of a new name')
        self.fileMenu.addAction(saveas)

        # Save action
        savepdf = QAction('Save as PDF', self)
        savepdf.triggered.connect(self.saveAsPDF)
        save.setToolTip('Save image to a PDF')
        self.fileMenu.addAction(savepdf)

        # Menu separator
        self.fileMenu.addSeparator()

        # Import action
        imp = QAction('&Import raw XY data', self)
        imp.setShortcut(QKeySequence('Ctrl+I'))
        imp.triggered.connect(self.importRawData)
        imp.setToolTip('Import raw data an plot alongside calculated data')
        self.fileMenu.addAction(imp)

        # Export action
        raw = QAction('Export raw XY data', self)
        raw.triggered.connect(self.exportRawData)
        raw.setToolTip('Export raw data to a file for use elsewhere')
        self.fileMenu.addAction(raw)

        # Export action
        exp = QAction('&Export calculated XY data', self)
        exp.setShortcut(QKeySequence('Ctrl+E'))
        exp.triggered.connect(self.exportXYData)
        exp.setToolTip('Export calculated data to a file for use elsewhere')
        self.fileMenu.addAction(exp)

        # Make script action
        scr = QAction('Make Sc&ript', self)
        scr.setShortcut(QKeySequence('Ctrl+R'))
        scr.triggered.connect(self.makeScript)
        scr.setToolTip('Create a python script that directly recreates this '
                       'spectrum')
        self.fileMenu.addAction(scr)

        # Menu separator
        self.fileMenu.addSeparator()

        # Quit action
        quit = QAction('&Quit', self)
        quit.setShortcuts(QKeySequence.Quit)
        quit.triggered.connect(QApplication.instance().quit)
        self.fileMenu.addAction(quit)

    #######
    # SLOTS
    #######

    def clearRawData(self):
        '''Clear the raw data from the plot'''
        self.plot.clearRawData()
        self.clear.setEnabled(False)

    def openFromInput(self):
        '''Open parameters from an input file'''
        filter = 'Input Files (*.inp);;All (*)'
        s = QFileDialog.getOpenFileName(self, 'Input File Name',
                                              '', filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        fileName = s[0]

        # Read given input file
        try:
            args = read_input(fileName)
        except ReaderError as r:  # Error reading the input file
            error.showMessage(str(r))

        # Set the number of peaks
        npeaks = len(args.num)
        if npeaks < 2:
            error.showMessage('Need at least 2 peaks for exchange')
            return
        elif npeaks > 4:
            error.showMessage('This GUI can only handle up to 4 peaks. '
                              'Use the command-line version for an arbitrary '
                              'number of peaks')
            return
        self.exchange.setNumPeaks(npeaks)

        # Set the exchange
        matrix = ZMat(npeaks, args.exchanges, args.exchange_rates,
                      args.symmetric_exchange)
        self.exchange.setMatrixSymmetry(args.symmetric_exchange)
        self.exchange.setMatrix(matrix)

        # Set the rate
        if 'lifetime' in args:
            self.rate.setUnit(args.lifetime[1])
            self.rate.setRate(args.lifetime[0])
        else:
            self.rate.setUnit(args.rate[1])
            self.rate.setRate(args.rate[0])

        # Set the peak data
        self.peak.setPeaks(args.vib, args.Gamma_Lorentz, args.Gamma_Gauss,
                           args.heights)

        # Plot this data
        self.control.setDataForPlot()

        # Plot raw data if it exists
        if args.raw is not None:
            self.rawName = args.rawName
            self.plot.setRawData(args.raw)
            self.plot.plotRawData()
            self.clear.setEnabled(True)

        # Set the limits
        self.scale.setValue(args.xlim[0], args.xlim[1], args.reverse)

    def saveToInput(self):
        '''Save current settings to current input file if available'''
        if not self.control.hasPlot:
            error.showMessage('Cannot save.. there is no data to save yet')
            return
        if self.fileName is None:
            self.saveToInputAs()
        else:
            self.inputGen(self.fileName)

    def saveToInputAs(self):
        '''Save current settings to an input file of specified name'''
        if not self.control.hasPlot:
            error.showMessage('Cannot save.. there is no data to save yet')
            return
        filter = 'Input Files (*.inp);;All (*)'
        d = '' if self.fileName is None else self.fileName
        s = QFileDialog.getSaveFileName(self, 'Input File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.fileName = s[0]

        # Generate the input file
        self.inputGen(self.fileName)

    def saveAsPDF(self):
        '''Save plot as a PDF'''
        if not self.control.hasPlot:
            error.showMessage('Cannot save.. there is no data to save yet')
            return
        filter = 'PDF Documents (*.pdf);;All (*)'
        d = '' if self.pdfName is None else self.pdfName
        s = QFileDialog.getSaveFileName(self, 'PDF File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.pdfName = s[0]

        # Set up the PDF printer
        printer = QPrinter()
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOrientation(QPrinter.Landscape)
        printer.setOutputFileName(self.pdfName)
        printer.setCreator('RAPID')

        # Send to the plot for printing
        p = QPainter()
        p.begin(printer)
        x, y = self.plot.calculatedData()
        plt = pgplot(x, y,
                     antialias=True,
                     connect='all',
                     pen={'color': 'b', 'width': 0})
        plt.setLabel('bottom', "Frequency (Wavenumbers, cm<sup>-1</sup>)")
        plt.getAxis('bottom').setPen('k')
        plt.setLabel('left', "Intensity (Normalized)")
        plt.getAxis('left').setPen('k')
        plt.setYRange(0, 1.1, padding=0)
        plt.invertX(self.plot.reversed)
        plt.setBackground('w')  # White

        # The raw (experimental) data, if any
        if self.plot.rawData is not None:
            data = self.plot.getRawData()
            x, y = data[:,0], data[:,1]
            curve2 = PlotCurveItem(x, y,
                                   antialias=True,
                                   connect='all',
                                   pen={'color': 'g', 'width': 0})
            plt.addItem(curve2)
        plt.render(p)
        p.end()

    def exportXYData(self):
        '''Export current spectrum to XY data'''
        if not self.control.hasPlot:
            error.showMessage('Cannot export.. there is no data to export yet')
            return
        filter = 'Data Files (*.txt *.data);;All (*)'
        d = '' if self.expName is None else self.expName
        s = QFileDialog.getSaveFileName(self, 'Calculated XY Data File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.expName = s[0]

        # Grab the XY data from the plot
        x, y = self.plot.calculatedData()
        # Save in a standard format
        try:
            write_data(x, y, self.expName)
        except (IOError, OSError) as e:
            error.showMessage(str(e))

    def exportRawData(self):
        '''Export current raw data to XY data'''
        if self.plot.rawData is None:
            error.showMessage('Cannot export.. there is no raw data to export yet')
            return
        filter = 'Data Files (*.txt *.data);;All (*)'
        d = '' if self.rawExpName is None else self.rawExpName
        s = QFileDialog.getSaveFileName(self, 'Raw XY Data File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.rawExpName = s[0]

        # Grab the raw XY data from the plot
        data = self.plot.getRawData()
        # Save in a standard format
        try:
            write_data(data[:,0], data[:,1], self.rawExpName)
        except (IOError, OSError) as e:
            error.showMessage(str(e))

    def importRawData(self):
        '''Import data from an XY file'''
        filter = 'Data Files (*.txt *.data);;All (*)'
        d = '' if self.rawName is None else self.rawName
        s = QFileDialog.getOpenFileName(self, 'Raw XY Data File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.rawName = s[0]

        # Load raw data and plot in a second curve
        rawData = loadtxt(str(self.rawName))
        self.plot.setRawData(rawData)
        self.plot.plotRawData()
        self.clear.setEnabled(True)

    def makeScript(self):
        '''Open parameters from an input file'''
        if not self.control.hasPlot:
            error.showMessage('Cannot save.. there is no data to save yet')
            return
        filter = 'Python Scripts (*.py)'
        d = '' if self.scriptName is None else self.scriptName
        s = QFileDialog.getSaveFileName(self, 'Python Script File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.scriptName = s[0]

        # Get parameters needed
        xlim, rev, oldp, newp = self.control.getParametersForScript()
        x, y = self.plot.calculatedData()
        if self.clear.isEnabled():
            raw = self.plot.rawData
        else:
            raw = None
        save_script(x, y, raw, xlim, rev, oldp, newp, self.scriptName)

    def inputGen(self, fileName):
        '''Generate an input file'''

        # Open file for writing        
        try:
            fl = open(fileName, 'w')
        except (IOError, OSError) as e:
            error.showError(str(e))

        # Generate a template string to print
        s = dedent('''\
            # The rate or lifetime of the reaction
            {rate}

            # The exchange matrix
            {exchange}

            # The peak data
            {peaks}

            # The plot limits
            {limits}

            # Raw input file, if any
            {raw}
            ''')

        # Get the parameters from the underlying data
        xlim, rev, rate, exchange, peaks = self.control.getParametersForInput()

        # Create the rate string
        if rate[1] in ('s', 'ns', 'ps', 'fs'):
            lr = 'lifetime'
        else:
            lr = 'rate'
        ratestr = '{0} {1[0]:.3G} {1[1]}'.format(lr, rate)

        # Create exchange string
        exstr = []
        if not exchange[2]:
            exstr.append('nosym')
        f = 'exchange {0:d} {1:d} {2:.3f}'
        for indx, r in zip(exchange[1], exchange[0]):
            exstr.append(f.format(indx[0]+1, indx[1]+1, r))
        exstr = '\n'.join(exstr)

        # Create peak string
        peakstr = []
        f = 'peak {0:.2f} {1:.3f} L={2:.3f} G={3:.3f}'
        for p, l, g, h in zip(peaks[0], peaks[1], peaks[2], peaks[3]):
            peakstr.append(f.format(p, h, l, g))
        peakstr = '\n'.join(peakstr)
            
        # Create the limits string
        limitstr = 'xlim {0[0]:d} {0[1]:d}'.format(xlim)
        if rev:
            limitstr += '\nreverse'

        # Create the IO string
        if self.rawName is not None:
            rawstr = 'raw {0}'.format(self.rawName)
        else:
            rawstr = ''

        # Write the string to file
        fl.write(s.format(rate=ratestr, peaks=peakstr, limits=limitstr,
                          exchange=exstr, raw=rawstr))

        # Close file
        fl.close()
Exemple #31
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(598, 450)
        self.icon = QIcon(":/icons/uglytheme/48x48/polibeepsync.png")
        Form.setWindowIcon(self.icon)
        Form.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(Form)
        self.tabWidget.setObjectName("tabWidget")

        # Tab General Settings
        self.tab = QWidget()
        self.tab.setObjectName("tab")
        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label_2 = QLabel(self.tab)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
        self.label = QLabel(self.tab)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.password = QLineEdit(self.tab)
        self.password.setMaximumSize(QSize(139, 16777215))
        self.password.setEchoMode(QLineEdit.Password)
        self.password.setObjectName("password")
        self.gridLayout.addWidget(self.password, 3, 1, 1, 1)
        self.userCode = QLineEdit(self.tab)
        self.userCode.setMaximumSize(QSize(139, 16777215))
        self.userCode.setText("")
        self.userCode.setObjectName("userCode")
        self.gridLayout.addWidget(self.userCode, 1, 1, 1, 1)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 1, 2, 1, 1)
        self.verticalLayout_2.addLayout(self.gridLayout)
        self.trylogin = QPushButton(self.tab)
        self.trylogin.setMaximumSize(QSize(154, 16777215))
        self.trylogin.setObjectName("trylogin")
        self.verticalLayout_2.addWidget(self.trylogin)
        self.login_attempt = QLabel(self.tab)
        self.login_attempt.setText("Logging in, please wait.")
        self.login_attempt.setStyleSheet("color: rgba(0, 0, 0, 0);")
        self.login_attempt.setObjectName("login_attempt")
        self.verticalLayout_2.addWidget(self.login_attempt)
        spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem1)
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QLabel(self.tab)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.rootfolder = QLineEdit(self.tab)
        self.rootfolder.setMinimumSize(QSize(335, 0))
        self.rootfolder.setMaximumSize(QSize(335, 16777215))
        self.rootfolder.setInputMask("")
        self.rootfolder.setReadOnly(True)
        self.rootfolder.setObjectName("rootfolder")
        self.horizontalLayout_3.addWidget(self.rootfolder)
        self.changeRootFolder = QPushButton(self.tab)
        self.changeRootFolder.setObjectName("changeRootFolder")
        self.horizontalLayout_3.addWidget(self.changeRootFolder)
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem2)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_5 = QLabel(self.tab)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_5.addWidget(self.label_5)
        self.timerMinutes = QSpinBox(self.tab)
        self.timerMinutes.setObjectName("timerMinutes")
        self.horizontalLayout_5.addWidget(self.timerMinutes)
        self.label_6 = QLabel(self.tab)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_5.addWidget(self.label_6)
        self.syncNow = QPushButton(self.tab)
        self.syncNow.setObjectName("syncNow")
        self.horizontalLayout_5.addWidget(self.syncNow)
        spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem3)
        self.verticalLayout_2.addLayout(self.horizontalLayout_5)
        self.addSyncNewCourses = QCheckBox(self.tab)
        self.addSyncNewCourses.setObjectName("addSyncNewCourses")
        self.verticalLayout_2.addWidget(self.addSyncNewCourses)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.tab, "")

        # Tab Courses
        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.horizontalLayout_2 = QHBoxLayout(self.tab_2)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_6 = QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.refreshCourses = QPushButton(self.tab_2)
        self.refreshCourses.setObjectName("refreshCourses")
        self.horizontalLayout_6.addWidget(self.refreshCourses)
        spacerItem4 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem4)
        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.coursesView = CoursesListView(self.tab_2)
        self.coursesView.setObjectName("coursesView")
        self.verticalLayout_3.addWidget(self.coursesView)
        self.horizontalLayout_2.addLayout(self.verticalLayout_3)
        self.tabWidget.addTab(self.tab_2, "")

        # Tab Status
        self.tab_3 = QWidget()
        self.tab_3.setObjectName("tab_3")
        self.horizontalLayout_7 = QHBoxLayout(self.tab_3)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.verticalLayout_4 = QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_8 = QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.about = QPushButton(self.tab_3)
        self.about.setObjectName("about")
        self.horizontalLayout_8.addWidget(self.about)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_8.addItem(spacerItem5)
        self.verticalLayout_4.addLayout(self.horizontalLayout_8)
        self.status = QTextEdit(self.tab_3)
        self.status.setTextInteractionFlags(Qt.TextSelectableByKeyboard
                                            | Qt.TextSelectableByMouse)
        self.status.setObjectName("status")
        self.verticalLayout_4.addWidget(self.status)
        self.horizontalLayout_7.addLayout(self.verticalLayout_4)
        self.tabWidget.addTab(self.tab_3, "")

        self.tab_4 = QWidget()
        self.tab_4.setObjectName("tab_4")
        self.verticalLayout.addWidget(self.tabWidget)

        self.okButton = QDialogButtonBox(Form)
        self.okButton.setStandardButtons(QDialogButtonBox.Ok)
        self.okButton.setObjectName("okButton")
        self.okButton.clicked.connect(self.hide)
        self.verticalLayout.addWidget(self.okButton)

        self.statusLabel = QLabel(Form)
        self.statusLabel.setObjectName("statusLabel")
        self.verticalLayout.addWidget(self.statusLabel)

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle("poliBeePsync")
        if pysideVersion == '1.2.2':
            self.label_2.setText(
                QApplication.translate("Form", "Password", None,
                                       QApplication.UnicodeUTF8))
            self.label.setText(
                QApplication.translate("Form", "User code", None,
                                       QApplication.UnicodeUTF8))
            self.trylogin.setText(
                QApplication.translate("Form", "Try login credentials", None,
                                       QApplication.UnicodeUTF8))
            self.login_attempt.setText(
                QApplication.translate("Form", "Login successful", None,
                                       QApplication.UnicodeUTF8))
            self.label_4.setText(
                QApplication.translate("Form", "Root folder", None,
                                       QApplication.UnicodeUTF8))
            self.changeRootFolder.setText(
                QApplication.translate("Form", "Change", None,
                                       QApplication.UnicodeUTF8))
            self.label_5.setText(
                QApplication.translate("Form", "Sync every", None,
                                       QApplication.UnicodeUTF8))
            self.label_6.setText(
                QApplication.translate("Form", "minutes", None,
                                       QApplication.UnicodeUTF8))
            self.syncNow.setText(
                QApplication.translate("Form", "Sync now", None,
                                       QApplication.UnicodeUTF8))
            self.addSyncNewCourses.setText(
                QApplication.translate(
                    "Form", "Automatically add and sync new available courses",
                    None, QApplication.UnicodeUTF8))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab),
                QApplication.translate("Form", "General settings", None,
                                       QApplication.UnicodeUTF8))
            self.refreshCourses.setText(
                QApplication.translate("Form", "Refresh list", None,
                                       QApplication.UnicodeUTF8))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_2),
                QApplication.translate("Form", "Courses", None,
                                       QApplication.UnicodeUTF8))
            self.about.setText(
                QApplication.translate("Form", "About", None,
                                       QApplication.UnicodeUTF8))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_3),
                QApplication.translate("Form", "Status", None,
                                       QApplication.UnicodeUTF8))
        else:
            self.label_2.setText(
                QApplication.translate("Form", "Password", None))
            self.label.setText(
                QApplication.translate("Form", "User code", None))
            self.trylogin.setText(
                QApplication.translate("Form", "Try login credentials", None))
            self.login_attempt.setText(
                QApplication.translate("Form", "Login successful", None))
            self.label_4.setText(
                QApplication.translate("Form", "Root folder", None))
            self.changeRootFolder.setText(
                QApplication.translate("Form", "Change", None))
            self.label_5.setText(
                QApplication.translate("Form", "Sync every", None))
            self.label_6.setText(
                QApplication.translate("Form", "minutes", None))
            self.syncNow.setText(
                QApplication.translate("Form", "Sync now", None))
            self.addSyncNewCourses.setText(
                QApplication.translate(
                    "Form", "Automatically add and sync new available courses",
                    None))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab),
                QApplication.translate("Form", "General settings", None))
            self.refreshCourses.setText(
                QApplication.translate("Form", "Refresh list", None))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_2),
                QApplication.translate("Form", "Courses", None))
            self.about.setText(QApplication.translate("Form", "About", None))
            self.tabWidget.setTabText(
                self.tabWidget.indexOf(self.tab_3),
                QApplication.translate("Form", "Status", None))
    def __init__ (self, lcvsa_dict, parent = None):
        QDialog.__init__(self)
        
        if isinstance(lcvsa_dict, dict):
            self._lcvsa_dict = lcvsa_dict
        else:
            self._lcvsa_dict = {lcvsa_dict.__class__.__name__+ "_1": lcvsa_dict}
        self._lcvsa = self._lcvsa_dict[self._lcvsa_dict.keys()[0]]

        # Get the various color maps from pylab        
        self.color_maps=[m for m in pylab.cm.datad if not m.endswith("_r")]
        self.color_maps += ["AA_traditional_"]
        self.color_maps.sort()

        self.mplwin_list = [] # The list of matplotlib windows
        
        # Create the major frames.
        main_frame = QHBoxLayout()

        self._explorer_windows = []
        leftWidget = QWidget()
        leftWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setLayout(main_frame)
        main_frame.setContentsMargins(5, 5, 5, 5)
        left_frame = QVBoxLayout()
        left_frame.setContentsMargins(1, 1, 1, 1)
        left_frame.setSpacing(5)
        main_frame.addWidget(leftWidget)
        main_frame.setAlignment(leftWidget, QtCore.Qt.AlignTop)
        leftWidget.setLayout(left_frame)
        leftWidget.setMinimumSize(600, 750)
        leftWidget.setMaximumWidth(750)

        
        right_frame = qNotebook() # The right frame holds a qNotebook
        main_frame.addLayout(right_frame)
        self._lframe = left_frame
        self._main_frame = main_frame
        self._rframe = right_frame

        # Put a small frame at the top of the left frame to hold some checkboxes, and a pop list for selecting analyses
        self.top_left_frame = QVBoxLayout()
        left_frame.addLayout(self.top_left_frame)

        # Make the checkboxes
        self.inline = qHotField("Put images in the notebook", bool, False)
        self.top_left_frame.addWidget(self.inline)
        self.show_legends = qHotField("Show legends on charts", bool, True)
        self.top_left_frame.addWidget(self.show_legends)
        self.show_titles = qHotField("Show titles on charts", bool, True)
        self.top_left_frame.addWidget(self.show_titles)
        self.show_tables_in_explorer = qHotField("Show tables in explorer", bool, False)
        self.top_left_frame.addWidget(self.show_tables_in_explorer)

        # Create the popup list that allows the selection of an analysis, for the case in which there are multiple analyses.
        if not isinstance(self._lcvsa, MonteCarloDescriptorClass):
            self.analysis_popup_list = AnalysisSelector(self)
            self.top_left_frame.addWidget(self.analysis_popup_list)

        # create the instance of helpForWindow so we can display help
        self.help_instance = helpForWindow()

        # Make the commandTabWidget that will hold tabs with all of the commands
        self.tabWidget = CommandTabWidget(self.help_instance)
        self._lframe.addWidget(self.tabWidget)
        self.set_up_left_frame() # usually calls make_widgets which adds the commands to the tabs

        # Add the field for executing code.
        self.exec_frame = QHBoxLayout()
        left_frame.addLayout(self.exec_frame)
        qmy_button(self.exec_frame, self.execute_code, "Execute")
        self.code_field = QLineEdit("")
        self.code_field.setMaximumWidth(400)
        self.code_field.returnPressed.connect(self.execute_code)
        self.exec_frame.addWidget(self.code_field)
        # left_frame.addStretch()
        main_frame.setStretch(0,1)
        main_frame.setStretch(1, 2)
        
        if self._lcvsa.saved_notebook_html != None:
            right_frame.append_text(self._lcvsa.saved_notebook_html)
            # text_doc = self._rframe._teditor.document()
            for imageFileName in self._lcvsa.saved_image_data_dict.keys():
                self._rframe.add_image_data_resource(self._lcvsa.saved_image_data_dict[imageFileName], imageFileName)
            right_frame.image_counter = self._lcvsa.saved_image_counter
                # text_doc.addResources(QTextDocument.ImageResource, QUrl(imageFileName), self._lcvsa.saved_notebook_image_dict[imageFileName])
        else:
            self.gprint("\n<b>Base class is " + self._lcvsa.__class__.__name__ + "\n</b>")
            self.display_analysis_parameters()
Exemple #33
0
    def _initUI(self):
        # Variables
        model_forcing = _InteractionForcingTableModel()

        # Actions
        act_add_forcing = QAction(getIcon("list-add"), "Add interaction forcing", self)
        act_remove_forcing = QAction(getIcon("list-remove"), "Remove interaction forcing", self)

        # Widgets
        self._lbl_elastic_scattering_c1 = QLabel('C1')
        self._lbl_elastic_scattering_c1.setStyleSheet("color: blue")
        self._txt_elastic_scattering_c1 = MultiNumericalLineEdit()
        self._txt_elastic_scattering_c1.setValidator(_ElasticScatteringValidator())
        self._txt_elastic_scattering_c1.setValues([0.0])

        self._lbl_elastic_scattering_c2 = QLabel('C2')
        self._lbl_elastic_scattering_c2.setStyleSheet("color: blue")
        self._txt_elastic_scattering_c2 = MultiNumericalLineEdit()
        self._txt_elastic_scattering_c2.setValidator(_ElasticScatteringValidator())
        self._txt_elastic_scattering_c2.setValues([0.0])

        self._lbl_cutoff_energy_inelastic = QLabel('Inelastic collisions')
        self._lbl_cutoff_energy_inelastic.setStyleSheet("color: blue")
        self._txt_cutoff_energy_inelastic = MultiNumericalLineEdit()
        self._txt_cutoff_energy_inelastic.setValidator(_CutoffEnergyValidator())
        self._txt_cutoff_energy_inelastic.setValues([50.0])
        self._cb_cutoff_energy_inelastic = UnitComboBox('eV')

        self._lbl_cutoff_energy_bremsstrahlung = QLabel('Bremsstrahlung emission')
        self._lbl_cutoff_energy_bremsstrahlung.setStyleSheet("color: blue")
        self._txt_cutoff_energy_bremsstrahlung = MultiNumericalLineEdit()
        self._txt_cutoff_energy_bremsstrahlung.setValidator(_CutoffEnergyValidator())
        self._txt_cutoff_energy_bremsstrahlung.setValues([50.0])
        self._cb_cutoff_energy_bremsstrahlung = UnitComboBox('eV')

        self._lbl_maximum_step_length = QLabel('Maximum step length')
        self._lbl_maximum_step_length.setStyleSheet("color: blue")
        self._txt_maximum_step_length = MultiNumericalLineEdit()
        self._txt_maximum_step_length.setValidator(_MaximumStepLengthValidator())
        self._txt_maximum_step_length.setValues([1e15])
        self._cb_maximum_step_length_unit = UnitComboBox('m')

        self._tbl_forcing = QTableView()
        self._tbl_forcing.setModel(model_forcing)
        self._tbl_forcing.setItemDelegate(_InteractionForcingDelegate())
        header = self._tbl_forcing.horizontalHeader()
        header.setResizeMode(QHeaderView.Stretch)

        self._tlb_forcing = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self._tlb_forcing.addWidget(spacer)
        self._tlb_forcing.addAction(act_add_forcing)
        self._tlb_forcing.addAction(act_remove_forcing)

        # Layouts
        layout = QHBoxLayout()

        layout.addLayout(_MaterialDialog._initUI(self), 1)

        frame = QFrame()
        frame.setFrameShape(QFrame.VLine)
        frame.setFrameShadow(QFrame.Sunken)
        layout.addWidget(frame)

        sublayout = QVBoxLayout()

        box_elastic_scattering = QGroupBox("Elastic scattering")
        boxlayout = QFormLayout()
        boxlayout.addRow(self._lbl_elastic_scattering_c1, self._txt_elastic_scattering_c1)
        boxlayout.addRow(self._lbl_elastic_scattering_c2, self._txt_elastic_scattering_c2)
        box_elastic_scattering.setLayout(boxlayout)
        sublayout.addWidget(box_elastic_scattering)

        box_cutoff_energy = QGroupBox("Cutoff energy")
        boxlayout = QFormLayout()
        boxsublayout = QHBoxLayout()
        boxsublayout.addWidget(self._txt_cutoff_energy_inelastic, 1)
        boxsublayout.addWidget(self._cb_cutoff_energy_inelastic)
        boxlayout.addRow(self._lbl_cutoff_energy_inelastic, boxsublayout)
        boxsublayout = QHBoxLayout()
        boxsublayout.addWidget(self._txt_cutoff_energy_bremsstrahlung, 1)
        boxsublayout.addWidget(self._cb_cutoff_energy_bremsstrahlung)
        boxlayout.addRow(self._lbl_cutoff_energy_bremsstrahlung, boxsublayout)
        box_cutoff_energy.setLayout(boxlayout)
        sublayout.addWidget(box_cutoff_energy)

        subsublayout = QFormLayout()
        subsubsublayout = QHBoxLayout()
        subsubsublayout.addWidget(self._txt_maximum_step_length, 1)
        subsubsublayout.addWidget(self._cb_maximum_step_length_unit)
        subsublayout.addRow(self._lbl_maximum_step_length, subsubsublayout)
        sublayout.addLayout(subsublayout)

        box_forcing = QGroupBox('Interaction forcing')
        boxlayout = QVBoxLayout()
        boxlayout.addWidget(self._tbl_forcing)
        boxlayout.addWidget(self._tlb_forcing)
        box_forcing.setLayout(boxlayout)
        sublayout.addWidget(box_forcing)

        sublayout.addStretch()

        layout.addLayout(sublayout, 1)

        # Signals
        self._txt_elastic_scattering_c1.textChanged.connect(self._onElasticScatteringC1Changed)
        self._txt_elastic_scattering_c2.textChanged.connect(self._onElasticScatteringC2Changed)
        self._txt_cutoff_energy_inelastic.textChanged.connect(self._onCutoffEnergyInelasticChanged)
        self._txt_cutoff_energy_bremsstrahlung.textChanged.connect(self._onCutoffEnergyBremsstrahlungChanged)
        self._txt_maximum_step_length.textChanged.connect(self._onMaximumStepLengthChanged)

        act_add_forcing.triggered.connect(self._onForcingAdd)
        act_remove_forcing.triggered.connect(self._onForcingRemove)

        return layout
class MainWindow(QWidget):
    """Class that contains the main window
    Includes two panels: 
    left panel -> control
    right panel -> plot and summary
    """
    def __init__(self, parent=None):

        QWidget.__init__(self)

        # Create the QVBoxLayout that lays out the whole form
        self.main_panel = QHBoxLayout()
        self.lpanel = QHBoxLayout()
        self.rpanel = QVBoxLayout()
        self.plot_box = QHBoxLayout()
        self.summary_box = QHBoxLayout()

        # Control widget
        self.control = psim_control.ControlLayout()
        self.control.sim_button.clicked.connect(self.button_pressed)

        # Plot Widget
        self.graph = psim_plot.MatplotlibWidget()

        # Summary Widget
        self.summary = psim_summary.SummaryLayout()

        # Adding plot to left panel and control widget to right panel
        self.lpanel.addWidget(self.control)
        self.rpanel.addWidget(self.graph)
        self.rpanel.addWidget(self.summary)

        # Adding lpanel and rpanel widget to the main MainWindow
        self.main_panel.addLayout(self.lpanel)
        self.main_panel.addLayout(self.rpanel)
        # self.main_panel.addStretch(1)
        self.setLayout(self.main_panel)

        self.df = None

    @Slot()
    def button_pressed(self):
        """Actions when sim button is pressed"""
        policy_name = self.control.policy.currentText()

        pam1 = int(self.control.p1.text())
        pam2 = int(self.control.p2.text())
        periods = int(self.control.periods.text())

        product = Product(
            name="Product_A",
            #demand_dist=make_distribution(constant, 192),
            #lead_time_dist=make_distribution(constant, 0),
            demand_dist=make_distribution(np.random.normal, 192, 30),
            lead_time_dist=make_distribution(np.random.triangular, 0, 1, 2),
            initial_inventory=500,
            price=8)

        if policy_name == 'Qs':
            policy = {'method': 'Qs', 'arguments': {'Q': pam1, 's': pam2}}
        elif policy_name == 'Ss':
            policy = {'method': 'Ss', 'arguments': {'S': pam1, 's': pam2}}
        elif policy_name == 'RS':
            policy = {'method': 'RS', 'arguments': {'R': pam1, 'S': pam2}}
        elif policy_name == 'RSs':
            pam3 = int(self.control.p3.text())
            policy = {
                'method': 'RSs',
                'arguments': {
                    'R': pam1,
                    'S': pam2,
                    's': pam3
                }
            }

        self.df = make_data(product, policy, periods)

        # Update summary
        K = 2  # cost of one order
        I = 0.02
        ordering_cost = sum([i > 0 for i in self.df['order']]) * K
        purchasing_cost = (product.initial_inventory +
                           sum(self.df['order'])) * product.price
        holding_cost = sum(self.df['avg_inv']) * (
            (product.price * I) / float(periods))
        shortage_cost = sum(self.df['lost_sales']) * product.price
        total_cost = ordering_cost + purchasing_cost + holding_cost + shortage_cost
        service = 1 - (sum(self.df['lost_sales']) / sum(self.df['demand']))
        print("purchasing_cost: ", purchasing_cost)
        print("ordering cost: ", ordering_cost)
        print("holding_cost: ", holding_cost)
        print("shortage_cost: ", shortage_cost)

        self.summary.inventory_cost.setText("{:,.2f}".format(total_cost))
        self.summary.service_level.setText("{:.2%}".format(service))
        self.graph.Plot(self.df, policy, periods)
        self.graph.draw()
Exemple #35
0
    def setupUI(self):
        """Arranges GUI elements inside the widget properly"""

        paneLayout = QHBoxLayout()
        paneLayout.setContentsMargins(0, 0, 0, 0)

        leftPane = QFrame()
        leftPane.setObjectName("leftPane")

        leftPaneLayout = QVBoxLayout()
        leftPaneLayout.setContentsMargins(20, 20, 20, 10)
        heading = QLabel("Select Employee: ")
        heading.setObjectName("heading")
        leftPaneLayout.addWidget(heading)
        leftPaneLayout.addSpacing(10)

        datelayout = QHBoxLayout()
        datelayout.addWidget(QLabel("Salary for month of "))
        datelayout.addWidget(self.month)
        datelayout.addWidget(self.year)
        datelayout.addStretch()
        leftPaneLayout.addLayout(datelayout)

        leftForm = QFormLayout()
        leftForm.setSpacing(10)
        leftForm.addRow(QLabel("Name"), self.name)
        leftForm.addRow(QLabel("ID No."), self.id)
        leftPaneLayout.addLayout(leftForm)

        leftPaneLayout.addStretch()
        leftPane.setLayout(leftPaneLayout)
        paneLayout.addWidget(leftPane)

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)
        form = QFormLayout()
        form.setSpacing(10)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)

        infoGroup = QGroupBox("Basic Info")
        infoGroup.setLayout(form)
        layout.addWidget(infoGroup)

        leftForm = QFormLayout()
        leftForm.addRow(QLabel("Dearness Allowance"), self.da_percent)
        leftForm.addRow(QLabel("Housing Rent Allowance"), self.hra_percent)
        leftForm.addRow(QLabel("Transport Allowance"), self.ta_percent)

        leftGroup = QGroupBox("Allowances")
        leftGroup.setLayout(leftForm)

        rightForm = QFormLayout()
        rightForm.addRow(QLabel("Income Tax"), self.it_percent)
        rightForm.addRow(QLabel("Profession Tax"), self.pt_percent)

        rightGroup = QGroupBox("Deductions")
        rightGroup.setLayout(rightForm)

        table = QHBoxLayout()
        table.addWidget(leftGroup)
        table.addWidget(rightGroup)

        layout.addLayout(table)

        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnCalculate)

        layout.addLayout(bttnLayout)

        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
Exemple #36
0
    def __init__(self,parent,dialog_title,list_title,form_title,mapped_klass,table_prototype,form_prototype,sort_criterion,index_builder):

        """
        sort_criterion is a SQLAlchemy colum used when querying the list of edited objects to sort it.
        index_builder : a function that takes an object of the mapped class and returns a string
           suitable for index building.
        """
        super(MetaFormDialog,self).__init__(parent)

        self.index_builder = index_builder
        self.sort_criterion = sort_criterion
        self.form_prototype = form_prototype
        self.mapped_klass = mapped_klass
        # Locate the primary key
        # this will work only with a one-field PK
        pk_column = list(filter( lambda c:c.primary_key, self.mapped_klass.__table__.columns))[0]
        self.key_field = pk_column.name


        self.in_save = False

        # The current item is the one currently shown in the
        # form. If it's None, then the form contains data
        # for a soon-to-be created item. Else, it's a frozen
        # copy. Since we work on frozen stuff, we can carry
        # the object around safely

        self.current_item = None


        self.list_model = PrototypedModelView(table_prototype, self)

        self.list_model_filtered = FilteringModel(self)
        self.list_model_filtered.setSourceModel(self.list_model)

        self.line_in = FilterLineEdit()
        self.line_in.key_down.connect(self._focus_on_list)
        self.line_in.textChanged.connect(self._filter_changed)

        self.list_view = PrototypedQuickView(table_prototype, self)
        self.list_view.setTabKeyNavigation(False)


        self.setWindowTitle(dialog_title)
        self.title_widget = TitleWidget(dialog_title,self)

        self.list_view.setModel(self.list_model_filtered)
        self.list_view.horizontalHeader().hide()
        self.list_view.verticalHeader().hide()
        self.list_view.horizontalHeader().setStretchLastSection(True)


        blayout = QVBoxLayout()

        b = QPushButton(_("New"))
        b.setObjectName("newButton")

        b.clicked.connect(self.create_action)
        blayout.addWidget(b)

        b = QPushButton(_("Save"))
        b.setObjectName("saveButton")
        b.clicked.connect(self.save_action)
        blayout.addWidget(b)

        b = QPushButton(_("Delete"))
        b.setObjectName("deleteButton")
        b.clicked.connect(self.delete_action)
        blayout.addWidget(b)

        blayout.addStretch()

        self.buttons = QDialogButtonBox()
        self.buttons.addButton( QDialogButtonBox.Ok)

        # BUG According to QLayout, the layout takes ownership of the widget
        # therefore, we have to pay attention when deleting...

        form_layout = QFormLayout()
        for p in self.form_prototype:
            w = p.edit_widget(self)
            w.setEnabled(p.is_editable)
            w.setObjectName("form_" + p.field)
            form_layout.addRow( p.title, w)

        top_layout = QVBoxLayout()
        top_layout.addWidget(self.title_widget)

        hl = QHBoxLayout()


        vlayout = QVBoxLayout()

        vlayout.addWidget(self.line_in)
        vlayout.addWidget(self.list_view)
        # gbox = QGroupBox(list_title,self)
        # gbox.setLayout(vlayout)
        gbox = SubFrame(list_title,vlayout,self)
        hl.addWidget(gbox)

        # gbox = QGroupBox(form_title,self)
        # gbox.setLayout(form_layout)
        gbox = SubFrame(form_title,form_layout,self)
        hl.addWidget(gbox)
        hl.addLayout(blayout)

        # hl.setStretch(0,0.3)
        # hl.setStretch(1,0.7)
        # hl.setStretch(2,0)

        top_layout.addLayout(hl)
        top_layout.addWidget(self.buttons)

        self.setLayout(top_layout) # QWidget takes ownership of the layout
        self.buttons.accepted.connect(self.reject)

        QWidget.setTabOrder(self.line_in, self.list_view)

        nb_objs = self._refresh_list()
        self.line_in.setFocus()
        self.list_view.selectionModel().currentChanged.connect(self.selected_item_changed) # FIXME Clear ownership issue
        if nb_objs > 0:
            self.list_view.selectRow(0)
        else:
            # Special case to automaticaly enter creation mode when
            # the list is empty
            self.create_action()
Exemple #37
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())
Exemple #38
0
        return "{} {}".format(self.name, self.price)


# form_rendered._field_map['name'].set_value("king")
# form_rendered._field_map['price'].set_value("1337")

data = Data(name="King Kong", price=123)

d = {'list': ['alpha', 'beta', 'gamma'], 'group': data}

form_rendered = Render(form)
form_rendered.set_all_values(data)
form_rendered.read_all_values(data)
print(data)

d = QDialog()
view = PySide.QtWebKit.QWebView(d)
view.setZoomFactor(1.5)
# view.setHtml("Hello world <a href='eulu.html'>Link</a>")
# view.setUrl('file:///Users/stc/Dropbox/index.html')
view.setUrl(
    'file:///PORT-STC/PRIVATE/SlickGrid-2.2.6/examples/example14-highlighting.html'
)
top_layout = QHBoxLayout()
top_layout.addWidget(view)
top_layout.addLayout(form_rendered.render())
d.setLayout(top_layout)
d.show()

d.exec_()
Exemple #39
0
class ui(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUI()
        self.id = 1
        self.lines = []
        self.editable = True
        self.des_sort = True
        self.faker = Factory.create()
        self.btn_add.clicked.connect(self.add_line)
        self.btn_del.clicked.connect(self.del_line)
        self.btn_modify.clicked.connect(self.modify_line)
        self.btn_select_line.clicked.connect(self.select_line)
        self.btn_select_single.clicked.connect(self.deny_muti_line)
        self.btn_sort.clicked.connect(self.sortItem)
        self.btn_set_header.clicked.connect(self.setheader)
        self.btn_set_middle.clicked.connect(self.middle)
        self.table.cellChanged.connect(self.cellchange)
        self.btn_noframe.clicked.connect(self.noframe)


#     # Sess = sessionmaker(bind = engine)

    def setupUI(self):
        self.setWindowTitle(windowTital)
        self.resize(640, 480)
        self.table = QTableWidget(self)
        self.btn_add = QPushButton(u'增加')
        self.btn_del = QPushButton(u'删除')
        self.btn_modify = QPushButton(u'可以编辑')
        self.btn_select_line = QPushButton(u'选择整行')
        self.btn_select_single = QPushButton(u'禁止选多行')
        self.btn_sort = QPushButton(u'以分数排序')
        self.btn_set_header = QPushButton(u'标头设置')
        self.btn_set_middle = QPushButton(u'文字居中加颜色')
        self.btn_noframe = QPushButton(u'取消边框颜色交替')
        self.spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum,
                                      QSizePolicy.Expanding)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.btn_add)
        self.vbox.addWidget(self.btn_del)
        self.vbox.addWidget(self.btn_modify)
        self.vbox.addWidget(self.btn_select_line)
        self.vbox.addWidget(self.btn_select_single)
        self.vbox.addWidget(self.btn_sort)
        self.vbox.addWidget(self.btn_set_header)
        self.vbox.addWidget(self.btn_set_middle)
        self.vbox.addWidget(self.btn_noframe)
        self.vbox.addSpacerItem(
            self.spacerItem)  #可以用addItem也可以用addSpacerItem方法添加,没看出哪里不一样
        self.txt = QLabel()
        self.txt.setMinimumHeight(50)
        self.vbox2 = QVBoxLayout()
        self.vbox2.addWidget(self.table)
        self.vbox2.addWidget(self.txt)
        self.hbox = QHBoxLayout()
        self.hbox.addLayout(self.vbox2)
        self.hbox.addLayout(self.vbox)
        self.setLayout(self.hbox)
        self.table.setColumnCount(4)  ##设置列数
        self.headers = [u'id', u'选择', u'姓名', u'成绩', u'住址']
        self.table.setHorizontalHeaderLabels(self.headers)
        self.show()

    def add_line(self):
        self.table.cellChanged.disconnect()
        row = self.table.rowCount()
        self.table.setRowCount(row + 1)
        id = str(self.id)
        ck = QCheckBox()
        h = QHBoxLayout()
        h.setAlignment(Qt.AlignCenter)
        h.addWidget(ck)
        w = QWidget()
        w.setLayout(h)
        name = self.faker.name()
        score = str(random.randint(50, 99))
        add = self.faker.address()
        self.table.setItem(row, 0, QTableWidgetItem(id))
        self.table.setCellWidget(row, 1, w)
        self.table.setItem(row, 2, QTableWidgetItem(name))
        self.table.setItem(row, 3, QTableWidgetItem(score))
        self.table.setItem(row, 4, QTableWidgetItem(add))
        self.id += 1
        self.lines.append([id, ck, name, score, add])
        self.settext(u'自动生成随机一行数据!,checkbox设置为居中显示')
        self.table.cellChanged.connect(self.cellchange)

    def del_line(self):
        removeline = []
        for line in self.lines:
            if line[1].isChecked():
                row = self.table.rowCount()
                for x in range(row, 0, -1):
                    if line[0] == self.table.item(x - 1, 0).text():
                        self.table.removeRow(x - 1)
                        removeline.append(line)
        for line in removeline:
            self.lines.remove(line)
        self.settext(u'删除在左边checkbox中选中的行,使用了一个笨办法取得行号\n,不知道有没有其他可以直接取得行号的方法!')

    def modify_line(self):
        if self.editable == True:
            self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.btn_modify.setText(u'禁止编辑')
            self.editable = False
        else:
            self.table.setEditTriggers(QAbstractItemView.AllEditTriggers)
            self.btn_modify.setText(u'可以编辑')
            self.editable = True
        self.settext(u'设置,是否可以编辑整个表格')

    def select_line(self):
        if self.table.selectionBehavior() == 0:
            self.table.setSelectionBehavior(1)
            self.btn_select_line.setStyleSheet('background-color:lightblue')
        else:
            self.table.setSelectionBehavior(0)
            self.btn_select_line.setStyleSheet('')
        self.settext(u'默认时,点击单元格,只可选择一个格,此处设置为可选择整行')

    def deny_muti_line(self):
        if self.table.selectionMode() in [2, 3]:
            self.table.setSelectionMode(QAbstractItemView.SingleSelection)
            self.btn_select_single.setStyleSheet('background-color:lightblue')
        else:
            self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)
            self.btn_select_single.setStyleSheet('')
        self.settext(u'点击时会轮换以多行或单行选择,默认是可以同时选择多行')

    def sortItem(self):
        if self.des_sort == True:
            self.table.sortItems(3, Qt.DescendingOrder)
            self.des_sort = False
            self.btn_sort.setStyleSheet('background-color:lightblue')
            self.table.setSortingEnabled(True)  # 设置表头可以自动排序
        else:
            self.table.sortItems(3, Qt.AscendingOrder)
            self.des_sort = True
            self.btn_sort.setStyleSheet('background-color:lightblue')
            self.table.setSortingEnabled(False)
        self.settext(u'点击时会轮换以升序降序排列,但排序时,会使自动列宽失效!')

    def setheader(self):
        font = QFont(u'微软雅黑', 12)
        font.setBold(True)
        self.table.horizontalHeader().setFont(font)  # 设置表头字体
        self.table.setColumnWidth(0, 50)
        self.table.setColumnWidth(1, 50)
        self.table.setColumnWidth(3, 100)
        self.table.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.Stretch)
        self.table.horizontalHeader().setStyleSheet(
            'QHeaderView::section{background:gray}')
        self.table.horizontalHeader().setFixedHeight(50)
        self.table.setColumnHidden(0, True)
        self.btn_set_header.setStyleSheet('background-color:lightblue')
        self.settext(
            u'设置标头字体及字号,隐藏ID列,设置标头除姓名外全部为固定宽度\n,设置姓名列自动扩展宽度,设置标头行高,设置标头背景色')

    def middle(self):
        self.btn_set_middle.setStyleSheet('background-color:lightblue')
        self.table.setStyleSheet('color:green;')
        row = self.table.rowCount()
        for x in range(row):
            for y in range(4):
                if y != 1:
                    item = self.table.item(x, y)
                    item.setTextAlignment(Qt.AlignCenter)
                else:
                    pass
        self.btn_set_middle.setStyleSheet('background-color:lightblue')
        self.settext(u'将文字居中显示,设置文字颜色')

    def cellchange(self, row, col):
        item = self.table.item(row, col)
        txt = item.text()
        self.settext(u'第%s行,第%s列 , 数据改变为:%s' % (row, col, txt))

    def noframe(self):
        self.table.setAlternatingRowColors(True)
        self.table.setFrameStyle(QFrame.NoFrame)
        self.table.setStyleSheet('color:green;'
                                 'gridline-color:white;'
                                 'border:0px solid gray')
        self.settext(u'取消表的框线,\n 取消表格内框')

    def settext(self, txt):
        font = QFont(u'微软雅黑', 10)
        self.txt.setFont(font)
        self.txt.setText(txt)
class MainWindow(QWidget):
    """Class that contains the main window
    Includes two panels: 
    left panel -> control
    right panel -> plot and summary
    """

    def __init__(self, parent=None):

        QWidget.__init__(self)

        # Create the QVBoxLayout that lays out the whole form
        self.main_panel = QHBoxLayout()
        self.lpanel = QHBoxLayout()
        self.rpanel = QVBoxLayout()
        self.plot_box = QHBoxLayout()
        self.summary_box = QHBoxLayout()

        # Control widget
        self.control = psim_control.ControlLayout()
        self.control.sim_button.clicked.connect(self.button_pressed)

        # Plot Widget
        self.graph = psim_plot.MatplotlibWidget()

        # Summary Widget
        self.summary = psim_summary.SummaryLayout()

        # Adding plot to left panel and control widget to right panel
        self.lpanel.addWidget(self.control)
        self.rpanel.addWidget(self.graph)
        self.rpanel.addWidget(self.summary)
        
        # Adding lpanel and rpanel widget to the main MainWindow
        self.main_panel.addLayout(self.lpanel)
        self.main_panel.addLayout(self.rpanel)
        # self.main_panel.addStretch(1)
        self.setLayout(self.main_panel)

        self.df = None

    @Slot()
    def button_pressed(self):
        """Actions when sim button is pressed"""
        policy_name = self.control.policy.currentText()

        pam1 = int(self.control.p1.text())
        pam2 = int(self.control.p2.text())
        periods = int(self.control.periods.text())

        product = Product(name="Product_A",
                          #demand_dist=make_distribution(constant, 192),
                          #lead_time_dist=make_distribution(constant, 0),
                          demand_dist=make_distribution(np.random.normal, 192, 30),
                          lead_time_dist=make_distribution(np.random.triangular, 0, 1, 2),
                          initial_inventory=500,
                          price=8)

        if policy_name == 'Qs':
            policy = {'method': 'Qs', 'arguments': {'Q': pam1, 's': pam2}}
        elif policy_name == 'Ss':
            policy = {'method': 'Ss', 'arguments': {'S': pam1, 's': pam2}}
        elif policy_name == 'RS':
            policy = {'method': 'RS', 'arguments': {'R': pam1, 'S': pam2}}
        elif policy_name == 'RSs':
            pam3 = int(self.control.p3.text())
            policy = {
                'method': 'RSs',
                'arguments': {
                    'R': pam1,
                    'S': pam2,
                    's': pam3}}

        self.df = make_data(product, policy, periods)
        
        # Update summary
        K = 2 # cost of one order
        I = 0.02
        ordering_cost = sum([i > 0 for i in self.df['order']]) * K
        purchasing_cost = (product.initial_inventory + sum(self.df['order'])) * product.price
        holding_cost = sum(self.df['avg_inv']) * ((product.price * I) / float(periods))
        shortage_cost = sum(self.df['lost_sales']) * product.price
        total_cost = ordering_cost + purchasing_cost + holding_cost + shortage_cost
        service = 1 - (sum(self.df['lost_sales']) / sum(self.df['demand']))
        print("purchasing_cost: ", purchasing_cost)
        print("ordering cost: ", ordering_cost)
        print("holding_cost: ", holding_cost)
        print("shortage_cost: ", shortage_cost)

        self.summary.inventory_cost.setText("{:,.2f}".format(total_cost))
        self.summary.service_level.setText("{:.2%}".format(service))
        self.graph.Plot(self.df, policy, periods)
        self.graph.draw()
Exemple #41
0
 def layoutWidgets(self):
     layout = QHBoxLayout()
     layout.addWidget(self.listWidget)
     layout.addLayout(self.buttonLayout)
     self.setLayout(layout)
Exemple #42
0
class Ui_editTeamDialog(object):
    def setupUi(self, editTeamDialog):

        editTeamDialog.setObjectName("editTeamDialog")
        editTeamDialog.setMinimumSize(QSize(500, 550))
        editTeamDialog.setMaximumSize(QSize(500, 550))

        self.mainVerticalLayout = QVBoxLayout(editTeamDialog)
        self.topLayout = QHBoxLayout()
        self.teamUserInfoLayout = QGridLayout()

        managerLabel = QLabel()
        self.teamUserInfoLayout.addWidget(managerLabel, 0, 0)

        teamLabel = QLabel()
        self.teamUserInfoLayout.addWidget(teamLabel, 1, 0)
        self.teamNameEdit = QLineEdit()
        self.teamNameEdit.setMinimumWidth(200)
        self.teamUserInfoLayout.addWidget(self.teamNameEdit, 1, 1)

        emailLabel = QLabel()
        self.teamUserInfoLayout.addWidget(emailLabel, 2, 0)
        self.emailEdit = QLineEdit()
        self.teamUserInfoLayout.addWidget(self.emailEdit, 2, 1)

        self.topLayout.addLayout(self.teamUserInfoLayout)
        self.topLayout.addStretch()

        self.mainVerticalLayout.addLayout(self.topLayout)
        self.mainVerticalLayout.addItem(QSpacerItem(0, 15))

        #self.mainVerticalLayout.addStretch()

        self.formationLayout = QHBoxLayout()

        self.formationRadioButtons = RadioButtonGroup("Formation",
                                                      Formation.formations)
        self.formationRadioButtons.setFlat(True)
        self.formationLayout.addWidget(self.formationRadioButtons)
        self.formationLayout.addStretch()

        self.mainVerticalLayout.addLayout(self.formationLayout)

        self.playersGroupBox = QGroupBox()

        self.gridLayout = QGridLayout(self.playersGroupBox)

        self.goalkeeperLabel = QLabel(self.playersGroupBox)
        self.gridLayout.addWidget(self.goalkeeperLabel, 0, 0)

        self.positionLabels = [QLabel(self.playersGroupBox) for i in range(11)]
        self.searchBoxes = [QLineEdit(self.playersGroupBox) for i in range(11)]
        self.selections = [QComboBox(self.playersGroupBox) for i in range(11)]
        self.clubLabels = [QLabel(self.playersGroupBox) for i in range(11)]
        self.valueLabels = [QLabel(self.playersGroupBox) for i in range(11)]

        for i, positionLabel in enumerate(self.positionLabels):
            self.gridLayout.addWidget(positionLabel, i, 0)

        for i, searchBox in enumerate(self.searchBoxes):
            searchBox.setToolTip("Search for a player by code or name")
            self.gridLayout.addWidget(searchBox, i, 1)
            searchBox.returnPressed.connect(partial(self.playerSearch, i))

        for i, selection in enumerate(self.selections):
            selection.setToolTip("Select a player")
            selection.setSizeAdjustPolicy(
                QComboBox.AdjustToContentsOnFirstShow)
            selection.setCurrentIndex(-1)
            self.gridLayout.addWidget(selection, i, 2)

        clubWidth = self.clubLabels[0].fontMetrics().width(
            "Wolverhampton Wanderers")
        for i, clubLabel in enumerate(self.clubLabels):
            clubLabel.setFixedWidth(clubWidth)
            self.gridLayout.addWidget(clubLabel, i, 3)

        valueWidth = self.valueLabels[0].fontMetrics().width("0.0")
        for i, valueLabel in enumerate(self.valueLabels):
            valueLabel.setFixedWidth(valueWidth)
            self.gridLayout.addWidget(valueLabel, i, 4)

        self.mainVerticalLayout.addWidget(self.playersGroupBox)
        self.mainVerticalLayout.addItem(QSpacerItem(0, 15))

        self.totalCostLayout = QHBoxLayout()
        self.totalCostLabel = QLabel()
        self.totalCostLayout.addWidget(self.totalCostLabel)

        self.mainVerticalLayout.addLayout(self.totalCostLayout)
        self.mainVerticalLayout.addItem(QSpacerItem(0, 15))

        self.buttonLayout = QHBoxLayout()

        okButton = QPushButton("OK")
        okButton.setAutoDefault(False)
        cancelButton = QPushButton("Cancel")
        cancelButton.setAutoDefault(False)
        self.buttonLayout.addWidget(okButton)
        self.buttonLayout.addWidget(cancelButton)
        buttonSpacer = QSpacerItem(0, 0, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.buttonLayout.addItem(buttonSpacer)
        self.mainVerticalLayout.addLayout(self.buttonLayout)

        okButton.clicked.connect(editTeamDialog.accept)
        cancelButton.clicked.connect(editTeamDialog.reject)

        managerLabel.setText("Manager")
        teamLabel.setText("Team Name")
        emailLabel.setText("Email")

        self.playersGroupBox.setTitle("Players")

        for formationRadioButton in self.formationRadioButtons:
            formationRadioButton.clicked.connect(
                partial(self.formationChanged,
                        str(formationRadioButton.text())))

        self.totalCostLabel.setText("Total Cost")
    def __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(
                QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)
Exemple #44
0
class MainWindow(QDialog):
    """monkey_linux UI"""
    def __init__(self,parent=None):
        super(MainWindow, self).__init__()
        self.init_conf()
        self.setParent(parent)
        common.Log.info("set up ui")
        self.setup_ui()
        self.findDeviceAction.triggered.connect(self.get_device_status)
        self.deleteDeviceAction.triggered.connect(self.del_device)
        # self.storeButton.clicked.connect(self.set_conf)
        self.startButton.clicked.connect(self.start)
        self.stopButton.clicked.connect(self.stop)
        self.checkLogButton.clicked.connect(self.check)
        self.monkeyButton.clicked.connect(self.checkMonkeyLog)
        self.exportButton.clicked.connect(self.exportConf)
        self.importButton.clicked.connect(self.importConf)
        self.setAbout.triggered.connect(self.about)
        self.startTime = datetime.datetime.now()
        self.secsTime = float(1) * 60 * 60



    def setup_ui(self):
        # main window width hand height
        # self.setMinimumWidth(600)
        self.setMaximumWidth(800)
        self.setMinimumHeight(600)
        # main window title
        self.setWindowTitle(static.title)
        # file menu bar
        self.menuBar = QMenuBar()
        self.menuBar.setMaximumHeight(23)
        # self.menuFile = self.menuBar.addMenu(static.menuFile)
        # self.importAction = QAction(QIcon(static.importPNG), static.importFile, self)
        # self.exportAction = QAction(QIcon(static.exportPNG), static.exportFile, self)
        # self.menuFile.addAction(self.importAction)
        # self.menuFile.addAction(self.exportAction)
        self.setEnvActioin = QAction(QIcon(static.setPNG), static.pcSet, self)
        self.menuSet = self.menuBar.addMenu(static.menuSet)
        self.menuSet.addAction(self.setEnvActioin)

        self.setAbout = QAction(QIcon(static.setPNG), static.menuAbout, self)
        self.setAbout.setStatusTip('About')  # 状态栏提示
        self.menuHelp = self.menuBar.addMenu(static.menuHelp)
        self.menuHelp.addAction(self.setAbout)



        # set all layout
        self.hbox = QHBoxLayout(self)

        # device ========
        self.topLeft = QFrame(self)
        self.topLeft.setMaximumSize(218, 300)
        self.topLeft.setMinimumSize(218, 200)
        self.topLeft.setFrameShape(QFrame.StyledPanel)
        self.topLeftLayout = QVBoxLayout(self.topLeft)
        self.toolBar = QToolBar()
        # self.androidDeviceAction = QRadioButton('Android', self)
        # self.androidDeviceAction.setFocusPolicy(Qt.NoFocus)
        # self.ipDeviceAction = QRadioButton('IP', self)
        # self.ipDeviceAction.setFocusPolicy(Qt.NoFocus)
        # self.ipDeviceAction.move(10, 10)
        # self.ipDeviceAction.toggle()
        self.findDeviceAction = QAction(QIcon(static.findDevice), static.findDeviceButton, self)
        self.deleteDeviceAction = QAction(QIcon(static.deleteDevice), static.deleteDeviceButton, self)
        # self.toolBar.addWidget(self.androidDeviceAction)
        # self.toolBar.addWidget(self.ipDeviceAction)
        self.toolBar.addAction(self.findDeviceAction)
        self.toolBar.addAction(self.deleteDeviceAction)
        self.deviceLab = QLabel(static.deviceName, self)
        self.device = QTableWidget(1, 2)
        self.device.setHorizontalHeaderLabels(['name', 'status'])
        self.device.setColumnWidth(0, 100)
        self.device.setColumnWidth(1, 80)
        self.topLeftLayout.addWidget(self.deviceLab)
        self.topLeftLayout.addWidget(self.toolBar)

        self.topLeftLayout.addWidget(self.device)


        # set button or other for running monkey or not and status of device and log ========
        self.topRight = QFrame(self)
        self.topRight.setFrameShape(QFrame.StyledPanel)
        self.topRight.setMaximumHeight(40)
        self.startButton = QPushButton(QIcon(static.startPNG), "")
        self.stopButton = QPushButton(QIcon(static.stopPNG), "")

        self.status = QLabel(static.status)
        self.statusEdit = QLineEdit(self)
        self.statusEdit.setReadOnly(True)
        self.statusEdit.setMaximumWidth(80)
        self.statusEdit.setMinimumWidth(80)
        self.statusEdit.setText("")
        # check log
        self.checkLogButton = QPushButton(static.checkLog)
        self.checkLogButton.setMaximumHeight(20)
        self.checkLogButton.setMinimumHeight(20)
        self.checkLogButton.setMaximumWidth(60)
        self.selectLog = QLabel(static.selectlog)
        self.logfile = QComboBox()
        self.dirlist = os.listdir(os.path.join(DIR, "Result"))
        for d in self.dirlist:
            if d != "AutoMonkey.log":
                self.logfile.insertItem(0, d)
        self.logfile.setMaximumWidth(150)
        self.logfile.setMaximumHeight(20)
        self.logfile.setMinimumHeight(20)
        self.topLayout = QHBoxLayout(self.topRight)
        self.topLayout.addWidget(self.startButton)
        self.topLayout.addWidget(self.stopButton)
        self.topLayout.addWidget(self.status)
        self.topLayout.addWidget(self.statusEdit)
        self.topLayout.addWidget(self.selectLog)
        self.topLayout.addWidget(self.logfile)
        self.topLayout.addWidget(self.checkLogButton)

        # set parameter for monkey =======
        self.midRight = QFrame(self)
        self.midRight.setMaximumSize(555, 200)
        self.midRight.setMinimumSize(555, 200)
        self.midRight.setFrameShape(QFrame.StyledPanel)
        self.midRightLayout = QVBoxLayout(self.midRight)
        self.subLayout0 = QVBoxLayout()
        self.subLayout1 = QVBoxLayout()
        self.subLayout2 = QHBoxLayout()
        self.subLayout3 = QVBoxLayout()
        self.subLayout4 = QVBoxLayout()
        self.subLayout5 = QHBoxLayout()
        self.subLayout6 = QHBoxLayout()
        self.toolBar = QToolBar()
        # self.storeAction = QAction(QIcon(static.storePNG), static.storeButton, self)
        self.startAction = QAction(QIcon(static.startPNG), static.startButton, self)
        self.stopAction = QAction(QIcon(static.stopPNG), static.stopButton, self)
        # self.toolBar.addAction(self.storeAction)
        self.toolBar.addAction(self.startAction)
        self.toolBar.addAction(self.stopAction)
        self.timeLongLbl = QLabel(static.timeString, self)
        self.timeLong = QLineEdit(self)
        self.timeLong.setMaximumWidth(100)
        self.timeLong.setMinimumWidth(100)
        self.timeLong.setPlaceholderText(static.timeLong)
        self.timeLongUnit = QLabel("H")
        self.etSetLbl = QLabel(static.eventTypeSet)
        self.etSet = QTableWidget(2, 2)
        self.etSet.setMaximumHeight(150)
        self.etSet.setHorizontalHeaderLabels(['option', 'value'])
        self.etSet.horizontalHeader().setStretchLastSection(True)
        self.etSet.setItem(0, 0, QTableWidgetItem("--throttle"))
        self.etSet.setItem(0, 1, QTableWidgetItem(str(static.eventType["--throttle"])))
        # set event type percent
        self.etPercentLbl = QLabel(static.eventTpyePercent, self)
        self.etPercent = QTableWidget(2, 2)
        self.etPercent.setMaximumHeight(150)
        self.etPercent.setHorizontalHeaderLabels(['option', 'value'])
        self.etPercent.horizontalHeader().setStretchLastSection(True)
        self.etPercent.setItem(0, 0, QTableWidgetItem("--pct-touch"))
        self.etPercent.setItem(0, 1, QTableWidgetItem(str(static.eventPercent["--pct-touch"])))
        self.etPercent.setItem(1, 0, QTableWidgetItem("--pct-motion"))
        self.etPercent.setItem(1, 1, QTableWidgetItem(str(static.eventPercent["--pct-motion"])))
        # self.storeButton = QPushButton(QIcon(static.storePNG), static.storeButton)
        # self.storeButton.setToolTip(static.storeButton)
        self.exportButton = QPushButton(QIcon(static.exportPNG), static.exportFile)
        self.exportButton.setToolTip(static.exportFile)
        self.importButton = QPushButton(QIcon(static.importPNG), static.importFile)
        self.importButton.setToolTip(static.importFile)
        self.subLayout2.addWidget(self.timeLongLbl)
        self.subLayout2.addWidget(self.timeLong)
        self.subLayout2.addWidget(self.timeLongUnit)
        self.subLayout2.addWidget(QLabel(" " * 300))
        # self.subLayout2.addWidget(self.storeButton)
        self.subLayout2.addWidget(self.exportButton)
        self.subLayout2.addWidget(self.importButton)

        self.subLayout0.addLayout(self.subLayout2)
        self.subLayout3.addWidget(self.etSetLbl)
        self.subLayout3.addWidget(self.etSet)
        self.subLayout4.addWidget(self.etPercentLbl)
        self.subLayout4.addWidget(self.etPercent)
        self.subLayout5.addLayout(self.subLayout0)
        self.subLayout6.addLayout(self.subLayout3)
        self.subLayout6.addLayout(self.subLayout4)
        self.midRightLayout.addLayout(self.subLayout5)
        self.midRightLayout.addLayout(self.subLayout6)

        # log ========
        self.bottom = QFrame(self)
        self.bottom.setFrameShape(QFrame.StyledPanel)
        # log information
        self.logInfo = QLabel(static.logInfo)
        # information filter
        self.logFilter = QLabel(static.logFilter)
        self.monkeyButton = QPushButton(static.openMonkeyLog)
        self.combo = QComboBox()
        for i in range(len(static.logLevel)):
            self.combo.addItem(static.logLevel[i])
        self.combo.setMaximumWidth(55)
        self.combo.setMaximumHeight(20)
        self.combo.setMinimumHeight(20)
        # information details
        self.bottomLayout = QVBoxLayout(self.bottom)
        self.subLayout = QHBoxLayout()
        self.subLayout.addWidget(self.logInfo)
        for i in range(10):
            self.subLayout.addWidget(QLabel(""))
        self.subLayout.addWidget(self.monkeyButton)
        self.subLayout.addWidget(self.logFilter)
        self.subLayout.addWidget(self.combo)
        self.bottomLayout.addLayout(self.subLayout)
        self.tabwidget = TabWidget()
        self.tabwidget.setMinimumHeight(100)
        self.bottomLayout.addWidget(self.tabwidget)

        # splitter mainWindow ++++++++++++++++++++++++++++++++++++
        self.splitter2 = QSplitter(Qt.Vertical)
        self.splitter2.addWidget(self.topRight)
        self.splitter2.addWidget(self.midRight)
        self.splitter0 = QSplitter(Qt.Horizontal)
        self.splitter0.addWidget(self.topLeft)
        self.splitter0.addWidget(self.splitter2)
        self.splitter1 = QSplitter(Qt.Vertical)
        self.splitter1.addWidget(self.menuBar)
        self.splitter1.addWidget(self.splitter0)
        self.splitter1.addWidget(self.bottom)
        self.hbox.addWidget(self.splitter1)
        self.setLayout(self.hbox)
        self.show()

    def about(self):
        common.showDialog(static.menuAbout, static.dialogAbout)

    def init_conf(self):
        common.Log.info("init monkey conf")
        with open(monkeyConfFile, "w") as f:
            f.write("deviceList = []" + "\n")
            f.write("times = " + static.times + "\n")
            f.write("--throttle = " + static.eventType["--throttle"] + "\n")
            f.write("--pct-touch = " + static.eventPercent["--pct-touch"] + "\n")
            f.write("--pct-motion = " + static.eventPercent["--pct-motion"] + "\n")

    def setup_env(self):
        pass

    def _set_eventType(self, confFile):
        try:
            option = self.etSet.item(0, 0).text()
            value = self.etSet.item(0, 1).text()
            if value > "0":
                with open(confFile, 'a+') as f:
                    f.write(option + " = " + value + "\n")
        except AttributeError, e:
            pass
    def __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)
Exemple #46
0
class Ui_editTeamDialog(object):
    def setupUi(self, editTeamDialog):
    
        editTeamDialog.setObjectName("editTeamDialog")
        editTeamDialog.setMinimumSize(QSize(500, 550))
        editTeamDialog.setMaximumSize(QSize(500, 550))
        
        self.mainVerticalLayout = QVBoxLayout(editTeamDialog)
        self.topLayout = QHBoxLayout()
        self.teamUserInfoLayout = QGridLayout()

        managerLabel = QLabel()
        self.teamUserInfoLayout.addWidget(managerLabel, 0, 0)

        teamLabel = QLabel()
        self.teamUserInfoLayout.addWidget(teamLabel, 1, 0)
        self.teamNameEdit = QLineEdit()
        self.teamNameEdit.setMinimumWidth(200)
        self.teamUserInfoLayout.addWidget(self.teamNameEdit, 1, 1)

        emailLabel = QLabel()
        self.teamUserInfoLayout.addWidget(emailLabel, 2, 0)
        self.emailEdit = QLineEdit()
        self.teamUserInfoLayout.addWidget(self.emailEdit, 2, 1)

        self.topLayout.addLayout(self.teamUserInfoLayout)
        self.topLayout.addStretch()

        self.mainVerticalLayout.addLayout(self.topLayout)
        self.mainVerticalLayout.addItem(QSpacerItem(0, 15))
        
        #self.mainVerticalLayout.addStretch()

        self.formationLayout = QHBoxLayout()

        self.formationRadioButtons = RadioButtonGroup("Formation", Formation.formations)
        self.formationRadioButtons.setFlat(True)
        self.formationLayout.addWidget(self.formationRadioButtons)
        self.formationLayout.addStretch()

        self.mainVerticalLayout.addLayout(self.formationLayout)
        
        self.playersGroupBox = QGroupBox()

        self.gridLayout = QGridLayout(self.playersGroupBox)

        self.goalkeeperLabel = QLabel(self.playersGroupBox)
        self.gridLayout.addWidget(self.goalkeeperLabel, 0, 0)

        self.positionLabels = [QLabel(self.playersGroupBox) for i in range(11)]
        self.searchBoxes = [QLineEdit(self.playersGroupBox) for i in range(11)]
        self.selections = [QComboBox(self.playersGroupBox) for i in range(11)]
        self.clubLabels = [QLabel(self.playersGroupBox) for i in range(11)]
        self.valueLabels = [QLabel(self.playersGroupBox) for i in range(11)]
        
        for i, positionLabel in enumerate(self.positionLabels):
            self.gridLayout.addWidget(positionLabel, i, 0)
        
        for i, searchBox in enumerate(self.searchBoxes):
            searchBox.setToolTip("Search for a player by code or name")
            self.gridLayout.addWidget(searchBox, i, 1)
            searchBox.returnPressed.connect(partial(self.playerSearch, i))
        
        for i, selection in enumerate(self.selections):
            selection.setToolTip("Select a player")
            selection.setSizeAdjustPolicy(QComboBox.AdjustToContentsOnFirstShow)
            selection.setCurrentIndex(-1)
            self.gridLayout.addWidget(selection, i, 2)
        
        clubWidth = self.clubLabels[0].fontMetrics().width("Wolverhampton Wanderers")
        for i, clubLabel in enumerate(self.clubLabels):
            clubLabel.setFixedWidth(clubWidth)
            self.gridLayout.addWidget(clubLabel, i, 3)
            
        valueWidth = self.valueLabels[0].fontMetrics().width("0.0")
        for i, valueLabel in enumerate(self.valueLabels):
            valueLabel.setFixedWidth(valueWidth)
            self.gridLayout.addWidget(valueLabel, i, 4)

        
        self.mainVerticalLayout.addWidget(self.playersGroupBox)
        self.mainVerticalLayout.addItem(QSpacerItem(0, 15))
        
        self.totalCostLayout = QHBoxLayout()
        self.totalCostLabel = QLabel()
        self.totalCostLayout.addWidget(self.totalCostLabel)

        self.mainVerticalLayout.addLayout(self.totalCostLayout)
        self.mainVerticalLayout.addItem(QSpacerItem(0, 15))
        
        self.buttonLayout = QHBoxLayout()
        
        okButton = QPushButton("OK")
        okButton.setAutoDefault(False)
        cancelButton = QPushButton("Cancel")
        cancelButton.setAutoDefault(False)
        self.buttonLayout.addWidget(okButton)
        self.buttonLayout.addWidget(cancelButton)
        buttonSpacer = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.buttonLayout.addItem(buttonSpacer)
        self.mainVerticalLayout.addLayout(self.buttonLayout)

        okButton.clicked.connect(editTeamDialog.accept)
        cancelButton.clicked.connect(editTeamDialog.reject)

        managerLabel.setText("Manager")
        teamLabel.setText("Team Name")
        emailLabel.setText("Email")

        self.playersGroupBox.setTitle("Players")

        for formationRadioButton in self.formationRadioButtons:
            formationRadioButton.clicked.connect(partial(self.formationChanged, str(formationRadioButton.text())))
        
        self.totalCostLabel.setText("Total Cost")
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()
Exemple #48
0
    def __init__(self, parent):
        super(EditSupplyOrderPanel, self).__init__(parent)

        self.current_supply_order_id = None

        self.proto = []
        self.proto.append(
            TextAreaPrototype('description',
                              _('Description'),
                              editable=True,
                              nullable=False))
        self.proto.append(
            FloatNumberPrototype('quantity',
                                 _('Quantity'),
                                 editable=True,
                                 nullable=False))
        self.proto.append(
            FloatNumberPrototype('unit_price',
                                 _('Unit price'),
                                 editable=True,
                                 nullable=True))

        self.delivery_date_prototype = FutureDatePrototype('description',
                                                           ('Description'),
                                                           editable=True,
                                                           nullable=False)

        self.model = SupplyOrderPartsModel(self, self.proto)

        self.controller_part = PrototypeController(
            self, self.proto, ProxyTableView(None, self.proto))

        self.controller_part.setModel(self.model)
        # self.controller_part.view.verticalHeader().hide()
        self.controller_part.view.horizontalHeader().setResizeMode(
            0, QHeaderView.Stretch)

        self.print_supply_order_action = QAction(_("Print supply order"),
                                                 self)  # , parent
        self.print_supply_order_action.triggered.connect(
            self.print_supply_order)
        self.print_supply_order_action.setShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_P))
        self.print_supply_order_action.setShortcutContext(
            Qt.WidgetWithChildrenShortcut)
        self.addAction(self.print_supply_order_action)

        self.save_supply_order_action = QAction(_("Save supply order"),
                                                self)  # , parent
        self.save_supply_order_action.triggered.connect(self.save)
        self.save_supply_order_action.setShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_S))
        self.save_supply_order_action.setShortcutContext(
            Qt.WidgetWithChildrenShortcut)
        self.addAction(self.save_supply_order_action)

        self.delete_supply_order_action = QAction(_("Deactivate supply order"),
                                                  self)  # , parent
        self.delete_supply_order_action.triggered.connect(self.delete)
        self.addAction(self.delete_supply_order_action)

        self.next_order_for_supplier_action = QAction(
            _("Next supplier's order"), self)  # , parent
        self.next_order_for_supplier_action.setShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_PageDown))
        self.next_order_for_supplier_action.setShortcutContext(
            Qt.WidgetWithChildrenShortcut)
        self.next_order_for_supplier_action.triggered.connect(
            self.next_order_for_supplier)
        self.addAction(self.next_order_for_supplier_action)

        self.previous_order_for_supplier_action = QAction(
            _("Previous supplier's order"), self)  # , parent
        self.previous_order_for_supplier_action.setShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_PageDown))
        self.previous_order_for_supplier_action.setShortcutContext(
            Qt.WidgetWithChildrenShortcut)
        self.previous_order_for_supplier_action.triggered.connect(
            self.next_order_for_supplier)
        self.addAction(self.previous_order_for_supplier_action)

        self.change_supplier_action = QAction(_("Change supplier"),
                                              self)  # , parent
        self.change_supplier_action.triggered.connect(self.change_supplier)
        self.addAction(self.change_supplier_action)

        # self.controller_operation.view.addAction(self.reprint_delivery_slip)
        self.controller_part.view.addAction(self.print_supply_order_action)
        self.controller_part.view.addAction(self.save_supply_order_action)
        self.controller_part.view.addAction(self.delete_supply_order_action)

        navigation = NavBar(self,
                            [(self.next_order_for_supplier_action.text(),
                              self.next_order_for_supplier),
                             (self.previous_order_for_supplier_action.text(),
                              self.previous_order_for_supplier),
                             (_("Action"), self.show_actions)])
        navigation.buttons[2].setObjectName("specialMenuButton")

        self.action_menu = QMenu(navigation.buttons[2])
        list_actions = [(self.print_supply_order_action, None),
                        (self.save_supply_order_action, None),
                        (self.delete_supply_order_action, None),
                        (self.change_supplier_action, None)]

        populate_menu(self.action_menu,
                      self,
                      list_actions,
                      context=Qt.WidgetWithChildrenShortcut)

        self.title_widget = TitleWidget(_("Supply order"), self, navigation)
        self.supplier_plate_widget = SupplierPlateWidget(self)
        self.edit_comment_widget = DescribedTextEdit(_("Comments"))
        self.edit_comment_widget.setMinimumHeight(20)
        self.edit_comment_widget.setMinimumWidth(600)
        self.edit_comment_widget.setMaximumHeight(60)
        self.edit_comment_widget.setSizePolicy(QSizePolicy.Preferred,
                                               QSizePolicy.Preferred)

        self.supplier_reference_widget = QLineEdit()

        self.delivery_date_widget = DateEntryWidget()
        self.delivery_date_widget.setMaximumWidth(100)

        self.creation_date_widget = QLabel()

        self.in_title_label = QLabel()

        top_layout1 = QHBoxLayout()
        top_layout1.addWidget(self.in_title_label)
        top_layout1.addStretch()
        top_layout1.addWidget(self.supplier_plate_widget)

        hlayout = QHBoxLayout()
        hlayout.addWidget(QLabel(_("Delivery date")))
        hlayout.addWidget(self.delivery_date_widget)
        hlayout.addStretch()

        hlayout3 = QHBoxLayout()
        hlayout3.addWidget(QLabel(_("Creation date")))
        hlayout3.addWidget(self.creation_date_widget)
        hlayout3.addStretch()

        hlayout2 = QHBoxLayout()
        hlayout2.addWidget(QLabel(_("Supplier's reference")))
        hlayout2.addWidget(self.supplier_reference_widget)
        hlayout2.addStretch()

        vlayout = QVBoxLayout()
        vlayout.addLayout(hlayout)  # delivery date
        vlayout.addLayout(hlayout3)  # creation date
        vlayout.addLayout(hlayout2)  # reference
        vlayout.addStretch()

        top_layout2 = QHBoxLayout()
        top_layout2.addLayout(vlayout)
        top_layout2.addWidget(self.edit_comment_widget)
        top_layout2.addStretch()
        top_layout2.setStretch(0, 0)
        top_layout2.setStretch(1, 0)
        # For some reason, the stretch added above is not enough
        # to push the whole layout to the left. I have to set
        # it's stretch factor too...
        top_layout2.setStretch(2, 100)

        vhead_layout = QVBoxLayout()
        vhead_layout.addWidget(self.title_widget)
        top_layout1.setContentsMargins(4, 0, 4, 0)
        # vhead_layout.addLayout(top_layout1)
        vhead_layout.addWidget(InlineSubFrame(top_layout1, None))

        vhead_layout.addLayout(top_layout2)
        # top_layout2.setContentsMargins(4,4,4,4)
        #vhead_layout.addWidget(InlineSubFrame(top_layout2,None))

        vhead_layout.addWidget(self.controller_part.view)
        vhead_layout.setStretch(0, 0)
        vhead_layout.setStretch(1, 0)
        vhead_layout.setStretch(2, 0)
        vhead_layout.setStretch(3, 10)

        self.setLayout(vhead_layout)

        self.controller_part.view.enable_edit_panel()

        # Handling changes in the model (helpful to know if saving
        # is necessary)

        self.model_data_changed = False
        self.model.rowsInserted.connect(self.data_changed_slot)
        self.model.rowsRemoved.connect(self.data_changed_slot)
        self.model.dataChanged.connect(self.data_changed_slot)
        self.supplier_reference_widget.textChanged.connect(
            self.data_changed2_slot)
        self.edit_comment_widget.textChanged.connect(self.data_changed2_slot)
        self.delivery_date_widget.textChanged.connect(self.data_changed2_slot)
Exemple #49
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().screen().rect().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)
        self.atoms = odict()
        titles = odict([
            ["preset", "Presets"],
            ["theory", "Theory code"],
            ["primordial", "Primordial perturbations"],
            ["geometry", "Geometry"],
            ["hubble", "Constaint on hubble parameter"],
            ["baryons", "Baryon sector"],
            ["dark_matter", "Dark matter"],
            ["dark_energy", "Lambda / Dark energy"],
            ["neutrinos", "Neutrinos and other extra matter"],
            ["bbn", "BBN"],
            ["reionization", "Reionization history"],
            ["cmb_lensing", "CMB lensing"],
            ["cmb", "CMB experiments"],
            ["sampler", "Samplers"]])
        for a in titles:
            self.atoms[a] = {
                "group": QGroupBox(titles[a]),
                "combo": QComboBox()}
            self.layout_options.addWidget(self.atoms[a]["group"])
            self.atoms[a]["layout"] = QVBoxLayout(self.atoms[a]["group"])
            self.atoms[a]["layout"].addWidget(self.atoms[a]["combo"])
            self.atoms[a]["combo"].addItems(
                [text(k,v) for k,v in getattr(input_database, a).items()])
        # Connect to refreshers -- needs to be after adding all elements
        for a in self.atoms:
            if a == "preset":
                self.atoms["preset"]["combo"].currentIndexChanged.connect(
                    self.refresh_preset)
                continue
            self.atoms[a]["combo"].currentIndexChanged.connect(self.refresh)
        # Add Planck-naming checkbox and connect to refresher too
        self.planck_names = QCheckBox("Keep common names")
        self.atoms["theory"]["layout"].addWidget(self.planck_names)
        self.planck_names.stateChanged.connect(self.refresh)
        # RIGHT: Output + buttons
        self.display_tabs = QTabWidget()
        self.display = {}
        for k in ["yaml", "python"]:
            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)
        # Select first preset, by default
#        print(self.atoms["preset"]["combo"].itemText(0))

    @Slot()
    def refresh(self):
        info = create_input(planck_names=self.planck_names.isChecked(), **{
            k:str(self.atoms[k]["combo"].currentText().split(_separator)[0])
            for k in self.atoms if k is not "preset"})
        self.refresh_display(info)

    @Slot()
    def refresh_preset(self):
        preset = self.atoms["preset"]["combo"].currentText().split(_separator)[0]
        info = create_input(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, "derived"]:
                continue
            self.atoms[k]["combo"].blockSignals(True)
            self.atoms[k]["combo"].setCurrentIndex(
                self.atoms[k]["combo"].findText(
                    text(v,getattr(input_database, k).get(v))))
            self.atoms[k]["combo"].blockSignals(False)

    def refresh_display(self, info):
        self.display["python"].setText(
            "from collections import OrderedDict\n\ninfo = " + pformat(info))
        self.display["yaml"].setText(yaml_dump(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)"}[ftype]
        fsuffix = {"yaml": ".yaml", "python": ".py"}[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())
    def init_UI(self):
        lay = QGridLayout()
        lay.addWidget(QLabel('<b>Position</b>'), 0, 0, 1, 4)

        posx = QDoubleSpinBox()
        posx.setValue(self.v.x)
        self.controls['posx'] = posx

        posy = QDoubleSpinBox()
        posy.setValue(self.v.y)
        self.controls['posy'] = posy

        posz = QDoubleSpinBox()
        posz.setValue(self.v.z)
        self.controls['posz'] = posz

        lay.addWidget(posx, 1, 0)
        lay.addWidget(posy, 1, 1)
        lay.addWidget(posz, 1, 2)

        lay.addWidget(QLabel('<b>Normal</b>'), 2, 0, 1, 4)

        norx = QDoubleSpinBox()
        norx.setValue(self.v.nx)
        self.controls['norx'] = norx

        nory = QDoubleSpinBox()
        nory.setValue(self.v.ny)
        self.controls['nory'] = nory

        norz = QDoubleSpinBox()
        norz.setValue(self.v.nz)
        self.controls['norz'] = norz

        lay.addWidget(norx, 3, 0)
        lay.addWidget(nory, 3, 1)
        lay.addWidget(norz, 3, 2)

        lay.addWidget(QLabel('<b>Texture Coordinates</b>'), 4, 0, 1, 4)

        u = QDoubleSpinBox()
        u.setValue(self.v.u)
        self.controls['u'] = u

        v = QDoubleSpinBox()
        v.setValue(self.v.v)
        self.controls['v'] = v

        lay.addWidget(u, 5, 0)
        lay.addWidget(v, 5, 1)

        lay.addWidget(QLabel('<b>Color</b>'), 6, 0, 1, 4)

        red = QSpinBox()
        red.setMinimum(0)
        red.setMaximum(255)
        red.setValue(self.v.color.red)
        self.controls['red'] = red

        green = QSpinBox()
        green.setMinimum(0)
        green.setMaximum(255)
        green.setValue(self.v.color.green)
        self.controls['green'] = green

        blue = QSpinBox()
        blue.setMinimum(0)
        blue.setMaximum(255)
        blue.setValue(self.v.color.blue)
        self.controls['blue'] = blue

        alpha = QSpinBox()
        alpha.setMinimum(0)
        alpha.setMaximum(255)
        alpha.setValue(self.v.color.alpha)
        self.controls['alpha'] = alpha

        lay.addWidget(red, 7, 0)
        lay.addWidget(green, 7, 1)
        lay.addWidget(blue, 7, 2)
        lay.addWidget(alpha, 7, 3)

        grp = QGroupBox('Vertex')
        grp.setLayout(lay)

        btns = QVBoxLayout()
        save = QPushButton('Save')
        save.clicked.connect(self.save)

        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)

        btns.addStretch()
        btns.addWidget(save)
        btns.addWidget(cancel)

        mainlay = QHBoxLayout()
        mainlay.addWidget(grp)
        mainlay.addLayout(btns)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 300, 250)
        self.setWindowTitle('MSH Suite - Vertex Editor')
        self.show()
 def __init__(self, parent=None):
   super(SummaryTab, self).__init__(parent)
   #create the widgets
   self.label_info = QLabel("No summary data to display")
   label_sent_packets = QLabel("Sent Packet Count")
   self.label_sent_packets = StyledLabel()
   self.label_sent_packets.setMaximumHeight(30)
   label_received_packets = QLabel("Received Packet Count")
   self.label_received_packets = StyledLabel()
   self.label_received_packets.setMaximumHeight(30)
   label_packets_lost = QLabel("Packets Lost")
   self.label_packets_lost = StyledLabel()
   self.label_packets_lost.setMaximumHeight(30)
   label_loss_percentage = QLabel("Packet Loss Percentage")
   self.label_loss_percentage = StyledLabel()
   self.label_loss_percentage.setMaximumHeight(30)
   label_output_delay = QLabel("Average Output Delay")
   self.label_output_delay = StyledLabel()
   self.label_output_delay.setMaximumHeight(30)
   #setup summary_layout
   #first, setup a stacked summary_layout to indicate first there's no summary data
   self.layout_stack = QStackedLayout()
   summary_centerer_layout = QHBoxLayout()
   summary_layout = QGridLayout() #if I use formlayout, i'm afraid things will stretch out too much horizontally
   row = 1; col = 0;
   summary_layout.addWidget(label_sent_packets, row, col)
   col += 2
   summary_layout.addWidget(self.label_sent_packets, row, col) #leave a middle column empty
   row += 1; col -= 2;
   summary_layout.addWidget(label_received_packets, row, col)
   col += 2
   summary_layout.addWidget(self.label_received_packets, row, col)
   row += 1; col -= 2
   summary_layout.addWidget(label_packets_lost, row, col)
   col += 2
   summary_layout.addWidget(self.label_packets_lost, row, col)
   row += 1; col -= 2;
   summary_layout.addWidget(label_loss_percentage, row, col)
   col += 2
   summary_layout.addWidget(self.label_loss_percentage, row, col)
   row += 1; col -= 2;
   summary_layout.addWidget(label_output_delay, row, col)
   col += 2
   summary_layout.addWidget(self.label_output_delay, row, col)
   #center things out
   summary_layout.setColumnMinimumWidth(1, 100) # 100 pixels in the middle
   summary_layout.setRowMinimumHeight(0, 10) #100 pixels from top
   summary_centerer_layout.addStretch()
   summary_centerer_layout.addLayout(summary_layout)
   summary_centerer_layout.addStretch()
   #make a dump widget for the stacked summary_layout
   widget = QWidget()
   widget.setLayout(summary_centerer_layout)
   self.layout_stack.insertWidget(0, widget)
   #setup summary_layout for info label!
   layout_info_label = QVBoxLayout()
   layout_info_label.addStretch()
   layout_info_label.addWidget(self.label_info)
   layout_info_label.addStretch()
   #make dump widget for info label summary_layout!!
   widget_info_label = QWidget()
   widget_info_label.setLayout(layout_info_label)
   self.layout_stack.insertWidget(1, widget_info_label)
   self.setLayout(self.layout_stack)
   self.zeroOut()
Exemple #52
0
                def __init__(self):
                    super().__init__()
                    if separate_colorbars:
                        if rescale_colorbars:
                            self.vmins = tuple(np.min(u[0]) for u in U)
                            self.vmaxs = tuple(np.max(u[0]) for u in U)
                        else:
                            self.vmins = tuple(np.min(u) for u in U)
                            self.vmaxs = tuple(np.max(u) for u in U)
                    else:
                        if rescale_colorbars:
                            self.vmins = (min(np.min(u[0])
                                              for u in U), ) * len(U)
                            self.vmaxs = (max(np.max(u[0])
                                              for u in U), ) * len(U)
                        else:
                            self.vmins = (min(np.min(u) for u in U), ) * len(U)
                            self.vmaxs = (max(np.max(u) for u in U), ) * len(U)

                    layout = QHBoxLayout()
                    plot_layout = QGridLayout()
                    self.colorbarwidgets = [
                        cbar_widget(self, vmin=vmin, vmax=vmax)
                        if cbar_widget else None
                        for vmin, vmax in zip(self.vmins, self.vmaxs)
                    ]
                    plots = [
                        widget(self,
                               grid,
                               vmin=vmin,
                               vmax=vmax,
                               bounding_box=bounding_box,
                               codim=codim)
                        for vmin, vmax in zip(self.vmins, self.vmaxs)
                    ]
                    if legend:
                        for i, plot, colorbar, l in zip(
                                range(len(plots)), plots, self.colorbarwidgets,
                                legend):
                            subplot_layout = QVBoxLayout()
                            caption = QLabel(l)
                            caption.setAlignment(Qt.AlignHCenter)
                            subplot_layout.addWidget(caption)
                            if not separate_colorbars or backend == 'matplotlib':
                                subplot_layout.addWidget(plot)
                            else:
                                hlayout = QHBoxLayout()
                                hlayout.addWidget(plot)
                                if colorbar:
                                    hlayout.addWidget(colorbar)
                                subplot_layout.addLayout(hlayout)
                            plot_layout.addLayout(subplot_layout,
                                                  int(i / columns),
                                                  (i % columns), 1, 1)
                    else:
                        for i, plot, colorbar in zip(range(len(plots)), plots,
                                                     self.colorbarwidgets):
                            if not separate_colorbars or backend == 'matplotlib':
                                plot_layout.addWidget(plot, int(i / columns),
                                                      (i % columns), 1, 1)
                            else:
                                hlayout = QHBoxLayout()
                                hlayout.addWidget(plot)
                                if colorbar:
                                    hlayout.addWidget(colorbar)
                                plot_layout.addLayout(hlayout,
                                                      int(i / columns),
                                                      (i % columns), 1, 1)
                    layout.addLayout(plot_layout)
                    if not separate_colorbars:
                        layout.addWidget(self.colorbarwidgets[0])
                        for w in self.colorbarwidgets[1:]:
                            w.setVisible(False)
                    self.setLayout(layout)
                    self.plots = plots
Exemple #53
0
class RadioApp(QWidget):
    def __init__(self):
        super().__init__()
        self.edit = False

        self.left_dock_create()
        self.middle_dock_create()
        self.right_dock_create()
        self.slotans_create()

        self.box = QHBoxLayout()
        self.box.addLayout(self.volbalayout)
        self.box.addLayout(self.middlelayout)
        self.box.addLayout(self.rightlayout)

        self.mainlayout = QVBoxLayout()
        self.mainlayout.addLayout(self.box)
        self.setLayout(self.mainlayout)

    def left_dock_create(self):
        self.statlabel = QLabel("RSSI: --")
        self.logolabel = QLabel()
        self.logolabel.setPixmap(
            QPixmap(os.path.join(script_path, "../assets/logo.png")))
        self.statlabel.setFont(QFont("DejaVu Sans", 12))

        self.btnvolba = []
        for i in range(1, 5):
            self.btnvolba.append(QPushButton("Voľba {}".format(i)))

        self.presetaddbtn = QPushButton()
        self.presetaddbtn.setIcon(QIcon(QPixmap("../assets/add.png")))

        self.volbalayout = QVBoxLayout()
        self.volbalayout.addWidget(self.logolabel)
        self.volbalayout.addWidget(self.statlabel)
        for btn in self.btnvolba:
            self.volbalayout.addWidget(btn)
        self.volbalayout.addWidget(self.presetaddbtn)

    def middle_dock_create(self):
        self.frekv = QLabel()
        self.frekv.setFont(QFont("DejaVu Sans", 26))
        self.write_frekv()

        self.btnstepleft = QPushButton("<")
        self.btnseekdown = QPushButton("<<")
        self.btnseekup = QPushButton(">>")
        self.btnstepright = QPushButton(">")

        self.laybtnmv = QHBoxLayout()
        self.laybtnmv.addWidget(self.btnseekdown)
        self.laybtnmv.addWidget(self.btnstepleft)
        self.laybtnmv.addWidget(self.btnstepright)
        self.laybtnmv.addWidget(self.btnseekup)

        self.labelrdsdt = QLabel("RDS")
        self.labelrdsdt.setFont(QFont("DejaVu Sans", 12))

        self.frekvlayout = QHBoxLayout()
        self.frekvlayout.addWidget(self.frekv)
        self.frekvlayout.setAlignment(Qt.AlignCenter)

        self.middlelayout = QVBoxLayout()
        self.middlelayout.addLayout(self.frekvlayout)
        self.middlelayout.addLayout(self.laybtnmv)
        self.middlelayout.addWidget(self.labelrdsdt)

    def right_dock_create(self):
        self.btnonoff = QPushButton("Reset")
        self.slidvol = QSlider(Qt.Vertical)
        self.slidvol.setMinimum(0)
        self.slidvol.setMaximum(100)
        self.slidvol.setValue(50)
        self.labspeaker = QLabel()
        self.labspeaker.setPixmap(
            QPixmap(os.path.join(script_path, "../assets/speaker.png")))
        self.sndvolumelabel = QLabel()

        self.rightlayout = QVBoxLayout()
        self.rightlayout.addWidget(self.btnonoff)
        self.rightlayout.addWidget(self.slidvol)
        self.rightlayout.addWidget(self.sndvolumelabel)
        self.rightlayout.addWidget(self.labspeaker)

    def slotans_create(self):
        self.slidvol.valueChanged.connect(self.set_radiovolume)
        self.btnstepleft.clicked.connect(lambda: self.step_frekv("d"))
        self.btnstepright.clicked.connect(lambda: self.step_frekv("u"))
        self.btnseekdown.clicked.connect(lambda: self.set_seek("d"))
        self.btnseekup.clicked.connect(lambda: self.set_seek("u"))

        self.presetaddbtn.clicked.connect(self.preset_editmode)
        self.btnonoff.clicked.connect(self.reset_radio)
        for btn in self.btnvolba:
            btn.clicked.connect(self.preset_choose)
        self.timerrssi = QTimer()
        self.timerrssi.timeout.connect(self.write_stats)
        self.timerrssi.start(3000)  # ms

    def reset_radio(self):
        dev_radio.shutdown()
        dev_radio.poweron()

    def preset_editmode(self):
        if self.edit == True:
            # Chceme sa vrátiť do normálneho režimu -> zvrátime editačný
            for btn in self.btnvolba:
                btn.setStyleSheet("")
                btn.clicked.disconnect()
                btn.clicked.connect(self.preset_choose)
        else:
            # Vstupujeme do editačného režimu
            for btn in self.btnvolba:
                btn.setStyleSheet("background-color: #30f030;")
                btn.clicked.disconnect()
                btn.clicked.connect(self.preset_set)
        self.edit = not self.edit

    def preset_set(self):
        button = self.sender()
        if isinstance(button, QPushButton):
            button.setText("{:.2f}".format(dev_radio.getfrequency() / 100))
            self.preset_editmode()

    def preset_choose(self):
        button = self.sender()
        if isinstance(button, QPushButton):
            try:
                frekv = int(float(button.text()) * 100)
            except ValueError:
                return
            dev_radio.setfrequency(frekv)
            self.write_frekv()

    def preset_save(self):
        with open("preset.txt", mode="w") as fw:
            for btn in self.btnvolba:
                try:
                    fw.write("{},".format(int(float(btn.text()) * 100)))
                except ValueError:
                    fw.write(" ,")

    def preset_restore(self):
        try:
            fr = open("preset.txt", mode="r")
            pres_list = fr.read().split(",")
        except FileNotFoundError:
            return

        fr.close()
        if len(pres_list) - 1 < len(self.btnvolba):
            print("Chyba: Zoznam predvolieb je krátky")
            return

        for i, btn in enumerate(self.btnvolba):
            try:
                btn.setText("{:.2f}".format(int(pres_list[i]) / 100))
            except ValueError:
                continue

    def set_seek(self, direction):
        if direction == "u":
            dev_radio.seekup()
        elif direction == "d":
            dev_radio.seekdown()
        self.write_frekv()

    def step_frekv(self, direction):
        curr_frekv = dev_radio.getfrequency()
        if direction == "u":
            curr_frekv += 10
            if curr_frekv > dev_radio.freqhigh:
                curr_frekv = dev_radio.freqlow
        elif direction == "d":
            curr_frekv -= 10
            if curr_frekv < dev_radio.freqlow:
                curr_frekv = dev_radio.freqhigh
        dev_radio.setfrequency(curr_frekv)
        self.write_frekv()

    def write_frekv(self):
        self.frekv.setText("<b>{:.2f} MHz</b>".format(
            dev_radio.getfrequency() / 100))

    def write_stats(self):
        self.statlabel.setText("<b>RSSI: {}</b>".format(dev_radio.getrssi()))

    def set_radiovolume(self):
        vol_percent = self.slidvol.value()
        self.sndvolumelabel.setText("{}%".format(vol_percent))
        new_volume = int(map_range(vol_percent, 0, 100, 0, 15))
        dev_radio.setvolume(new_volume)

    def rds_psshow(self, station):
        print("Stanica: {}".format(station))

    def rds_txtshow(self, text):
        print("Text: {}".format(text))

    def rds_tmshow(self, hodiny, minuty):
        print("{}:{}".format(hodiny, minuty))
Exemple #54
0
    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)
Exemple #55
-1
    def __init__(self, text, validator, minValue, maxValue ):
    
        QWidget.__init__( self )
        layout = QHBoxLayout( self )
        
        checkBox = QCheckBox()
        checkBox.setFixedWidth( 115 )
        checkBox.setText( text )
        
        layout.addWidget( checkBox )
        
        hLayoutX = QHBoxLayout()
        lineEditXMin = QLineEdit()
        lineEditXMax = QLineEdit()
        hLayoutX.addWidget( lineEditXMin )
        hLayoutX.addWidget( lineEditXMax )
        lineEditXMin.setValidator( validator )
        lineEditXMax.setValidator( validator )
        lineEditXMin.setText( str( minValue ) )
        lineEditXMax.setText( str( maxValue ) )
        
        layout.addLayout( hLayoutX )
        
        self.checkBox      = checkBox
        self.lineEditX_min = lineEditXMin
        self.lineEditX_max = lineEditXMax
        self.lineEdits = [ lineEditXMin, lineEditXMax ]

        QtCore.QObject.connect( checkBox, QtCore.SIGNAL( "clicked()" ), self.updateEnabled )
        self.updateEnabled()