def __init__(self, parent = None):
		QDockWidget.__init__(self, "File System Tree View", parent)
		self.setObjectName("FileNavigatorDock")

		self.fsm = QFileSystemModel(self)
		tv = QTreeView(self)
		tv.showColumn(1)
		self.fsm.setRootPath(self.parent().workdir)
		tv.setModel(self.fsm)

		self.setAllowedAreas( self.left | self.right )
		self.setGeometry(0,0,400,1000)

		pb = QPushButton("...",self)
		pb.clicked.connect(self.changeWorkdir)
		self.le = QLineEdit(self)
		self.le.setText(self.parent().workdir)

		dockbox = QWidget(self)
		hl = QHBoxLayout(dockbox)
		hl.addWidget(self.le)
		hl.addWidget(pb)
		hll=QWidget(self)
		hll.setLayout(hl)
		vl = QVBoxLayout(dockbox)
		dockbox.setLayout(vl)
		vl.addWidget(hll)
		vl.addWidget(tv)
		self.setWidget(dockbox)

		self.adjustSize()

		self.parent().say("Vista del sistema de ficheros creada")
Exemple #2
0
    def __init__(self, parent, *args, **kwargs):
        super(FWidget, self).__init__(parent=parent, *args, **kwargs)

        self.parent = parent
        vbox = QVBoxLayout()
        editbox = QGridLayout()

        self.search_field = LineEdit()
        # self.search_field.textChanged.connect(self.search)
        self.search_field.setToolTip(u"Taper le nom ou le numéro de "
                                     u"téléphone à chercher")
        editbox.addWidget(self.search_field, 0, 0)

        search_but = Button("")
        search_but.setIcon(QIcon.fromTheme('search', QIcon('')))
        search_but.clicked.connect(self.search)
        editbox.addWidget(search_but, 0, 1)
        # self.empty = FLabel(u"")
        # editbox.addWidget(self.empty, 1, 0)

        addgroup_but = Button(u"Nouveau groupe")
        addgroup_but.setIcon(QIcon.fromTheme('document-new', QIcon('')))
        addgroup_but.clicked.connect(self.addgroup)

        self.contact_grp = Button(u"Envoyer à groupe")
        self.contact_grp.setIcon(QIcon.fromTheme('document-new', QIcon('')))
        self.contact_grp.clicked.connect(self.contact_group)
        self.contact_grp.setEnabled(False)

        editbox.addWidget(addgroup_but, 2, 0)
        editbox.addWidget(self.contact_grp, 1, 0)

        vbox.addLayout(editbox)
        self.setLayout(vbox)
Exemple #3
0
    def open_gui(self):
        self.main = MainWindow(self)
        self.main.setFixedSize(730, 430)
        self.main.setWindowIcon(QIcon(os.path.join(ProgramPath.program_path(), "demo-icon.png")))
        
        self.tabs = QTabWidget()
        
        widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        widget.setLayout(layout)

        self.main.setCentralWidget(widget)
        
        self.projects.append(ProjectEnvDisplay(self.tabs, self))
        self.projects.append(ProjectStatistics(self.tabs, self))
        self.projects.append(ProjectXively(self.tabs, self))

        self.tabs.addTab(self.projects[0], "Display Environment Measurements")
        self.tabs.addTab(self.projects[1], "Show Statistics with Button Control")
        self.tabs.addTab(self.projects[2], "Connect to Xively")

        self.active_project = self.projects[0]

        self.tabs.currentChanged.connect(self.tabChangedSlot)

        self.main.setWindowTitle("Starter Kit: Weather Station Demo " + config.DEMO_VERSION)
        self.main.show()
Exemple #4
0
    def __init__(self, table_p, obj, parent, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

        self.setWindowTitle("Confirmation de le suppression")
        self.title = FPageTitle("Voulez vous vraiment le supprimer?")
        self.obj = obj
        self.table_p = table_p
        self.parent = parent
        # self.title.setAlignment(Qt.AlignHCenter)
        title_hbox = QHBoxLayout()
        title_hbox.addWidget(self.title)
        report_hbox = QGridLayout()

        report_hbox.addWidget(FLabel(obj.display_name()), 0, 0)
        # delete and cancel hbox
        Button_hbox = QHBoxLayout()

        # Delete Button widget.
        delete_but = Button("Supprimer")
        Button_hbox.addWidget(delete_but)
        delete_but.clicked.connect(self.delete)
        # Cancel Button widget.
        cancel_but = Button("Annuler")
        Button_hbox.addWidget(cancel_but)
        cancel_but.clicked.connect(self.cancel)

        # Create the QVBoxLayout contenaire.
        vbox = QVBoxLayout()
        vbox.addLayout(title_hbox)
        vbox.addLayout(report_hbox)
        vbox.addLayout(Button_hbox)
        self.setLayout(vbox)
    def __init__(self):
        super(ShortcutSection, self).__init__()
        container = QVBoxLayout(self)
        self.tree = QTreeWidget()
        self.tree.setHeaderLabels([self.tr("Keys"), self.tr("Description")])
        self.tree.header().setStretchLastSection(True)
        self.tree.setColumnWidth(0, 200)
        container.addWidget(self.tree)

        self.items = {
            "new": "Create a new editor to work in a file",
            "new-project": "Create a new project",
            "open": "Open one or more files",
            "open-project": "Opens an existing project Edis",
            "reload": "Reload file",
            "save": "Save file"
            }

        for i, e in list(self.items.items()):
            item = QTreeWidgetItem(self.tree,
                                   [keymap.get_keymap(i).toString(), e])
            item.setFlags(Qt.ItemIsEditable | Qt.ItemIsEnabled)

        self.tree.itemDoubleClicked.connect(self._change_shortcut)
        # Install
        EnvironmentConfiguration.install_widget(self.tr("Shortcuts"), self)
    def __init__(self, parent=None, **kwargs):
        QWidget.__init__(self, parent, **kwargs)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.setLayout(layout)

        self.setSizePolicy(QSizePolicy.Fixed,
                           QSizePolicy.Expanding)
        self.__tabs = []

        self.__currentIndex = -1
        self.__changeOnHover = False

        self.__iconSize = QSize(26, 26)

        self.__group = QButtonGroup(self, exclusive=True)
        self.__group.buttonPressed[QAbstractButton].connect(
            self.__onButtonPressed
        )
        self.setMouseTracking(True)

        self.__sloppyButton = None
        self.__sloppyRegion = QRegion()
        self.__sloppyTimer = QTimer(self, singleShot=True)
        self.__sloppyTimer.timeout.connect(self.__onSloppyTimeout)
class NewChartPage1(QWizardPage):
    """WizardPage to adjust chart properties"""
    def __init__(self, parent, sensorgroup):
        QWizardPage.__init__(self, parent)
        self.setTitle(QCoreApplication.translate('DataStorageBrowser', 'Adjust chart properties'))
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)
        self.propertyWidget = None
        self.sensorgroup = sensorgroup


    def initializePage(self):
        i, x = self.field('templateNumber').toInt()
        tmpl = chartTemplates[i]
        tmpl.setSensorgroup(self.sensorgroup)
        if self.propertyWidget is not None:
            self.mainLayout.removeWidget(self.propertyWidget)
            self.propertyWidget.hide()
            del self.propertyWidget
        self.propertyWidget = SimTools.RichTypes.Qt4Widgets.RichTypesWidget(self)
        self.mainLayout.addWidget(self.propertyWidget)
        self.propertyWidget.addRichTypes(tmpl.properties)
        self.adjustSize()

    def validatePage(self):
        self.propertyWidget.applyChanges()
        return True
    def __init__(self, project, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.project = project
        self.setWindowTitle(translations.TR_PROJECT_PROPERTIES)
        self.resize(600, 500)
        vbox = QVBoxLayout(self)
        self.tab_widget = QTabWidget()
        self.projectData = ProjectData(self)
        self.projectExecution = ProjectExecution(self)
        self.projectMetadata = ProjectMetadata(self)
        self.tab_widget.addTab(self.projectData, translations.TR_PROJECT_DATA)
        self.tab_widget.addTab(self.projectExecution,
            translations.TR_PROJECT_EXECUTION)
        self.tab_widget.addTab(self.projectMetadata,
            translations.TR_PROJECT_METADATA)

        vbox.addWidget(self.tab_widget)
        self.btnSave = QPushButton(translations.TR_SAVE)
        self.btnCancel = QPushButton(translations.TR_CANCEL)
        hbox = QHBoxLayout()
        hbox.addWidget(self.btnCancel)
        hbox.addWidget(self.btnSave)

        vbox.addLayout(hbox)

        self.connect(self.btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btnSave, SIGNAL("clicked()"), self.save_properties)
Exemple #9
0
    def __init__(self, parent, titre, contenu, fonction_modif):
        QDialog.__init__(self, parent)
        self.setWindowTitle(titre)
        sizer = QVBoxLayout()
        self.parent = parent
        self.fonction_modif = fonction_modif
        self.texte = PythonSTC(self)
#        self.texte.setMinimumSize(300, 10)
        self.texte.setText(contenu)
##        self.texte.SetInsertionPointEnd()
        sizer.addWidget(self.texte)

        boutons = QHBoxLayout()
        self.btn_modif = QPushButton(u"Modifier - F5")
        boutons.addWidget(self.btn_modif)
        self.btn_esc = QPushButton(u"Annuler - ESC")
        boutons.addStretch()
        boutons.addWidget(self.btn_esc)
        sizer.addLayout(boutons)
        self.setLayout(sizer)

        self.btn_modif.clicked.connect(self.executer)
        self.btn_esc.clicked.connect(self.close)

        self.setMinimumSize(400, 500)
        self.texte.setFocus()
Exemple #10
0
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletAnalogOutV2, *args)
        
        self.ao = self.device
        
        self.input_voltage_label = VoltageLabel()
        
        self.output_voltage_label = QLabel('Output Voltage [mV]: ')
        self.output_voltage_box = QSpinBox()
        self.output_voltage_box.setMinimum(0)
        self.output_voltage_box.setMaximum(12000)
        self.output_voltage_box.setSingleStep(1)
        
        layout_h1 = QHBoxLayout()
        layout_h1.addStretch()
        layout_h1.addWidget(self.output_voltage_label)
        layout_h1.addWidget(self.output_voltage_box)
        layout_h1.addStretch()
        
        layout_h2 = QHBoxLayout()
        layout_h2.addStretch()
        layout_h2.addWidget(self.input_voltage_label)
        layout_h2.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h2)
        layout.addLayout(layout_h1)
        layout.addStretch()
        
        self.output_voltage_box.editingFinished.connect(self.voltage_finished)
        
        self.cbe_input_voltage = CallbackEmulator(self.ao.get_input_voltage,
                                                  self.cb_get_input_voltage,
                                                  self.increase_error_count)
Exemple #11
0
    def __init__(self, ipcon, uid, version):
        PluginBase.__init__(self, ipcon, uid, 'Linear Poti Bricklet', version)
        
        self.lp = BrickletLinearPoti(uid, ipcon)
        
        self.qtcb_position.connect(self.cb_position)
        self.lp.register_callback(self.lp.CALLBACK_POSITION,
                                  self.qtcb_position.emit) 
        
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, 100)
        
        self.position_label = PositionLabel('Position: ')
        
        self.current_value = None

        plot_list = [['', Qt.red, self.get_current_value]]
        self.plot_widget = PlotWidget('Position', plot_list)
        
        layout_h = QHBoxLayout()
        layout_h.addStretch()
        layout_h.addWidget(self.position_label)
        layout_h.addWidget(self.slider)
        layout_h.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h)
        layout.addWidget(self.plot_widget)
Exemple #12
0
    def __init__(self, model, parent=None):
        super().__init__(parent)

        self._view = QTableView()
        self._view.setModel(model)

        cancelButton = QPushButton(_("cancel"))
        cancelButton.clicked.connect(self.reject)

        okButton = QPushButton(_("OK"))
        okButton.setDefault(True)
        okButton.clicked.connect(self.accept)

        addButton = QPushButton("+")
        addButton.clicked.connect(self.add)

        buttonBox = QHBoxLayout()
        buttonBox.addWidget(addButton)
        buttonBox.addStretch(1)
        buttonBox.addWidget(cancelButton)
        buttonBox.addWidget(okButton)

        layout = QVBoxLayout()
        layout.addWidget(self._view)
        layout.addLayout(buttonBox)

        self.setLayout(layout)

        self.accepted.connect(self.save)

        self.setWindowTitle(_("Admin.edit" + model.table))
        self.resize(600, 300)
        self._view.resizeColumnsToContents()
Exemple #13
0
    def __init__(self, parent=None):
        super().__init__(parent)

        layout = QVBoxLayout()

        textBox = QHBoxLayout()
        textBox.addStretch(1)
        textBox.addWidget(QLabel(_("DeleteConfirmation.text")))
        textBox.addStretch(1)
        layout.addLayout(textBox)

        cancelButton = QPushButton(_("cancel"))
        cancelButton.clicked.connect(self.reject)

        okButton = QPushButton(_("OK"))
        okButton.clicked.connect(self.accept)

        buttonBox = QHBoxLayout()
        buttonBox.addStretch(1)
        buttonBox.addWidget(cancelButton)
        buttonBox.addWidget(okButton)
        layout.addLayout(buttonBox)

        self.setLayout(layout)
        self.setWindowTitle(_("DeleteConfirmation.title"))
    def __init__(self, item, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self._item = item
        self.setWindowTitle(self.tr("Project Properties"))
        vbox = QVBoxLayout(self)
        self.tab_widget = QTabWidget()
        self.projectData = ProjectData(self)
        self.projectExecution = ProjectExecution(self)
        self.projectMetadata = ProjectMetadata(self)
        self.tab_widget.addTab(self.projectData, self.tr("Project Data"))
        self.tab_widget.addTab(self.projectExecution,
            self.tr("Project Execution"))
        self.tab_widget.addTab(self.projectMetadata,
            self.tr("Project Metadata"))

        vbox.addWidget(self.tab_widget)
        self.btnSave = QPushButton(self.tr("Save"))
        self.btnCancel = QPushButton(self.tr("Cancel"))
        hbox = QHBoxLayout()
        hbox.addWidget(self.btnCancel)
        hbox.addWidget(self.btnSave)

        vbox.addLayout(hbox)

        self.connect(self.btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btnSave, SIGNAL("clicked()"), self.save_properties)
class SpinBoxImageView(QHBoxLayout):
    valueChanged = pyqtSignal(int)
    def __init__(self, parentView, backgroundColor, foregroundColor,
                 value, height, fontSize):
        QHBoxLayout.__init__(self)
        self.backgroundColor = backgroundColor
        self.foregroundColor = foregroundColor

        self.labelLayout = QVBoxLayout()
        self.upLabel = LabelButtons('spin-up', parentView,
                                    backgroundColor, foregroundColor,
                                    height/2, height/2)
        self.labelLayout.addWidget(self.upLabel)
        self.upLabel.clicked.connect(self.on_upLabel)

        self.downLabel = LabelButtons('spin-down', parentView,
                                      backgroundColor,
                                      foregroundColor, height/2,
                                      height/2)
        self.labelLayout.addWidget(self.downLabel)
        self.downLabel.clicked.connect(self.on_downLabel)

        self.addLayout(self.labelLayout)

        self.spinBox = QSpinBox()
        self.spinBox.valueChanged.connect(self.spinBoxValueChanged)
        self.addWidget(self.spinBox)
        self.spinBox.setToolTip("Spinbox")
        self.spinBox.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.spinBox.setAlignment(Qt.AlignRight)
        self.spinBox.setMaximum(value)
        self.spinBox.setMaximumHeight(height)
        self.spinBox.setSuffix("/" + str(value))
        font = self.spinBox.font()
        font.setPixelSize(fontSize)
        self.spinBox.setFont(font)
        self.do_draw()

    def do_draw(self):
        r, g, b, a = self.foregroundColor.getRgb()
        rgb = "rgb({0},{1},{2})".format(r, g, b)
        sheet = TEMPLATE.format(rgb,
                                self.backgroundColor.name())
        self.spinBox.setStyleSheet(sheet)

    def spinBoxValueChanged(self, value):
        self.valueChanged.emit(value)

    def setValue(self, value):
        self.spinBox.setValue(value)

    def setNewValue(self, value):
        self.spinBox.setMaximum(value)
        self.spinBox.setSuffix("/" + str(value))

    def on_upLabel(self):
        self.spinBox.setValue(self.spinBox.value() + 1)

    def on_downLabel(self):
        self.spinBox.setValue(self.spinBox.value() - 1)
Exemple #16
0
    class Ui_MainWindow(object):
        """ This code is normally generated by Qt Designer """

        def setupUi(self, MainWindow):
            """
            """

            MainWindow.resize(100,200)

            # Create the "Central Widget" and add a "Layout"
            self.centralwidget = QWidget(MainWindow)
            MainWindow.setCentralWidget(self.centralwidget)
            self.verticalLayout= QVBoxLayout(self.centralwidget)

            # Add a Temperature sensor and Label Widgets
            self.t1 = QFellesSolenoidValve(self.centralwidget)

            # Add Widgets to Layout
            self.verticalLayout.addWidget(self.t1)

            # Create the Menu bar
            self.menubar = QMenuBar(MainWindow)
            MainWindow.setMenuBar(self.menubar)
            # Create the Status Bar
            self.statusbar = QStatusBar(MainWindow)
            MainWindow.setStatusBar(self.statusbar)

            self.retranslateUi(MainWindow)

        def retranslateUi(self, MainWindow):
            """
            """
            pass
    def create_main_frame(self):

        self.fig = Figure(dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.setFocusPolicy( Qt.ClickFocus )
        self.canvas.setFocus()

        self.mpl_toolbar = myNavigationToolbar(self.canvas, self)
        self.canvas.mpl_connect('button_press_event', self.on_click)
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('key_release_event', self.on_key_release)
        #self.canvas.mpl_connect('button_press_event', self.disable_clicks)


        self.cbar_button = QPushButton("Color Range")
        self.cbar_button.setFocusPolicy( Qt.NoFocus )
        self.grid_cb = QCheckBox("Show Grid")
        self.grid_cb.setFocusPolicy( Qt.NoFocus )
        self.grid_cb.stateChanged.connect(self.showGrid)

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()

        vbox.addWidget(self.canvas)  # the matplotlib canvas
        hbox.addWidget(self.mpl_toolbar)
        hbox.addWidget(self.cbar_button)
        hbox.addWidget(self.grid_cb)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
Exemple #18
0
class ProprietesAvance(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.objets = parent.objets
        self.panel = self.parent.parent.panel
        self.canvas = self.parent.parent.canvas
        self.islabel = self.parent.parent.islabel

        self.sizer = QVBoxLayout()
        if len(self.objets) is 1:
            self.objet = self.objets[0]

            style = QVBoxLayout()
            style_box = QGroupBox(u"Style de l'objet")
            style_box.setLayout(style)
            style.addWidget(QLabel(u"Attention, ne modifiez ce contenu que si vous savez ce que vous faites."))
            self.avance = QTextEdit()
            self.avance.setMinimumSize(350, 200)
            self.actualiser()
            style.addWidget(self.avance)
            self.sizer.addWidget(style_box)

            ok = QPushButton('OK')
            appliquer = QPushButton(u"Appliquer")
            actualiser = QPushButton(u"Actualiser")
            ok.clicked.connect(self.EvtOk)
            appliquer.clicked.connect(self.EvtAppliquer)
            actualiser.clicked.connect(self.actualiser)
            boutons = QHBoxLayout()
            boutons.addWidget(ok)
            boutons.addWidget(appliquer)
            boutons.addWidget(actualiser)
            self.sizer.addLayout(boutons)

        self.setLayout(self.sizer)
        ##self.parent.parent.dim3 = self.sizer.CalcMin().Get()

    def EvtOk(self):
        self.EvtAppliquer()
        self.parent.parent.fenetre_principale.raise_()
        self.parent.parent.close() # fermeture de la frame


    def EvtAppliquer(self):
        txt = self.avance.toPlainText().split('\n')
        dico = "{"
        for ligne in txt:
            key, value = ligne.split(":", 1)
            key = "'" + key.strip() + "':"
            dico += key + value + ","
        dico += "}"
        if self.islabel:
            self.canvas.executer(u"%s.etiquette.style(**%s)" %(self.objet.parent.nom, dico))
        else:
            self.canvas.executer(u"%s.style(**%s)" %(self.objet.nom, dico))

    def actualiser(self, event = None):
        items = (txt.split(':', 1) for txt in advanced_split(str(self.objet.style())[1:-1], ","))
        self.avance.setPlainText('\n'.join(sorted(key.strip()[1:-1] + ':' + value for key, value in items)))
Exemple #19
0
    def __init__(self, parent, objets, islabel = False):
        u"Le paramètre 'label' indique si l'objet à éditer est un label"
        print "OBJETS:"
        print objets
        print unicode(objets[0])
        print repr(objets[0])
        print objets[0].__class__
        print isinstance(objets[0], str)
        objets[0].titre_complet("du", False)
        self.parent = parent
        self.islabel = islabel
        self.fenetre_principale = self.parent.window()
        self.panel = self.fenetre_principale.onglets.onglet_actuel
        self.canvas = self.panel.canvas

        self.objets = objets
        if self.islabel:
            titre = u"du label"
        else:
            if len(objets) == 0:
                self.close()
            if len(objets) == 1:
                titre = objets[0].titre_complet("du", False)
            else:
                titre = u"des objets"
#        wx.MiniFrame.__init__(self, parent, -1, u"Propriétés " + titre, style=wx.DEFAULT_FRAME_STYLE | wx.TINY_CAPTION_HORIZ)
        QDialog.__init__(self, parent)
        self.setWindowTitle(u"Propriétés " + titre)
        self.setPalette(white_palette)
        ##self.SetExtraStyle(wx.WS_EX_BLOCK_EVENTS )
        main = QVBoxLayout()
        self.setLayout(main)
        self.onglets = OngletsProprietes(self)
        main.addWidget(self.onglets)
Exemple #20
0
    def __init__(self, pathProjects, parent=None):
        #pathProjects must be a list
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Add File to Project"))
        self.pathSelected = ''
        vbox = QVBoxLayout(self)

        self._tree = QTreeWidget()
        self._tree.header().setHidden(True)
        self._tree.setSelectionMode(QTreeWidget.SingleSelection)
        self._tree.setAnimated(True)
        vbox.addWidget(self._tree)
        hbox = QHBoxLayout()
        btnAdd = QPushButton(self.tr("Add here!"))
        btnCancel = QPushButton(self.tr("Cancel"))
        hbox.addWidget(btnCancel)
        hbox.addWidget(btnAdd)
        vbox.addLayout(hbox)
        #load folders
        self._root = None
        for pathProject in pathProjects:
            folderStructure = file_manager.open_project(pathProject)
            self._load_project(folderStructure, pathProject)

        self.connect(btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(btnAdd, SIGNAL("clicked()"), self._select_path)
Exemple #21
0
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletUVLight, *args)

        self.uv_light = self.device

        self.cbe_uv_light = CallbackEmulator(self.uv_light.get_uv_light,
                                             self.cb_uv_light,
                                             self.increase_error_count)

        self.uv_label = UVLabel(u'UV Light: ')
        self.index_label = IndexLabel(u'UV Index: ')

        self.current_uv_light = None
        
        plot_list = [['', Qt.red, self.get_current_uv_light]]
        self.plot_widget_uv = PlotWidget(u'UV Light [µW/cm²]', plot_list)
        
        layout_h1 = QHBoxLayout()
        layout_h1.addStretch()
        layout_h1.addWidget(self.uv_label)
        layout_h1.addStretch()
        
        layout_h2 = QHBoxLayout()
        layout_h2.addStretch()
        layout_h2.addWidget(self.index_label)
        layout_h2.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h1)
        layout.addLayout(layout_h2)
        layout.addWidget(self.plot_widget_uv)
    def add_tweets_widgets(self):
        for tab in [self.main_form.all_tweets_tab, self.main_form.recommended_tweets_tab]:
            tab_layout = QVBoxLayout()
            tab.setLayout(tab_layout)

            tab.tweets_widget = TweetsWidget()
            tab_layout.addWidget(tab.tweets_widget)
Exemple #23
0
    def __init__(self):
        super(MainWidget, self).__init__()

        self.collectionView = QWebView()
        self.collectionView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        # self.collectionView.page().setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
        self.setZoomFactor(QSettings().value("zoom_factor", QVariant(1.0)).toDouble()[0])
        self.connect(self.collectionView, SIGNAL("linkClicked(const QUrl&)"), self.linkClicked)

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

        self.smewtd = SmewtDaemon()
        self.smewtd.taskManager.progressChanged.connect(self.progressChanged)

        self.setLayout(layout)

        self.history = []
        self.index = 0
        baseUrl = QSettings().value("base_url").toString()
        if baseUrl == "":
            baseUrl = "smewt://media/speeddial/"
        self.setSmewtUrl(baseUrl)
        # somehow it looks like this refresh is necessary otherwise our main widget doesn't get inserted in the javascript
        self.refreshCollectionView()

        self.externalProcess = QProcess()
    def __init__(self, path):
        """Plugin dialog

        'path'
            Path of the ninja.exe.log
        """

        super(ninjaErrorLogDialog, self).__init__()

        # Set log path
        self._path = path

        self.setWindowTitle('Ninja Error Log')
        self.setFixedSize(600, 400)

        # Create text area and load file
        self.editor = QTextEdit()
        self.editor.setReadOnly(True)

        with open(self._path, 'r') as f:
            self.editor.setPlainText(f.read())
            f.close()

        # Create delete button
        self.delete_button = QPushButton('Delete log file')
        self.delete_button.setToolTip('Requires admin permissions.')

        # Create central layout and add widgets
        vlayout = QVBoxLayout(self)
        vlayout.addWidget(self.editor)
        vlayout.addWidget(self.delete_button)

        # SIGNALS
        self.connect(self.delete_button, SIGNAL('clicked()'), self._delete_log)
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     vbox = QVBoxLayout(self)
     self._webInspector = QWebInspector(self)
     vbox.addWidget(self._webInspector)
     self.btnDock = QPushButton(self.tr("Undock"))
     vbox.addWidget(self.btnDock)
Exemple #26
0
    def __init__(self, pathProjects, parent=None):
        #pathProjects must be a list
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Add File to Project"))
        self.pathSelected = ''
        vbox = QVBoxLayout(self)

        self._tree = QTreeWidget()
        self._tree.header().setHidden(True)
        self._tree.setSelectionMode(QTreeWidget.SingleSelection)
        self._tree.setAnimated(True)
        vbox.addWidget(self._tree)
        hbox = QHBoxLayout()
        btnAdd = QPushButton(self.tr("Add here!"))
        btnCancel = QPushButton(self.tr("Cancel"))
        hbox.addWidget(btnCancel)
        hbox.addWidget(btnAdd)
        vbox.addLayout(hbox)
        #load folders
        self._root = None
        self._loading_items = {}
        self.loading_projects(pathProjects)
        self._thread_execution = ThreadExecution(
            self._thread_load_projects, args=[pathProjects])
        self.connect(self._thread_execution,
                     SIGNAL("finished()"), self._callback_load_project)
        self._thread_execution.start()

        self.connect(btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(btnAdd, SIGNAL("clicked()"), self._select_path)
Exemple #27
0
 def __init__(self, base):
     QVBoxLayout.__init__(self)
     self.base = base
     self.child = None
     self.columns = {}
     self.is_empty = None
     self.loading()
    def __init__(self, data, title="", comment="",
                 icon=None, parent=None, apply=None):
        super(FormDialog, self).__init__(parent)

        self.apply_callback = apply
        
        # Form
        if isinstance(data[0][0], (list, tuple)):
            self.formwidget = FormTabWidget(data, comment=comment,
                                            parent=self)
        elif len(data[0])==3:
            self.formwidget = FormComboWidget(data, comment=comment,
                                              parent=self)
        else:
            self.formwidget = FormWidget(data, comment=comment, 
                                         parent=self)
        layout = QVBoxLayout()
        layout.addWidget(self.formwidget)
        
        # Button box
        bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        if self.apply_callback is not None:
            apply_btn = bbox.addButton(QDialogButtonBox.Apply)
            self.connect(apply_btn, SIGNAL("clicked()"), self.apply)
        self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()"))
        self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()"))
        layout.addWidget(bbox)

        self.setLayout(layout)
        
        self.setWindowTitle(title)
        if not isinstance(icon, QIcon):
            icon = QWidget().style().standardIcon(QStyle.SP_MessageBoxQuestion)
        self.setWindowIcon(icon)
    def __init__(self):
        super(Window, self).__init__()
        self.view = QWebView(self)

        layout = QVBoxLayout(self)
        layout.setMargin(0)
        layout.addWidget(self.view)
Exemple #30
0
    def __init__(self, page, parent=None):
        super(HelpForm, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAttribute(Qt.WA_GroupLeader)

        backAction = QAction(QIcon(":/back.png"), "&Back", self)
        backAction.setShortcut(QKeySequence.Back)
        homeAction = QAction(QIcon(":/home.png"), "&Home", self)
        homeAction.setShortcut("Home")
        self.pageLabel = QLabel()

        toolBar = QToolBar()
        toolBar.addAction(backAction)
        toolBar.addAction(homeAction)
        toolBar.addWidget(self.pageLabel)
        self.textBrowser = QTextBrowser()

        layout = QVBoxLayout()
        layout.addWidget(toolBar)
        layout.addWidget(self.textBrowser, 1)
        self.setLayout(layout)

        self.connect(backAction, SIGNAL("triggered()"),
                     self.textBrowser, SLOT("backward()"))
        self.connect(homeAction, SIGNAL("triggered()"),
                     self.textBrowser, SLOT("home()"))
        self.connect(self.textBrowser, SIGNAL("sourceChanged(QUrl)"),
                     self.updatePageTitle)

        self.textBrowser.setSearchPaths([":/help"])
        self.textBrowser.setSource(QUrl(page))
        self.resize(400, 600)
        self.setWindowTitle("{0} Help".format(
                QApplication.applicationName()))
Exemple #31
0
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletAnalogIn, *args)

        self.ai = self.device

        self.cbe_voltage = CallbackEmulator(self.ai.get_voltage,
                                            self.cb_voltage,
                                            self.increase_error_count)

        self.voltage_label = VoltageLabel('Voltage: ')

        self.current_value = None

        plot_list = [['', Qt.red, self.get_current_value]]
        self.plot_widget = PlotWidget('Voltage [mV]', plot_list)

        layout_h2 = QHBoxLayout()
        layout_h2.addStretch()
        layout_h2.addWidget(self.voltage_label)
        layout_h2.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h2)
        layout.addWidget(self.plot_widget)

        if self.firmware_version >= (2, 0, 1):
            self.combo_range = QComboBox()
            self.combo_range.addItem('Automatic',
                                     BrickletAnalogIn.RANGE_AUTOMATIC)
            if self.firmware_version >= (2, 0, 3):
                self.combo_range.addItem('0V - 3.30V',
                                         BrickletAnalogIn.RANGE_UP_TO_3V)
            self.combo_range.addItem('0V - 6.05V',
                                     BrickletAnalogIn.RANGE_UP_TO_6V)
            self.combo_range.addItem('0V - 10.32V',
                                     BrickletAnalogIn.RANGE_UP_TO_10V)
            self.combo_range.addItem('0V - 36.30V',
                                     BrickletAnalogIn.RANGE_UP_TO_36V)
            self.combo_range.addItem('0V - 45.00V',
                                     BrickletAnalogIn.RANGE_UP_TO_45V)
            self.combo_range.currentIndexChanged.connect(self.range_changed)

            layout_h1 = QHBoxLayout()
            layout_h1.addStretch()
            layout_h1.addWidget(QLabel('Range:'))
            layout_h1.addWidget(self.combo_range)

            if self.firmware_version >= (2, 0, 3):
                self.spin_average = QSpinBox()
                self.spin_average.setMinimum(0)
                self.spin_average.setMaximum(255)
                self.spin_average.setSingleStep(1)
                self.spin_average.setValue(50)
                self.spin_average.editingFinished.connect(
                    self.spin_average_finished)

                layout_h1.addStretch()
                layout_h1.addWidget(QLabel('Average Length:'))
                layout_h1.addWidget(self.spin_average)

            layout_h1.addStretch()
            layout.addLayout(layout_h1)
 def __init__(self, parent=None):
     super(AffectiveCaDialog, self).__init__(parent)
     
     ko = 0
     self.subjects = self.pullSubjects()
     
     self.frame1 = QGroupBox('Behaviors')
     self.frame2 = QGroupBox('Categories')
     
     hc1_box = QVBoxLayout()
     hc2_box = QVBoxLayout()
     self.li = []
     self.liID = []
     for subject in self.subjects:
         num = subject['id']
         self.liID.append(num)
         self.c = QRadioButton('cb'+str(num))
         self.c.setText(str(subject['name']).upper())
         self.c.setObjectName("chk"+str(num))
         self.c.setChecked(False)
         self.c.toggled.connect(lambda state, x=num, y=self.c: self.catItems(x, y))
         hc1_box.addWidget(self.c)
         self.li.append(self.c)
         
         ko += 1
        
     
     self.li1 = []
     self.li1ID = []
     self.hc2_box = QVBoxLayout()
         
     self.frame1.setLayout(hc1_box)
     #frame1.setFrameShape(QFrame.StyledPanel)
     self.frame2.setLayout(self.hc2_box)
     #frame2.setFrameShape(QFrame.StyledPanel)
     
     h_box = QHBoxLayout()
     h_box.addWidget(self.frame1)
     h_box.addWidget(self.frame2)
     
     
     self.pb = QPushButton()
     self.pb.setObjectName("MakeEntries")
     self.pb.setText("Edit View")
     
     self.pb1 = QPushButton()
     self.pb1.setObjectName("View Report")
     self.pb1.setText("Report View")
     
     self.pb2 = QPushButton()
     self.pb2.setObjectName("Cancel")
     self.pb2.setText("Cancel")
     
     but_box = QHBoxLayout()
     but_box.addWidget(self.pb2)
     but_box.addWidget(self.pb1)
     but_box.addWidget(self.pb)
     
     main_box = QVBoxLayout()
     main_box.addLayout(h_box)
     main_box.addLayout(but_box)
     
     
     self.setLayout(main_box)
     self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
     self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
     self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close())
     self.setWindowTitle(self.pagetitle)
class AffectiveCaDialog(QDialog):
    pagetitle = 'Behavioural-Assessment'
    holdc = {}
    hold  = []
    def __init__(self, parent=None):
        super(AffectiveCaDialog, self).__init__(parent)
        
        ko = 0
        self.subjects = self.pullSubjects()
        
        self.frame1 = QGroupBox('Behaviors')
        self.frame2 = QGroupBox('Categories')
        
        hc1_box = QVBoxLayout()
        hc2_box = QVBoxLayout()
        self.li = []
        self.liID = []
        for subject in self.subjects:
            num = subject['id']
            self.liID.append(num)
            self.c = QRadioButton('cb'+str(num))
            self.c.setText(str(subject['name']).upper())
            self.c.setObjectName("chk"+str(num))
            self.c.setChecked(False)
            self.c.toggled.connect(lambda state, x=num, y=self.c: self.catItems(x, y))
            hc1_box.addWidget(self.c)
            self.li.append(self.c)
            
            ko += 1
           
        
        self.li1 = []
        self.li1ID = []
        self.hc2_box = QVBoxLayout()
            
        self.frame1.setLayout(hc1_box)
        #frame1.setFrameShape(QFrame.StyledPanel)
        self.frame2.setLayout(self.hc2_box)
        #frame2.setFrameShape(QFrame.StyledPanel)
        
        h_box = QHBoxLayout()
        h_box.addWidget(self.frame1)
        h_box.addWidget(self.frame2)
        
        
        self.pb = QPushButton()
        self.pb.setObjectName("MakeEntries")
        self.pb.setText("Edit View")
        
        self.pb1 = QPushButton()
        self.pb1.setObjectName("View Report")
        self.pb1.setText("Report View")
        
        self.pb2 = QPushButton()
        self.pb2.setObjectName("Cancel")
        self.pb2.setText("Cancel")
        
        but_box = QHBoxLayout()
        but_box.addWidget(self.pb2)
        but_box.addWidget(self.pb1)
        but_box.addWidget(self.pb)
        
        main_box = QVBoxLayout()
        main_box.addLayout(h_box)
        main_box.addLayout(but_box)
        
        
        self.setLayout(main_box)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close())
        self.setWindowTitle(self.pagetitle)

    
    def catItems(self, a, b):
        _a = a
        self.cas = self.pullCas(_a)
        self.li1 = []
        self.li1ID = []
        for rp in self.hold:
            self.hc2_box.removeWidget(rp)
            sip.delete(rp)
        
        self.hold = []
        ko = 0
        for ca in self.cas:
            num = ca['id']
            self.li1ID.append(num)
            self.c1 = QCheckBox('cbx'+str(num))
            self.c1.setText(str(ca['name']).upper())
            self.c1.setObjectName("chkx"+str(num))
            self.c1.setChecked(True)
            self.hc2_box.addWidget(self.c1)
            self.hold.append(self.c1)
            self.li1.append(self.c1)
            ko += 1
            
        
        #self.hc2_box.show()
        
    
    def pullSubjects(self):
        cn = Db()
        arr = cn.selectn('datas', '' , '', {'pubID': 11})
        return arr
    
    def pullCas(self, a):
        _a = a
        cn = Db()
        arr = cn.selectn('datas', '' , '', {'subID': _a})
        return arr
    
    def button_close(self):
        self.reject()
        
    def button_click(self):
        self.accept()
        
    def getValue(self):
        
        k1 = []
        k2 = []
        for s in range(0, len(self.li)):
            if self.li[s].isChecked():
                k1.append(self.liID[s])
            else:
                k2.append(self.liID[s])
                 
          
        
    
        k11 = []
        k21 = []
        for s in range(0, len(self.li1)):
            if self.li1[s].isChecked():
                k11.append(self.li1ID[s])
            else:
                k21.append(self.li1ID[s])
                 
        return [k1, k11] 
Exemple #34
0
    def setupUi(self):
        self.setWindowTitle(self.tr('Parameter definition'))

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(40)
        self.verticalLayout.setMargin(20)

        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.label = QLabel(self.tr('Parameter name'))
        self.horizontalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.horizontalLayout.addWidget(self.nameTextBox)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.horizontalLayout2 = QHBoxLayout(self)
        self.horizontalLayout2.setSpacing(2)
        self.horizontalLayout2.setMargin(0)
        self.horizontalLayout3 = QHBoxLayout(self)
        self.horizontalLayout3.setSpacing(2)
        self.horizontalLayout3.setMargin(0)
        self.horizontalLayout4 = QHBoxLayout(self)
        self.horizontalLayout4.setSpacing(2)
        self.horizontalLayout4.setMargin(0)

        if isinstance(self.param, Parameter):
            self.nameTextBox.setText(self.param.description)

        if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \
           isinstance(self.param, ParameterBoolean):
            self.state = QCheckBox()
            self.state.setText(self.tr('Checked'))
            self.state.setChecked(False)
            if self.param is not None:
                self.state.setChecked(True if self.param.value else False)
            self.horizontalLayout3.addWidget(self.state)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in self.alg.inputs.values():
                if isinstance(param.param, (ParameterVector, ParameterTable)):
                    self.parentCombo.addItem(param.param.description,
                                             param.param.name)
                    if self.param is not None:
                        if self.param.parent == param.param.name:
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.horizontalLayout3.addWidget(self.parentCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type')))
            self.shapetypeCombo = QComboBox()
            self.shapetypeCombo.addItem(self.tr('Any'))
            self.shapetypeCombo.addItem(self.tr('Point'))
            self.shapetypeCombo.addItem(self.tr('Line'))
            self.shapetypeCombo.addItem(self.tr('Polygon'))
            if self.param is not None:
                self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] +
                                                    1)
            self.horizontalLayout3.addWidget(self.shapetypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Vector (any)'))
            self.datatypeCombo.addItem(self.tr('Vector (point)'))
            self.datatypeCombo.addItem(self.tr('Vector (line)'))
            self.datatypeCombo.addItem(self.tr('Vector (polygon)'))
            self.datatypeCombo.addItem(self.tr('Raster'))
            self.datatypeCombo.addItem(self.tr('Table'))
            if self.param is not None:
                self.datatypeCombo.setCurrentIndex(self.param.datatype + 1)
            self.horizontalLayout3.addWidget(self.datatypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values')))
            self.minTextBox = QLineEdit()
            self.maxTextBox = QLineEdit()
            if self.param is not None:
                self.minTextBox.setText(unicode(self.param.min))
                self.maxTextBox.setText(unicode(self.param.max))
            self.horizontalLayout3.addWidget(self.minTextBox)
            self.horizontalLayout3.addWidget(self.maxTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
            self.horizontalLayout4.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.default
                if self.param.isInteger:
                    default = int(math.floor(default))
                self.defaultTextBox.setText(unicode(default))
            self.horizontalLayout4.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout4)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.default)
            self.horizontalLayout3.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Type')))
            self.fileFolderCombo = QComboBox()
            self.fileFolderCombo.addItem(self.tr('File'))
            self.fileFolderCombo.addItem(self.tr('Folder'))
            if self.param is not None:
                self.fileFolderCombo.setCurrentIndex(
                    1 if self.param.isFolder else 0)
            self.horizontalLayout3.addWidget(self.fileFolderCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)

        self.horizontalLayout2.addWidget(QLabel(self.tr('Required')))
        self.yesNoCombo = QComboBox()
        self.yesNoCombo.addItem(self.tr('Yes'))
        self.yesNoCombo.addItem(self.tr('No'))
        self.horizontalLayout2.addWidget(self.yesNoCombo)
        if self.param is not None:
            self.yesNoCombo.setCurrentIndex(1 if self.param.optional else 0)
        self.verticalLayout.addLayout(self.horizontalLayout2)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)
Exemple #35
0
class ModelerParameterDefinitionDialog(QDialog):

    PARAMETER_NUMBER = 'Number'
    PARAMETER_RASTER = 'Raster layer'
    PARAMETER_TABLE = 'Table'
    PARAMETER_VECTOR = 'Vector layer'
    PARAMETER_STRING = 'String'
    PARAMETER_BOOLEAN = 'Boolean'
    PARAMETER_TABLE_FIELD = 'Table field'
    PARAMETER_EXTENT = 'Extent'
    PARAMETER_FILE = 'File'

    # To add
    PARAMETER_MULTIPLE = 'Multiple input'
    PARAMETER_FIXED_TABLE = 'Fixed table'

    paramTypes = [
        PARAMETER_BOOLEAN,
        PARAMETER_EXTENT,
        PARAMETER_FILE,
        PARAMETER_NUMBER,
        PARAMETER_RASTER,
        PARAMETER_STRING,
        PARAMETER_TABLE,
        PARAMETER_TABLE_FIELD,
        PARAMETER_VECTOR,
    ]

    def __init__(self, alg, paramType=None, param=None):
        self.alg = alg
        self.paramType = paramType
        self.param = param
        QDialog.__init__(self)
        self.setModal(True)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle(self.tr('Parameter definition'))

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(40)
        self.verticalLayout.setMargin(20)

        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.label = QLabel(self.tr('Parameter name'))
        self.horizontalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.horizontalLayout.addWidget(self.nameTextBox)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.horizontalLayout2 = QHBoxLayout(self)
        self.horizontalLayout2.setSpacing(2)
        self.horizontalLayout2.setMargin(0)
        self.horizontalLayout3 = QHBoxLayout(self)
        self.horizontalLayout3.setSpacing(2)
        self.horizontalLayout3.setMargin(0)
        self.horizontalLayout4 = QHBoxLayout(self)
        self.horizontalLayout4.setSpacing(2)
        self.horizontalLayout4.setMargin(0)

        if isinstance(self.param, Parameter):
            self.nameTextBox.setText(self.param.description)

        if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \
           isinstance(self.param, ParameterBoolean):
            self.state = QCheckBox()
            self.state.setText(self.tr('Checked'))
            self.state.setChecked(False)
            if self.param is not None:
                self.state.setChecked(True if self.param.value else False)
            self.horizontalLayout3.addWidget(self.state)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in self.alg.inputs.values():
                if isinstance(param.param, (ParameterVector, ParameterTable)):
                    self.parentCombo.addItem(param.param.description,
                                             param.param.name)
                    if self.param is not None:
                        if self.param.parent == param.param.name:
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.horizontalLayout3.addWidget(self.parentCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type')))
            self.shapetypeCombo = QComboBox()
            self.shapetypeCombo.addItem(self.tr('Any'))
            self.shapetypeCombo.addItem(self.tr('Point'))
            self.shapetypeCombo.addItem(self.tr('Line'))
            self.shapetypeCombo.addItem(self.tr('Polygon'))
            if self.param is not None:
                self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] +
                                                    1)
            self.horizontalLayout3.addWidget(self.shapetypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Vector (any)'))
            self.datatypeCombo.addItem(self.tr('Vector (point)'))
            self.datatypeCombo.addItem(self.tr('Vector (line)'))
            self.datatypeCombo.addItem(self.tr('Vector (polygon)'))
            self.datatypeCombo.addItem(self.tr('Raster'))
            self.datatypeCombo.addItem(self.tr('Table'))
            if self.param is not None:
                self.datatypeCombo.setCurrentIndex(self.param.datatype + 1)
            self.horizontalLayout3.addWidget(self.datatypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values')))
            self.minTextBox = QLineEdit()
            self.maxTextBox = QLineEdit()
            if self.param is not None:
                self.minTextBox.setText(unicode(self.param.min))
                self.maxTextBox.setText(unicode(self.param.max))
            self.horizontalLayout3.addWidget(self.minTextBox)
            self.horizontalLayout3.addWidget(self.maxTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
            self.horizontalLayout4.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.default
                if self.param.isInteger:
                    default = int(math.floor(default))
                self.defaultTextBox.setText(unicode(default))
            self.horizontalLayout4.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout4)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.default)
            self.horizontalLayout3.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Type')))
            self.fileFolderCombo = QComboBox()
            self.fileFolderCombo.addItem(self.tr('File'))
            self.fileFolderCombo.addItem(self.tr('Folder'))
            if self.param is not None:
                self.fileFolderCombo.setCurrentIndex(
                    1 if self.param.isFolder else 0)
            self.horizontalLayout3.addWidget(self.fileFolderCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)

        self.horizontalLayout2.addWidget(QLabel(self.tr('Required')))
        self.yesNoCombo = QComboBox()
        self.yesNoCombo.addItem(self.tr('Yes'))
        self.yesNoCombo.addItem(self.tr('No'))
        self.horizontalLayout2.addWidget(self.yesNoCombo)
        if self.param is not None:
            self.yesNoCombo.setCurrentIndex(1 if self.param.optional else 0)
        self.verticalLayout.addLayout(self.horizontalLayout2)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)

    def okPressed(self):
        description = unicode(self.nameTextBox.text())
        if description.strip() == '':
            QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                self.tr('Invalid parameter name'))
            return
        if self.param is None:
            validChars = \
                'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
            safeName = ''.join(c for c in description if c in validChars)
            name = safeName.lower()
            i = 2
            while name in self.alg.inputs:
                name = safeName.lower() + str(i)
        else:
            name = self.param.name
        if self.paramType \
                == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \
                or isinstance(self.param, ParameterBoolean):
            self.param = ParameterBoolean(name, description,
                                          self.state.isChecked())
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            if self.parentCombo.currentIndex() < 0:
                QMessageBox.warning(
                    self, self.tr('Unable to define parameter'),
                    self.tr('Wrong or missing parameter values'))
                return
            parent = self.parentCombo.itemData(self.parentCombo.currentIndex())
            self.param = ParameterTableField(name, description, parent)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \
                isinstance(self.param, ParameterRaster):
            self.param = ParameterRaster(name, description,
                                         self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \
                isinstance(self.param, ParameterTable):
            self.param = ParameterTable(name, description,
                                        self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.param = ParameterVector(
                name, description, [self.shapetypeCombo.currentIndex() - 1],
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.param = ParameterMultipleInput(
                name, description,
                self.datatypeCombo.currentIndex() - 1,
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            try:
                vmin = unicode(self.minTextBox.text()).strip()
                if vmin == '':
                    vmin = None
                else:
                    vmin = float(vmin)
                vmax = unicode(self.maxTextBox.text()).strip()
                if vmax == '':
                    vmax = None
                else:
                    vmax = float(vmax)
                self.param = ParameterNumber(
                    name, description, vmin, vmax,
                    unicode(self.defaultTextBox.text()))
            except:
                QMessageBox.warning(
                    self, self.tr('Unable to define parameter'),
                    self.tr('Wrong or missing parameter values'))
                return
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.param = ParameterString(name, description,
                                         unicode(self.defaultTextBox.text()))
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \
                isinstance(self.param, ParameterExtent):
            self.param = ParameterExtent(name, description)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            isFolder = self.fileFolderCombo.currentIndex() == 1
            self.param = ParameterFile(name, description, isFolder=isFolder)
        self.param.optional = self.yesNoCombo.currentIndex() == 1
        self.close()

    def cancelPressed(self):
        self.param = None
        self.close()
Exemple #36
0
 def create_layout(self):
     """Returns the main layout for our widget."""
     return QVBoxLayout()
Exemple #37
0
class EvtViewer(QWidget, Script):
    def __init__(self):
        Script.__init__(self, "EvtViewer")
        self.type = "EvtViewer"
        self.t = None

    def start(self, args):
        try:
            self.preview = args['preview'].value()
        except IndexError:
            self.preview = False

        try:
            self.node = args['file'].value()
        except (KeyError, Exception):
            print "No input file provided. Exiting."

        self.t = EVTX()
        if not self.preview:
            self.t.start(args)
            processus_manager = ModuleProcessusManager()
            evtx = processus_manager.get('evtx')
            evtx.update(self.t)

    def updateWidget(self):
        pass

    def initCallback(self):
        pass

    def refresh(self):
        pass

    def c_display(self):
        print "cannot display in console mode. You must use the gui"

    def g_display(self):
        QWidget.__init__(self)
        self.layout = QVBoxLayout(self)

        processus_manager = ModuleProcessusManager()
        evtx = processus_manager.get('evtx')

        if not self.preview:
            self.viewer = EventLogViewer(self.node, evtx.data(self.node.uid()))
            self.layout.addWidget(self.viewer)
            self.name = self.node.name()
            self.viewer.display(evtx.data(self.node.uid()), self.node)
        else:
            self.build_preview()

    #def report(self):
    #reportManager = ReportManager()
    #events = self.viewer.evtx_table_view.selectedEvents()
    #if events and len(events):
    #doc = EvtxDocument(events, str(self.node.name()), 'Case/Events')
    #reportManager.addReportDocument(doc)

    def build_preview(self):
        data = self.t.light_parser(self.node)

        self.layout.addWidget(QLabel("File name : " + data['File']))

        tmp_widget = QWidget()
        tmp_layout = QHBoxLayout(tmp_widget)

        tmp_layout.addWidget(QLabel("Oldest chunk : " + data['Oldest']))
        tmp_layout.addWidget(QLabel("Current chunk : " + data['Current']))
        tmp_layout.addWidget(QLabel("Next record : " + data['Next']))
        tmp_layout.addWidget(
            QLabel("Version : " + data['Maj'] + "." + data['Min']))
        tmp_layout.addWidget(QLabel("Chunk number : " + data['chunk_nb']))
        self.layout.addWidget(tmp_widget)

        data_list = QTableWidget()
        data_list.setColumnCount(4)

        data_list.setHorizontalHeaderLabels(
            ['Chunk number', 'First record', 'Last record', 'Offset'])
        data_list.horizontalHeader().setStretchLastSection(True)
        data_list.verticalHeader().hide()
        data_list.setSortingEnabled(False)
        data_list.setSelectionBehavior(QAbstractItemView.SelectRows)
        data_list.setEditTriggers(QAbstractItemView.NoEditTriggers)

        data_list.setRowCount(int(data['chunk_nb']))
        for chunk_count in range(int(data['chunk_nb'])):
            rec = data[str(chunk_count)]

            data_list.setItem(chunk_count, 0,
                              QTableWidgetItem(str(chunk_count)))
            data_list.setItem(chunk_count, 1, QTableWidgetItem(rec[0]))
            data_list.setItem(chunk_count, 2, QTableWidgetItem(rec[1]))
            data_list.setItem(chunk_count, 3, QTableWidgetItem(rec[2]))

        self.layout.addWidget(data_list)

    def closeEvent(self, event):
        pass
Exemple #38
0
class ParamsDialog(QDialog):

    data = {}
    ui = {}

    def __init__(self,
                 config,
                 parent,
                 replication_checkbox=False,
                 segmentation_checkbox=False):
        QDialog.__init__(self)
        self.setStyleSheet(parent.styleSheet())
        self.setWindowTitle("Method Settings")
        self.data = config
        self.ui = {}
        self.area = QScrollArea()
        self.widget = QWidget()
        l = self._parseConfig(self.data, self.ui)
        self.widget.setLayout(l)
        self.area.setWidget(self.widget)
        self.area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.area)
        if replication_checkbox:
            self.replication_checkbox = QCheckBox(self.tr("Allow replication"))
            self.layout.addWidget(self.replication_checkbox)
        if segmentation_checkbox:
            self.segmentation_checkbox = QCheckBox(
                self.tr("Generate assegnments in segments"))
            self.layout.addWidget(self.segmentation_checkbox)
        self.buttons = QHBoxLayout()
        self.ok = QPushButton("OK")
        self.cancel = QPushButton("Cancel")
        self.buttons.addWidget(self.ok)
        self.buttons.addWidget(self.cancel)
        self.layout.addLayout(self.buttons)
        self.setLayout(self.layout)
        QObject.connect(self.ok, SIGNAL("clicked()"), self.OK)
        QObject.connect(self.cancel, SIGNAL("clicked()"), self.Cancel)

    def _parseDict(self, config, ui):
        l = QVBoxLayout()
        lst = list(config.keys())
        for k in lst:
            t = type(config[k])
            if t == type(int()):
                hbox = QHBoxLayout()
                label = QLabel(k)
                edit = QLineEdit(str(config[k]))
                val = QIntValidator(self)
                edit.setValidator(val)
                hbox.addWidget(label)
                hbox.addWidget(edit)
                l.addLayout(hbox)
                ui[k] = (edit, label, hbox, val)
            elif t == type(float()):
                hbox = QHBoxLayout()
                label = QLabel(k)
                edit = QLineEdit(str(config[k]))
                val = QDoubleValidator(self)
                edit.setValidator(val)
                hbox.addWidget(label)
                hbox.addWidget(edit)
                l.addLayout(hbox)
                ui[k] = (edit, label, hbox, val)
            elif t == type(list()):
                hbox = QHBoxLayout()
                label = QLabel(k)
                edit = QComboBox()
                i = 0
                for s in config[k][0]:
                    edit.addItem(s)
                    if i == config[k][1]:
                        edit.setCurrentIndex(i)
                    i += 1
                hbox.addWidget(label)
                hbox.addWidget(edit)
                l.addLayout(hbox)
                ui[k] = (edit, label, hbox)
            elif t == type(dict()):
                gbox = QGroupBox()
                gbox.setTitle(k)
                ui[k] = {"gbox": gbox}
                l2 = self._parseDict(config[k], ui[k])
                ui[k]["layout"] = l2
                gbox.setLayout(l2)
                l.addWidget(gbox)
        return l

    def _parseConfig(self, config, ui):
        l = QVBoxLayout()
        for k in config:
            t = type(k[1])
            if t == type(int()):
                hbox = QHBoxLayout()
                label = QLabel(k[0])
                edit = QLineEdit(str(k[1]))
                val = QIntValidator(self)
                edit.setValidator(val)
                hbox.addWidget(label)
                hbox.addWidget(edit)
                l.addLayout(hbox)
                ui[k[0]] = (edit, label, hbox, val)
            elif t == type(float()):
                hbox = QHBoxLayout()
                label = QLabel(k[0])
                edit = QLineEdit(str(k[1]))
                val = QDoubleValidator(self)
                edit.setValidator(val)
                hbox.addWidget(label)
                hbox.addWidget(edit)
                l.addLayout(hbox)
                ui[k[0]] = (edit, label, hbox, val)
            elif t == type(list()):
                hbox = QHBoxLayout()
                label = QLabel(k[0])
                edit = QComboBox()
                i = 0
                for s in k[1][0]:
                    edit.addItem(s)
                    if i == k[1][1]:
                        edit.setCurrentIndex(i)
                    i += 1
                hbox.addWidget(label)
                hbox.addWidget(edit)
                l.addLayout(hbox)
                ui[k[0]] = (edit, label, hbox)
            elif t == type(dict()):
                gbox = QGroupBox()
                gbox.setTitle(k[0])
                ui[k[0]] = {"gbox": gbox}
                l2 = self._parseDict(k[1], ui[k[0]])
                ui[k[0]]["layout"] = l2
                gbox.setLayout(l2)
                l.addWidget(gbox)
        return l

    def _getDict(self, config, ui):
        res = {}
        for k in config.keys():
            t = type(config[k])
            if t == type(int()):
                res[k] = int(ui[k][0].text())
            elif t == type(float()):
                res[k] = float(ui[k][0].text())
            elif t == type(list()):
                lst = []
                i = 0
                cur = 0
                while i < ui[k][0].count():
                    s = ui[k][0].itemText(i)
                    if s == ui[k][0].currentText():
                        cur = i
                    lst.append(s)
                    i += 1
                res[k] = [lst, cur]
            elif t == type(dict()):
                res[k] = self._getDict(config[k], ui[k])
        return res

    def _getData(self, config, ui):
        res = []
        for k in config:
            t = type(k[1])
            if t == type(int()):
                res.append([k[0], int(ui[k[0]][0].text())])
            elif t == type(float()):
                res.append([k[0], float(ui[k[0]][0].text())])
            elif t == type(list()):
                lst = []
                i = 0
                cur = 0
                while i < ui[k[0]][0].count():
                    s = ui[k[0]][0].itemText(i)
                    if s == ui[k[0]][0].currentText():
                        cur = i
                    lst.append(s)
                    i += 1
                res.append([k[0], [lst, cur]])
            elif t == type(dict()):
                res.append([k[0], self._getDict(k[1], ui[k[0]])])
        if self.replication_checkbox:
            res.append([
                "replication_allowed",
                str(self.replication_checkbox.isChecked())
            ])
        if self.segmentation_checkbox:
            res.append([
                "assignInSegments",
                str(self.segmentation_checkbox.isChecked())
            ])
        return res

    def OK(self):
        self.data = self._getData(self.data, self.ui)
        self.accept()

    def Cancel(self):
        self.reject()
Exemple #39
0
class GroupParameterWidget(GenericParameterWidget):
    """Widget class for List parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A GroupParameter object.
        :type parameter: GroupParameter

        """
        super(GroupParameterWidget, self).__init__(parameter, parent)

        # Get the parameter label and use its value as the checkbox text
        label_item = self.input_layout.itemAt(0)
        label_widget = label_item.widget()
        text = label_widget.text()
        self._enable_check_box = QCheckBox(text)
        # Tooltips
        self.setToolTip('Tick here to enable ' + self._parameter.name)

        # add all widget in the group
        self._group_layout = QVBoxLayout()
        self._group_layout.setSpacing(0)

        if not self._parameter.is_required:
            self.input_layout.insertWidget(0, self._enable_check_box)
            # now we don't need the parameter label anymore so chuck it
            self.input_layout.removeItem(label_item)
            # Make the sub group appear indented
            self._group_layout.setContentsMargins(20, 0, 0, 0)
        else:
            self._parameter.enable_parameter = True

        self.main_layout.addLayout(self._group_layout)

        # Why are we doing imports here? TS
        from qt_widgets.parameter_container import ParameterContainer

        self.param_container = ParameterContainer(
            parameters=self._parameter.value)
        self.param_container.setup_ui(must_scroll=parameter.must_scroll)

        # add handlers
        # noinspection PyUnresolvedReferences
        self._enable_check_box.stateChanged.connect(
            self.on_enable_checkbox_changed)
        self._enable_check_box.setChecked(self._parameter.enable_parameter)
        self.on_enable_checkbox_changed(self._parameter.enable_parameter)

        self._group_layout.addWidget(self.param_container)

    def on_enable_checkbox_changed(self, state):
        if state:
            self.param_container.show()
        else:
            self.param_container.hide()
        self._parameter.enable_parameter = state

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A ListParameter from the current state of widget

        """
        if self._parameter.enable_parameter:
            parameters = self.param_container.get_parameters()
            self._parameter.value = parameters
            self._parameter.validate()

        return self._parameter
Exemple #40
0
    def insertLayout(self):
        def createPixmapWidget(self, parent, iconName):
            w = QLabel(parent)
            parent.layout().addWidget(w)
            w.setFixedSize(16, 16)
            w.hide()
            if os.path.exists(iconName):
                w.setPixmap(QPixmap(iconName))
            return w

        self.setLayout(QVBoxLayout())
        self.layout().setMargin(2)

        self.warning_bar = gui.widgetBox(self, orientation="horizontal",
                                         margin=0, spacing=0)
        self.warning_icon = gui.widgetLabel(self.warning_bar, "")
        self.warning_label = gui.widgetLabel(self.warning_bar, "")
        self.warning_label.setStyleSheet("padding-top: 5px")
        self.warning_bar.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum)
        gui.rubber(self.warning_bar)
        self.warning_bar.setVisible(False)

        self.topWidgetPart = gui.widgetBox(self,
                                           orientation="horizontal", margin=0)
        self.leftWidgetPart = gui.widgetBox(self.topWidgetPart,
                                            orientation="vertical", margin=0)
        if self.want_main_area:
            self.leftWidgetPart.setSizePolicy(
                QSizePolicy(QSizePolicy.Fixed, QSizePolicy.MinimumExpanding))
            self.leftWidgetPart.updateGeometry()
            self.mainArea = gui.widgetBox(self.topWidgetPart,
                                          orientation="vertical",
                                          sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                                 QSizePolicy.Expanding),
                                          margin=0)
            self.mainArea.layout().setMargin(4)
            self.mainArea.updateGeometry()

        if self.want_control_area:
            self.controlArea = gui.widgetBox(self.leftWidgetPart,
                                             orientation="vertical", margin=4)

        if self.want_graph and self.show_save_graph:
            graphButtonBackground = gui.widgetBox(self.leftWidgetPart,
                                                  orientation="horizontal", margin=4)
            self.graphButton = gui.button(graphButtonBackground,
                                          self, "&Save Graph")
            self.graphButton.setAutoDefault(0)

        if self.want_status_bar:
            self.widgetStatusArea = QFrame(self)
            self.statusBarIconArea = QFrame(self)
            self.widgetStatusBar = QStatusBar(self)

            self.layout().addWidget(self.widgetStatusArea)

            self.widgetStatusArea.setLayout(QHBoxLayout(self.widgetStatusArea))
            self.widgetStatusArea.layout().addWidget(self.statusBarIconArea)
            self.widgetStatusArea.layout().addWidget(self.widgetStatusBar)
            self.widgetStatusArea.layout().setMargin(0)
            self.widgetStatusArea.setFrameShape(QFrame.StyledPanel)

            self.statusBarIconArea.setLayout(QHBoxLayout())
            self.widgetStatusBar.setSizeGripEnabled(0)

            self.statusBarIconArea.hide()

            self._warningWidget = createPixmapWidget(
                self.statusBarIconArea,
                gui.resource_filename("icons/triangle-orange.png"))
            self._errorWidget = createPixmapWidget(
                self.statusBarIconArea,
                gui.resource_filename("icons/triangle-red.png"))
Exemple #41
0
class search(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.heditor = parent
        #Open a new instance for I/O
        self.file = self.heditor.node.open()
        self.__size = self.heditor.node.size()
        #Last search type tag [0:hex|1:characters]
        self.lastSearchType = 0
        #Init Thread
        self.search_th = searchThread(self.file)
        #tupple of searched patterns [key:hex(pattern)|value:offsetslist]
        self.searchedPatterns = {}
        self.connect(self.search_th, SIGNAL("searchDone()"), self.searchdone)
        self.connect(self.search_th, SIGNAL("currentPos"), self.updatePBar)

    def initShape(self):
        self.vbox = QVBoxLayout()
        self.createValues()
        self.createOptions()
        self.createResults()
        self.createSearching()
        self.createButtons()
        #fill
        fill = QWidget()
        self.vbox.addWidget(fill)

        self.setLayout(self.vbox)

    def createValues(self):
        self.wvalues = QWidget()
        self.valuesgrid = QGridLayout()

        ltype = QLabel("Type:")
        self.type = QComboBox()
        self.type.addItem("Hexadecimal")
        self.type.addItem("Character(s)")
        self.type.addItem("Unicode")

        lneedle = QLabel("Pattern:")
        self.needle = QLineEdit()

        lwild = QLabel("Wildcard:")
        self.wildcard = QLineEdit()

        lstart = QLabel("Start: ")
        self.start = QFFSpinBox(self)
        self.start.setMaximum(self.heditor.filesize)
        self.start.setValue(0)

        self.valuesgrid.addWidget(ltype, 0, 0)
        self.valuesgrid.addWidget(self.type, 0, 1)

        self.valuesgrid.addWidget(lneedle, 1, 0)
        self.valuesgrid.addWidget(self.needle, 1, 1)

        self.valuesgrid.addWidget(lwild, 2, 0)
        self.valuesgrid.addWidget(self.wildcard, 2, 1)

        self.valuesgrid.addWidget(lstart, 3, 0)
        self.valuesgrid.addWidget(self.start, 3, 1)

        self.wvalues.setLayout(self.valuesgrid)
        self.vbox.addWidget(self.wvalues)

    def createOptions(self):
        self.woptions = QWidget()
        self.optgrid = QGridLayout()

        lopt = QLabel("Options:")

        self.fromcursor = QCheckBox("From cursor")
        self.back = QCheckBox("Backwards")

        self.optgrid.addWidget(lopt, 0, 0)
        self.optgrid.addWidget(self.fromcursor, 0, 1)

        self.woptions.setLayout(self.optgrid)
        self.vbox.addWidget(self.woptions)

    def createResults(self):
        self.wresults = QWidget()
        self.resgrid = QGridLayout()

        self.resultab = resultab(self)
        self.resgrid.addWidget(self.resultab, 0, 0)

        self.wresults.setLayout(self.resgrid)
        self.vbox.addWidget(self.wresults)

    def createSearching(self):
        self.wsing = QWidget()
        self.singgrid = QGridLayout()

        self.searchlabel = QLabel("Launch search")
        self.singgrid.addWidget(self.searchlabel, 0, 0)

        self.wsing.setLayout(self.singgrid)
        self.vbox.addWidget(self.wsing)

    def createButtons(self):
        self.applyB = QPushButton("Apply")
        self.connect(self.applyB, SIGNAL('clicked()'), self.searchit)

        self.vbox.addWidget(self.applyB)

    def toHex(self, str, wildcard=None):
        HEXCHAR = "0123456789abcdefABCDEF"
        hexStr = ""
        evenhex = ""
        for i in range(len(str)):
            if str[i] in HEXCHAR:
                if len(evenhex) == 1:
                    hexStr += chr(int(evenhex + str[i], 16))
                    evenhex = ""
                else:
                    evenhex = str[i]
            elif wildcard != None and str[i] == wildcard:
                if evenhex == "":
                    hexStr += wildcard
                else:
                    raise ValueError, "argument 'str' must be an even number of char"
            else:
                raise ValueError, "argument 'str' contains not valid characters"
        if len(evenhex) != 0:
            raise ValueError, "argument 'str' must be an even number of char"
        return hexStr

    def toUnicode(self, string):
        res = string.encode("hex")
        unires = ""
        cp = 0
        while cp < len(res):
            unires += res[cp]
            if (cp - 1) % 2 == 0 and cp != 0 and cp + 1 != len(res):
                unires += "00"
            cp = cp + 1
        return unires.decode("hex")


#####################
#     Search IT     #
#####################

    def searchit(self):
        if self.needle.text() != "":
            needle = self.needle.text()
            err = False
            #check needle
            type = self.type.currentText()
            if type == "Hexadecimal":
                self.lastSearchType = 0
                try:
                    pattern = self.toHex(str(needle))
                except ValueError:
                    err = True
                    msg = MessageBoxError(self.heditor,
                                          "Required Hexadecimal pattern")
                    msg.exec_()
                    return
            elif type == "Character(s)":
                self.lastSearchType = 1
                pattern = str(needle)
            elif type == "Unicode":
                self.lastSearchType = 2
                pattern = self.toUnicode(str(needle))

            if not err:
                opt_fromcursor = self.fromcursor.isChecked()
                spinstart = self.start.value()
                wild = self.wildcard.text()
                # XXX
                if opt_fromcursor:
                    start = self.heditor.selection.offset
                elif spinstart > 0:
                    start = spinstart
                else:
                    start = 0
                    self.search_th.setData(pattern, start, wild)
                    self.searchlabel.setText("Searching ...")

                    self.search_th.start()

    def searchdone(self):
        #            print "Results found: ", nres
        res = self.search_th.getResults()

        if len(res) > 0:
            label = "%2.d" % len(res)
            label += " matchs"
            self.searchlabel.setText(label)
            self.resultab.buttonCloseTab.setEnabled(True)
            self.resultab.addResults(res)
            msg = MessageBoxInfo(self.heditor, label)
            msg.exec_()
        else:
            msg = MessageBoxError(self.heditor, "No results founded")
            msg.exec_()

    def updatePBar(self, pos):
        rpos = self.__size - pos
        rsize = self.__size - self.search_th.startOffset
        self.searchlabel.setText(str((rsize - rpos) * 100 / rsize) + " %")

    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.searchit()
Exemple #42
0
    def __init__(self, parent, app):
        super(QWidget, self).__init__()

        layout1 = QHBoxLayout()
        layout2 = QVBoxLayout()

        layout1.addStretch()
        layout1.addLayout(layout2)
        layout1.addStretch()

        label = QLabel(self)
        label.setText(
            "Simple Project: <b>Display Environment Measurements on LCD</b>. Simply displays all measured values on LCD. Sources in all programming languages can be found <a href=\"http://www.tinkerforge.com/en/doc/Kits/WeatherStation/WeatherStation.html#display-environment-measurements-on-lcd\">here</a>.<br>"
        )
        label.setTextFormat(Qt.RichText)
        label.setTextInteractionFlags(Qt.TextBrowserInteraction)
        label.setOpenExternalLinks(True)
        label.setWordWrap(True)
        label.setAlignment(Qt.AlignJustify)

        layout2.addSpacing(10)
        layout2.addWidget(label)
        layout2.addSpacing(10)

        self.lcdwidget = LCDWidget(self, app)

        layout2.addWidget(self.lcdwidget)
        layout2.addStretch()

        self.setLayout(layout1)

        self.qtcb_update_illuminance.connect(self.update_illuminance_data_slot)
        self.qtcb_update_air_pressure.connect(
            self.update_air_pressure_data_slot)
        self.qtcb_update_temperature.connect(self.update_temperature_data_slot)
        self.qtcb_update_humidity.connect(self.update_humidity_data_slot)
        self.qtcb_button_pressed.connect(self.button_pressed_slot)
Exemple #43
0
    def init_MeshGenTab(self):
        vbox = QVBoxLayout()
        vbox.setSpacing(10)

        self.text_mesh_in = QLabel('input data:')
        self.text_mesh_data = QLabel('mesh data:')
        vbox.addWidget(QLabel())
        vbox.addWidget(self.text_mesh_in)
        vbox.addWidget(self.text_mesh_data)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        vbox.addWidget(hr)

        vbox1 = QVBoxLayout()
        btn_meshload = QPushButton("Load SEG", self)
        btn_meshload.clicked.connect(self.loadSeg)
        btn_meshsave = QPushButton("Save MESH", self)
        btn_meshsave.clicked.connect(self.saveMesh)
        text_mesh_output = QLabel('format:')

        combo_sm = QComboBox(self)
        combo_sm.activated[str].connect(self.changeOut)
        supp_write = []
        for k, v in supported_capabilities.iteritems():
            if 'w' in v:
                supp_write.append(k)

        combo_sm.addItems(supp_write)
        combo_sm.setCurrentIndex(supp_write.index('vtk'))

        vbox1.addWidget(btn_meshload)
        vbox1.addWidget(btn_meshsave)
        hbox1 = QHBoxLayout()
        hbox1.addWidget(text_mesh_output)
        hbox1.addWidget(combo_sm)
        vbox1.addLayout(hbox1)
        vbox1.addStretch(1)

        vbox2 = QVBoxLayout()
        btn_meshgener = QPushButton("Generate", self)
        btn_meshgener.clicked.connect(self.generMesh)
        text_mesh_mesh = QLabel('generator:')

        combo_mg = QComboBox(self)
        combo_mg.activated[str].connect(self.changeMesh)
        self.mesh_generator = 'marching cubes'
        keys = mesh_generators.keys()
        keys.sort()
        combo_mg.addItems(keys)
        combo_mg.setCurrentIndex(keys.index(self.mesh_generator))

        vbox2.addWidget(btn_meshgener)
        hbox1 = QHBoxLayout()
        hbox1.addWidget(text_mesh_mesh)
        hbox1.addWidget(combo_mg)
        vbox2.addLayout(hbox1)
        #vbox2.addStretch(1)
        vbox2.addWidget(QLabel())

        btn_meshsmooth = QPushButton("Smooth", self)
        btn_meshsmooth.clicked.connect(self.smoothMesh)
        text_mesh_smooth = QLabel('method:')

        combo_out = QComboBox(self)
        combo_out.activated[str].connect(self.changeSmoothMethod)
        keys = smooth_methods.keys()
        combo_out.addItems(keys)
        combo_out.setCurrentIndex(keys.index('taubin'))

        vbox2.addWidget(btn_meshsmooth)
        hbox1 = QHBoxLayout()
        hbox1.addWidget(text_mesh_smooth)
        hbox1.addWidget(combo_out)
        vbox2.addLayout(hbox1)
        vbox2.addStretch(1)

        vbox3 = QVBoxLayout()
        btn_meshview = QPushButton("Mesh preview", self)
        btn_meshview.clicked.connect(self.viewMesh)
        vbox3.addWidget(btn_meshview)
        vbox3.addStretch(1)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(vbox1)
        hbox.addStretch(1)
        hbox.addLayout(vbox2)
        hbox.addStretch(1)
        hbox.addLayout(vbox3)
        hbox.addStretch(1)

        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        return vbox
Exemple #44
0
 def __init__(self, parent=None):
     super(pngDisplay, self).__init__(parent)
     #self.profiler = cProfile.Profile()
     # create the label that displays the image - cribbing from the Image
     # Viewer example in the Qt docs.
     self.imLabel = QLabel()
     self.imLabel.setBackgroundRole(QPalette.Base)
     self.imLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
     self.imLabel.setScaledContents(True)
     # Create a gray field to use when no png is available
     self.defaultPM = QPixmap(700,900)
     self.defaultPM.fill(QColor("gray"))
     # Create a scroll area within which to display our imLabel, this
     # enables the creation of horizontal and vertical scroll bars, when
     # the imLabel exceeds the size of the scroll area.
     self.scarea = QScrollArea()
     # The following two lines make sure that page up/dn gets through
     # the scrollarea widget and up to us.
     self.setFocusPolicy(Qt.ClickFocus)
     self.scarea.setFocusProxy(self)
     self.scarea.setBackgroundRole(QPalette.Dark)
     #self.scarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
     #self.scarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
     self.scarea.setWidget(self.imLabel)
     # create the text label that will have the page number in it
     self.txLabel = QLabel(u"No image")
     self.txLabel.setAlignment(Qt.AlignBottom | Qt.AlignHCenter)
     self.txLabel.setFrameStyle(QFrame.Sunken | QFrame.StyledPanel)
     # Create a spinbox to set the zoom from 15 to 200 with a label:
     # (originally a slider, hence the name)
     self.minZoom = 0.15
     self.maxZoom = 2.00
     self.zlider = QSpinBox()
     self.zlider.setRange(int(100*self.minZoom),int(100*self.maxZoom))
     # connect the value change signal to a slot to handle it
     self.connect(self.zlider, SIGNAL("valueChanged(int)"), self.newZoomFactor)
     # create the to-width and to-height zoom buttons
     zoomWidthButton = QPushButton(u'to Width')
     self.connect(zoomWidthButton, SIGNAL("clicked()"), self.zoomToWidth)
     zoomHeightButton = QPushButton(u'to Height')
     self.connect(zoomHeightButton, SIGNAL("clicked()"), self.zoomToHeight)
     # Make an hbox to contain the spinbox and two pushbuttons, with
     # stretch on left and right to center the group.
     zlabel = QLabel(
         u'&Zoom ' + str(self.zlider.minimum())
         + '-' + str(self.zlider.maximum()) + '%')
     zlabel.setBuddy(self.zlider)
     zhbox = QHBoxLayout()
     zhbox.addStretch(1)
     zhbox.addWidget(zlabel,0,Qt.AlignLeft)
     zhbox.addWidget(self.zlider,0)
     zhbox.addStretch(1)
     zhbox.addWidget(zoomWidthButton)
     zhbox.addWidget(zoomHeightButton)
     zhbox.addStretch(1)
     # With all the pieces in hand, create our layout basically a
     # vertical stack: scroll area, label, slider box.
     vbox = QVBoxLayout()
     # the image gets a high stretch and default alignment, the text
     # label hugs the bottom and doesn't stretch at all.
     vbox.addWidget(self.txLabel,0,Qt.AlignBottom)
     vbox.addWidget(self.scarea,10)
     vbox.addLayout(zhbox,0)
     self.setLayout(vbox)
     # Initialize assuming no book is open.
     self.ready = False # nothing to display
     # Recover the last-set zoom factor from the settings object, default 1.0
     qv = IMC.settings.value("pngs/zoomFactor",QVariant(1.0))
     self.zoomFactor = qv.toFloat()[0]
     # The following causes entry into newZoomFactor, below, which tests
     # self.ready, hence the latter has to be assigned-to first.
     self.zlider.setValue(int(self.zoomFactor*100))
     self.clear()
Exemple #45
0
    def init_ReaderTab(self):
        vbox = QVBoxLayout()
        vbox.setSpacing(10)

        self.text_dcm_dir = QLabel('DICOM dir:')
        self.text_dcm_data = QLabel('DICOM data:')
        vbox.addWidget(QLabel())
        vbox.addWidget(self.text_dcm_dir)
        vbox.addWidget(self.text_dcm_data)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        vbox.addWidget(hr)

        vbox1 = QVBoxLayout()
        btn_dcmdir = QPushButton("Load DICOM", self)
        btn_dcmdir.clicked.connect(self.loadDcmDir)
        btn_dcmsave = QPushButton("Save DCM", self)
        btn_dcmsave.clicked.connect(self.saveDcm)
        vbox1.addWidget(btn_dcmdir)
        vbox1.addWidget(btn_dcmsave)
        vbox1.addStretch(1)

        vbox2 = QVBoxLayout()
        btn_dcmred = QPushButton("Reduce", self)
        btn_dcmred.clicked.connect(self.reduceDcm)
        btn_dcmcrop = QPushButton("Crop", self)
        btn_dcmcrop.clicked.connect(self.cropDcm)
        vbox2.addWidget(btn_dcmred)
        vbox2.addWidget(btn_dcmcrop)
        vbox2.addStretch(1)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(vbox1)
        hbox.addStretch(1)
        hbox.addLayout(vbox2)
        hbox.addStretch(1)

        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        return vbox
Exemple #46
0
    def initUI(self):
        import os.path as op
        path_to_script = op.dirname(os.path.abspath(__file__))

        cw = QWidget()
        self.setCentralWidget(cw)
        vbox = QVBoxLayout()
        vbox.setSpacing(10)

        # status bar
        self.statusBar().showMessage('Ready')

        # info panel
        font_label = QFont()
        font_label.setBold(True)
        font_info = QFont()
        font_info.setItalic(True)
        font_info.setPixelSize(10)

        dicom2fem_title = QLabel('DICOM2FEM')
        info = QLabel('Version: 0.9\n\n' + 'Developed by:\n' +
                      'University of West Bohemia\n' +
                      'Faculty of Applied Sciences\n' +
                      QString.fromUtf8('V. Lukeš - 2014') +
                      '\n\nBased on PYSEG_BASE project')
        info.setFont(font_info)
        dicom2fem_title.setFont(font_label)
        dicom2fem_logo = QLabel()
        logopath = os.path.join(path_to_script, "../src/brain.png")
        logo = QPixmap(logopath)
        dicom2fem_logo.setPixmap(logo)
        vbox1 = QVBoxLayout()
        vbox1.addWidget(dicom2fem_title)
        vbox1.addWidget(info)
        vbox1.addStretch(1)

        vbox2 = QVBoxLayout()
        vbox2.addWidget(dicom2fem_logo)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(vbox1)
        hbox.addStretch(1)
        hbox.addLayout(vbox2)
        hbox.addStretch(1)
        vbox.addLayout(hbox)

        tabs = QTabWidget()
        tab1 = QWidget()
        tab2 = QWidget()
        tab3 = QWidget()

        tab1.setLayout(self.init_ReaderTab())
        tab2.setLayout(self.init_SegmentationTab())
        tab3.setLayout(self.init_MeshGenTab())
        tabs.addTab(tab1, "DICOM Reader")
        tabs.addTab(tab2, "Segmentation")
        tabs.addTab(tab3, "Mesh generator")

        vbox.addWidget(tabs)

        # quit
        btn_quit = QPushButton("Quit", self)
        btn_quit.clicked.connect(self.quit)
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(btn_quit)
        hbox.addStretch(1)

        vbox.addLayout(hbox)

        cw.setLayout(vbox)
        self.setWindowTitle('DICOM2FEM')
        self.show()
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
       # self.
        self.central = QWidget(self)
        self.control_side=QVBoxLayout()
        self.textbox = QTextEdit(self.central)
        self.textbox.setFont(TEXT_FONT)
        self.textbox.setMinimumSize(50, 50)
        self.text_update.connect(self.append_text)
        sys.stdout = self
        print("Camera number %u" % camera_num)
        self.logic = 0
        self.value = 1
        self.V_Logic=0
        self.ImageName=""
        
       
        
        #LoginForm.center(self)
        
        #PickName.valueChanged.connect(print(PickName))
            #print(PickName)



        if DISP_SCALE > 1:
            print("Display scale %u:1" % DISP_SCALE)

        self.vlayout = QVBoxLayout()        # Window layout
        self.displays = QHBoxLayout()
        self.control = QVBoxLayout()
        self.textboxs= QHBoxLayout()
        self.co2= QVBoxLayout()
        self.buttons =QVBoxLayout()
        self.disp = ImageWidget(self)
        self.controls= QTabWidget()
      

        self.vlayout.addLayout(self.displays)
        self.displays.addWidget(self.disp)
        self.label = QLabel(self)
       # self.displays.addLayout(self.control)
        self.displays.addLayout(self.textboxs)
        self.vlayout.addWidget(self.label)
        self.vlayout.addWidget(self.textbox)
        self.central.setLayout(self.vlayout)
        self.setCentralWidget(self.central)
        self.central.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.displays.addLayout(self.control_side)
        #self.control_side.addWidget(self.controls)
        self.control_side.addLayout(self.control)

 
 
        #widget

        self.Pictures=QWidget()
        self.Pictures.layout=QVBoxLayout()
        self.Pictures.setLayout(self.Pictures.layout)
        
        self.Videos=QWidget()
        self.Videos.layout=QVBoxLayout()
        self.Videos.setLayout(self.Videos.layout)
  
        
        self.controls.addTab(self.Pictures,"Multimedia")
        #self.controls.addTab(self.Videos,"Videos")

        #carbon
        self.control.addLayout(self.co2)      
                # C02(+)
        self.btnco2p= QPushButton('CO2+')
        self.btnco2p.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        #self.co2.addWidget(self.btnco2p)
                #Labels
        self.setco2=QLabel("mmHg")
        #self.co2.addWidget(self.setco2)
        self.setco2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.setco2.setAlignment(Qt.AlignCenter)
   
                # CO2(-)
        self.btnco2m= QPushButton('CO2-')
        #self.co2.addWidget(self.btnco2m)
        self.btnco2m.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
      
       
        self.mainMenu = self.menuBar()      # Menu bar
        exitAction = QAction('&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(self.close)
        self.fileMenu = self.mainMenu.addMenu('&File')
        self.fileMenu.addAction(exitAction)
        
        #spacers
        self.verticalSpacer = QSpacerItem(150, 100,QSizePolicy.Expanding)
        self.verticalSpacerb = QSpacerItem(70, 50,QSizePolicy.Expanding)
        #sizes
        size = QSize(60, 60)
        # Camera
        self.btnc= QPushButton('Capture')
        self.btnc.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.Pictures.layout.addLayout(self.buttons)
        self.buttons.addWidget(self.btnc)
        self.buttons.addSpacerItem(self.verticalSpacer)
        self.btnc.setIcon(QIcon('camera.png'))
        #self.btnc.setStyleSheet("border-radius : 50;")
        self.btnc.setIconSize(size)


        #Video
        self.btnr= QPushButton('Record')
        self.btnr.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.Pictures.layout.addWidget(self.btnr)
        self.Pictures.layout.addSpacerItem(self.verticalSpacerb)
        self.btnr.setIcon(QIcon('video.png'))
        self.btnr.setIconSize(size)
        
        self.btns= QPushButton('Stop')
        self.btns.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.Pictures.layout.addWidget(self.btns)
        self.btns.setIcon(QIcon('stop.png'))
        self.btns.setIconSize(size)
        self.Pictures.layout.addSpacerItem(self.verticalSpacerb)
        
        self.btnc.clicked.connect(self.CaptureClicked)# Capture Photo trigger
        self.btnr.clicked.connect(self.RecordingClicked) # Recording Video trigger
        self.btns.clicked.connect(self.StopClicked)#Stop recording Trigger
Exemple #48
0
    def init_SegmentationTab(self):
        vbox = QVBoxLayout()
        vbox.setSpacing(10)

        self.text_seg_in = QLabel('input data:')
        self.text_seg_data = QLabel('segment. data:')
        vbox.addWidget(QLabel())
        vbox.addWidget(self.text_seg_in)
        vbox.addWidget(self.text_seg_data)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        vbox.addWidget(hr)

        vbox1 = QVBoxLayout()
        btn_segload = QPushButton("Load DCM", self)
        btn_segload.clicked.connect(self.loadDcm)
        btn_segsave = QPushButton("Save SEG", self)
        btn_segsave.clicked.connect(self.saveSeg)
        vbox1.addWidget(btn_segload)
        vbox1.addWidget(btn_segsave)
        vbox1.addStretch(1)

        vbox2 = QVBoxLayout()
        btn_maskreg = QPushButton("Mask region", self)
        btn_maskreg.clicked.connect(self.maskRegion)
        btn_segauto = QPushButton("Automatic seg.", self)
        btn_segauto.clicked.connect(self.autoSeg)
        btn_segman = QPushButton("Manual seg.", self)
        btn_segman.clicked.connect(self.manualSeg)
        vbox2.addWidget(btn_maskreg)
        vbox2.addWidget(btn_segauto)
        vbox2.addWidget(btn_segman)
        vbox2.addStretch(1)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(vbox1)
        hbox.addStretch(1)
        hbox.addLayout(vbox2)
        hbox.addStretch(1)

        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        return vbox
Exemple #49
0
    def initUI(self):
        self.setWindowTitle(u"分类显示")

        layer_label = QLabel(u"选择图层:")
        self.layer_combo = QComboBox()
        layers_name = getAllLayerName(self.iface)
        self.layer_combo.addItems(layers_name)
        self.layer = getLayerByName(self.layer_combo.currentText(), self.iface)
        self.connect(self.layer_combo, SIGNAL('currentIndexChanged(int)'),
                     self.layerListener)

        field_label = QLabel(u"选择字段:")
        self.field_combo = QComboBox()
        if self.layer != None:
            fields_list = []
            for field in self.layer.pendingFields():
                fields_list.append(field.name().strip())
            self.field_combo.addItems(fields_list)

        ok = QPushButton(u"确定")
        cancel = QPushButton(u"取消")
        self.connect(ok, SIGNAL('clicked()'), self.run)
        self.connect(cancel, SIGNAL('clicked()'), self.accept)

        # 选择图层、字段Widget
        source_grid = QGridLayout()
        source_grid.setSpacing(10)
        source_grid.addWidget(layer_label, 0, 1)
        source_grid.addWidget(self.layer_combo, 0, 2)
        source_grid.addWidget(field_label, 1, 1)
        source_grid.addWidget(self.field_combo, 1, 2)
        source_widget = QWidget()
        source_widget.setLayout(source_grid)

        # 参数设置窗口(带滚动条)
        self.setting_Widget = QWidget()
        self.setting_Widget.setMinimumSize(380, 800)

        self.scroll_vbox = QVBoxLayout()
        self.scroll_vbox.setSpacing(15)

        self.setting_vbox = QVBoxLayout()
        self.setting_vbox.setSpacing(5)
        range_widget = self.createARange()
        self.setting_vbox.addWidget(range_widget)

        self.add_range_btn = QPushButton(u"添加")
        self.connect(self.add_range_btn, SIGNAL("clicked()"),
                     self.add_range_box)

        self.scroll_vbox.addLayout(self.setting_vbox)
        self.scroll_vbox.addWidget(self.add_range_btn)
        self.scroll_vbox.addStretch(1)

        self.setting_Widget.setLayout(self.scroll_vbox)

        self.scroll = QScrollArea()
        self.scroll.setWidget(self.setting_Widget)
        self.scroll.setAutoFillBackground(True)
        self.scroll.setWidgetResizable(True)

        # 确定/取消 按钮 Widget
        btn_hbox = QHBoxLayout()
        btn_hbox.setSpacing(15)
        btn_hbox.addStretch(1)
        btn_hbox.addWidget(ok)
        btn_hbox.addWidget(cancel)
        btn_hbox.addStretch(1)
        btn_widget = QWidget()
        btn_widget.setLayout(btn_hbox)

        vbox = QVBoxLayout()
        vbox.setSpacing(15)
        vbox.addWidget(source_widget)
        vbox.addWidget(self.scroll)
        vbox.addWidget(btn_widget)

        self.setLayout(vbox)
        self.setFixedSize(430, 500)
Exemple #50
0
    def __init__(self, parent=None):
        super(SleepTimer, self).__init__(parent)
        self.forceSpinBoxWidget = global_vars.configuration.get("GENERAL").get(
            "sleeptimerdigitalspinbox")
        self.setStyleSheet(
            "SleepTimer {"
            "background-color: rgb(76, 76, 76);"
            "color: rgb(240, 240, 240);"
            "}"
            "QLabel {"
            "color: white;"
            "}"
            "QSpinBox {"
            "padding-right: 10px; /* make room for the arrows */"
            "border-width: 3;"
            "}"
            "QSpinBox::up-button {"
            "width: 26px;"
            "}"
            "QSpinBox::down-button {"
            "width: 26px;"
            "}")
        self.value = 0  # the value is calculated in self.active (calculated seconds in total)
        self.isActive = False

        if self.forceSpinBoxWidget:
            self.sb_hours = LeadingZeroSpinBox()
            self.sb_hours.setRange(0, 23)
            self.sb_hours.setAlignment(Qt.AlignCenter)
            self.sb_hours.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        else:
            self.sb_hours = QDeclarativeView()
            self.sb_hours.setSource(QUrl(os.path.join(cwd, 'sb_hours.qml')))
            self.sb_hours.setResizeMode(QDeclarativeView.SizeViewToRootObject)
            self.sb_hours.setStyleSheet("background:transparent;")
            self.sb_hours.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)

            self.sb_hours_obj = self.sb_hours.rootObject().findChild(
                QObject, "spinner")
            self.sb_hours_value = QDeclarativeProperty(
                self.sb_hours.rootObject().findChild(QDeclarativeItem,
                                                     name="spinner"),
                "currentIndex")

        if self.forceSpinBoxWidget:
            self.sb_minutes = LeadingZeroSpinBox()
            self.sb_minutes.setRange(0, 59)
            self.sb_minutes.setAlignment(Qt.AlignCenter)
            self.sb_minutes.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Expanding)
        else:
            self.sb_minutes = QDeclarativeView()
            self.sb_minutes.setSource(QUrl(os.path.join(cwd,
                                                        'sb_minutes.qml')))
            self.sb_minutes.setResizeMode(
                QDeclarativeView.SizeViewToRootObject)
            self.sb_minutes.setStyleSheet("background:transparent;")
            self.sb_minutes.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Expanding)

            self.sb_minutes_obj = self.sb_minutes.rootObject().findChild(
                QObject, "spinner")
            self.sb_minutes_value = QDeclarativeProperty(
                self.sb_minutes.rootObject().findChild(QDeclarativeItem,
                                                       name="spinner"),
                "currentIndex")

        tmpFont = QFont()
        tmpFont.setPointSize(18)
        self.lbl_hours = QLabel(QString("h"))
        self.lbl_hours.setFont(tmpFont)
        self.lbl_minutes = QLabel(QString("min"))
        self.lbl_minutes.setFont(tmpFont)

        # Load QML Widget Bomb
        self.bomb = QDeclarativeView()
        self.bomb.setSource(QUrl(os.path.join(cwd, 'timebomb.qml')))
        self.bomb.setResizeMode(QDeclarativeView.SizeViewToRootObject)
        #self.bomb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.bomb.setStyleSheet("background:transparent;")
        self.bomb_text = QDeclarativeProperty(
            self.bomb.rootObject().findChild(QDeclarativeItem,
                                             name="counter_text"), "text")

        #setup layouts
        tmpLayout = QHBoxLayout()
        tmpLayout.addSpacerItem(QSpacerItem(40, 40, QSizePolicy.Expanding))
        tmpLayout.addWidget(self.sb_hours)
        tmpLayout.addWidget(self.lbl_hours)
        tmpLayout.addWidget(self.sb_minutes)
        tmpLayout.addWidget(self.lbl_minutes)
        tmpLayout.addSpacerItem(QSpacerItem(40, 40, QSizePolicy.Expanding))

        tmp2Layout = QVBoxLayout()
        tmp2Layout.addLayout(tmpLayout)
        tmp2Layout.addWidget(self.bomb)
        tmp2Layout.addSpacerItem(QSpacerItem(40, 40, QSizePolicy.Expanding))

        self.setLayout(tmp2Layout)
        self.blockValueSignal = False  # if this is true, valueChanged signal is not evaluated
        if self.forceSpinBoxWidget:
            self.sb_hours.valueChanged.connect(self.onValueChanged)
            self.sb_minutes.valueChanged.connect(self.onValueChanged)
        else:
            self.sb_hours_obj.currentIndexChanged.connect(self.onValueChanged)
            self.sb_minutes_obj.currentIndexChanged.connect(
                self.onValueChanged)

        # setup Timer which is started as soon as a value is changed in any of the spinboxes
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.setInterval(
            2000)  # 2 seconds until timer starts automatically
        self.connect(self.timer, SIGNAL("timeout()"), self.activate)

        #setup Timer which is a second-timer. It is startet with the self.timer (see self.active)
        self.countDown = QTimer()
        self.countDown.setInterval(1000)  #sec
        self.connect(self.countDown, SIGNAL("timeout()"), self.check)
Exemple #51
0
class ImageView2DDockWidget(QWidget):
    onDockButtonClicked = pyqtSignal()
    onMaxButtonClicked = pyqtSignal()
    onMinButtonClicked = pyqtSignal()

    def __init__(self, graphicsView):
        QWidget.__init__(self)

        self.graphicsView = graphicsView
        self._isDocked = True
        self._isMaximized = False
        
        self.setContentsMargins(0, 0, 0, 0)
        
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)
        
        self.windowForGraphicsView = ImageView2DFloatingWindow()
        self.windowForGraphicsView.layout = QVBoxLayout()
        self.windowForGraphicsView.layout.setContentsMargins(0, 0, 0, 0)
        self.windowForGraphicsView.setLayout(self.windowForGraphicsView.layout)
        
        self.windowForGraphicsView.onCloseClick.connect(self.onDockButton)
    
        self.addGraphicsView()
    
    def connectHud(self):
        if hasattr(self.graphicsView, '_hud'):
            self.graphicsView._hud.dockButtonClicked.connect(self.onDockButton)
            self.graphicsView._hud.maximizeButtonClicked.connect(self.onMaxButton)

    def onMaxButton(self):
        if self._isMaximized:
            self.onMinButtonClicked.emit()
            self.minimizeView()
        else:
            self.onMaxButtonClicked.emit()
            self.maximizeView()
        
    def onDockButton(self):
        self.onDockButtonClicked.emit()
        
    def addGraphicsView(self):
        self.layout.addWidget(self.graphicsView)
        
    def removeGraphicsView(self):
        self.layout.removeWidget(self.graphicsView)
        
    def undockView(self):
        self._isDocked = False
        if hasattr(self.graphicsView, '_hud'):
            self.graphicsView._hud.dockButton.setIcon('dock')
            self.graphicsView._hud.maxButton.setEnabled(False)
        
        self.removeGraphicsView()
        self.windowForGraphicsView.layout.addWidget(self.graphicsView)
        self.windowForGraphicsView.showMaximized() #supersize me
        self.windowForGraphicsView.setWindowTitle("ilastik")
        self.windowForGraphicsView.raise_()
    
    def dockView(self):
        self._isDocked = True
        if hasattr(self.graphicsView, '_hud'):
            self.graphicsView._hud.dockButton.setIcon('undock')
            self.graphicsView._hud.maxButton.setEnabled(True)
        
        self.windowForGraphicsView.layout.removeWidget(self.graphicsView)
        self.windowForGraphicsView.hide()
        self.addGraphicsView()
        
    def maximizeView(self):
        self._isMaximized = True
        if hasattr(self.graphicsView, '_hud'):
            self.graphicsView._hud.maxButton.setIcon('minimize')
        
    def minimizeView(self):
        self._isMaximized = False
        if hasattr(self.graphicsView, '_hud'):
            self.graphicsView._hud.maxButton.setIcon('maximize')
class MyWindow(QMainWindow):
    text_update = pyqtSignal(str)
    
   
    # Create main window
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
       # self.
        self.central = QWidget(self)
        self.control_side=QVBoxLayout()
        self.textbox = QTextEdit(self.central)
        self.textbox.setFont(TEXT_FONT)
        self.textbox.setMinimumSize(50, 50)
        self.text_update.connect(self.append_text)
        sys.stdout = self
        print("Camera number %u" % camera_num)
        self.logic = 0
        self.value = 1
        self.V_Logic=0
        self.ImageName=""
        
       
        
        #LoginForm.center(self)
        
        #PickName.valueChanged.connect(print(PickName))
            #print(PickName)



        if DISP_SCALE > 1:
            print("Display scale %u:1" % DISP_SCALE)

        self.vlayout = QVBoxLayout()        # Window layout
        self.displays = QHBoxLayout()
        self.control = QVBoxLayout()
        self.textboxs= QHBoxLayout()
        self.co2= QVBoxLayout()
        self.buttons =QVBoxLayout()
        self.disp = ImageWidget(self)
        self.controls= QTabWidget()
      

        self.vlayout.addLayout(self.displays)
        self.displays.addWidget(self.disp)
        self.label = QLabel(self)
       # self.displays.addLayout(self.control)
        self.displays.addLayout(self.textboxs)
        self.vlayout.addWidget(self.label)
        self.vlayout.addWidget(self.textbox)
        self.central.setLayout(self.vlayout)
        self.setCentralWidget(self.central)
        self.central.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.displays.addLayout(self.control_side)
        #self.control_side.addWidget(self.controls)
        self.control_side.addLayout(self.control)

 
 
        #widget

        self.Pictures=QWidget()
        self.Pictures.layout=QVBoxLayout()
        self.Pictures.setLayout(self.Pictures.layout)
        
        self.Videos=QWidget()
        self.Videos.layout=QVBoxLayout()
        self.Videos.setLayout(self.Videos.layout)
  
        
        self.controls.addTab(self.Pictures,"Multimedia")
        #self.controls.addTab(self.Videos,"Videos")

        #carbon
        self.control.addLayout(self.co2)      
                # C02(+)
        self.btnco2p= QPushButton('CO2+')
        self.btnco2p.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        #self.co2.addWidget(self.btnco2p)
                #Labels
        self.setco2=QLabel("mmHg")
        #self.co2.addWidget(self.setco2)
        self.setco2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.setco2.setAlignment(Qt.AlignCenter)
   
                # CO2(-)
        self.btnco2m= QPushButton('CO2-')
        #self.co2.addWidget(self.btnco2m)
        self.btnco2m.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
      
       
        self.mainMenu = self.menuBar()      # Menu bar
        exitAction = QAction('&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(self.close)
        self.fileMenu = self.mainMenu.addMenu('&File')
        self.fileMenu.addAction(exitAction)
        
        #spacers
        self.verticalSpacer = QSpacerItem(150, 100,QSizePolicy.Expanding)
        self.verticalSpacerb = QSpacerItem(70, 50,QSizePolicy.Expanding)
        #sizes
        size = QSize(60, 60)
        # Camera
        self.btnc= QPushButton('Capture')
        self.btnc.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.Pictures.layout.addLayout(self.buttons)
        self.buttons.addWidget(self.btnc)
        self.buttons.addSpacerItem(self.verticalSpacer)
        self.btnc.setIcon(QIcon('camera.png'))
        #self.btnc.setStyleSheet("border-radius : 50;")
        self.btnc.setIconSize(size)


        #Video
        self.btnr= QPushButton('Record')
        self.btnr.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.Pictures.layout.addWidget(self.btnr)
        self.Pictures.layout.addSpacerItem(self.verticalSpacerb)
        self.btnr.setIcon(QIcon('video.png'))
        self.btnr.setIconSize(size)
        
        self.btns= QPushButton('Stop')
        self.btns.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
        self.Pictures.layout.addWidget(self.btns)
        self.btns.setIcon(QIcon('stop.png'))
        self.btns.setIconSize(size)
        self.Pictures.layout.addSpacerItem(self.verticalSpacerb)
        
        self.btnc.clicked.connect(self.CaptureClicked)# Capture Photo trigger
        self.btnr.clicked.connect(self.RecordingClicked) # Recording Video trigger
        self.btns.clicked.connect(self.StopClicked)#Stop recording Trigger
        
    # capturing image
    def CaptureClicked(self):
        
        self.now = datetime.now()
        self.dt_string = self.now.strftime("%d_%m-%H_%M_%S")
        self.ImageName=PatientName+"-"+self.dt_string
        self.logic=2
        #print(self.ImageName)
        
        ##recording video
    def RecordingClicked(self):
        self.V_Logic=3
        self.FileName=self.ImageName+".avi"
    def StopClicked(self):
        self.V_Logic=4
        
    def change_res(cap, width, height):
        cap.set(3, width)
        cap.set(4, height)
    
    # grab resolution dimensions and set video capture to it.
    def get_dims(cap, res='720p'):
        width, height = STD_DIMENSIONS["480p"]
        if res in STD_DIMENSIONS:
            width,height = STD_DIMENSIONS[res]
        ## change the current caputre device
        ## to the resulting resolution
        MyWindow.change_res(cap, width, height)
        return width, height
    

    def get_video_type(FileName):
        FileName, ext = os.path.splitext(FileName)
        if ext in VIDEO_TYPE:
          return  VIDEO_TYPE[ext]
        return VIDEO_TYPE['avi']
    
    

        
    #>>>>>>>>>>>>>>>>>>>>>>>>
        
   
    # Start image capture & display
    def start(self):
        self.timer = QTimer(self)           # Timer to trigger display
        self.timer.timeout.connect(lambda: 
                    self.show_image(image_queue, self.disp, DISP_SCALE))
        self.timer.start(DISP_MSEC)         
        self.capture_thread = threading.Thread(target=grab_images, 
                    args=(camera_num, image_queue))
        self.capture_thread.start()         # Thread to grab images

    # Fetch camera image from queue, and display it
    def show_image(self, imageq, display, scale):
        if not imageq.empty():
            image = imageq.get()
            if image is not None and len(image) > 0:
                img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                #img=img.flip()
                self.display_image(img, display, scale)
                
                #capturing
                if (self.logic==2):
                   self.value=self.value+1
                   cv2.imwrite('%s.jpg'%self.ImageName,image)
                   print('your Image have been Saved')
                   self.logic=1
                #else:
                   #print("error printing")
                #video recording
                if (self.V_Logic==3):
                   out.write(image)
                   print("Recording...")
                
                if (self.V_Logic==4):
                   out.release()
                   print("Recording Stopped.")
                   self.V_Logic=0
                    
                
    def DisplayPatient(self):
       # self.setco2.setText(B.PatientName)
        print("Patient Name:", PatientName)
 
  

    # Display an image, reduce size if required
    
    def display_image(self, img, display, scale=1):
        disp_size = img.shape[1]//scale, img.shape[0]//scale
        disp_bpl = disp_size[0] * 3
        if scale > 1:
            img = cv2.resize(img, disp_size, 
                             interpolation=cv2.INTER_CUBIC)
        qimg = QImage(img.data, disp_size[0], disp_size[1], 
                      disp_bpl, IMG_FORMAT)
        display.setImage(qimg)

    # Handle sys.stdout.write: update text display
    def write(self, text):
        self.text_update.emit(str(text))
    def flush(self):
        pass

    # Append to text display
    def append_text(self, text):
        cur = self.textbox.textCursor()     # Move cursor to end of text
        cur.movePosition(QTextCursor.End) 
        s = str(text)
        while s:
            head,sep,s = s.partition("\n")  # Split line at LF
            cur.insertText(head)            # Insert text at cursor
            if sep:                         # New line if LF
                cur.insertBlock()
        self.textbox.setTextCursor(cur)     # Update visible cursor

    # Window is closing: stop video capture
    def closeEvent(self, event):
        global capturing
        capturing = False
        self.capture_thread.join()
            def __init__(self, source_stage_index, num_stages, *args,
                         **kwargs):
                super(LabelDistributionOptionsDlg,
                      self).__init__(*args, **kwargs)

                from PyQt4.QtCore import Qt
                from PyQt4.QtGui import QGroupBox, QCheckBox, QRadioButton, QDialogButtonBox

                self.setWindowTitle(
                    "Distributing from Stage {}".format(source_stage_index +
                                                        1))

                self.stage_checkboxes = []
                for stage_index in range(1, num_stages + 1):
                    self.stage_checkboxes.append(
                        QCheckBox("Stage {}".format(stage_index)))

                # By default, send labels back into the current stage, at least.
                self.stage_checkboxes[source_stage_index].setChecked(True)

                stage_selection_layout = QVBoxLayout()
                for checkbox in self.stage_checkboxes:
                    stage_selection_layout.addWidget(checkbox)

                stage_selection_groupbox = QGroupBox(
                    "Send labels from Stage {} to:".format(source_stage_index +
                                                           1), self)
                stage_selection_groupbox.setLayout(stage_selection_layout)

                self.copy_button = QRadioButton("Copy", self)
                self.partition_button = QRadioButton("Partition", self)
                self.partition_button.setChecked(True)
                distribution_mode_layout = QVBoxLayout()
                distribution_mode_layout.addWidget(self.copy_button)
                distribution_mode_layout.addWidget(self.partition_button)

                distribution_mode_group = QGroupBox("Distribution Mode", self)
                distribution_mode_group.setLayout(distribution_mode_layout)

                buttonbox = QDialogButtonBox(Qt.Horizontal, parent=self)
                buttonbox.setStandardButtons(QDialogButtonBox.Ok
                                             | QDialogButtonBox.Cancel)
                buttonbox.accepted.connect(self.accept)
                buttonbox.rejected.connect(self.reject)

                dlg_layout = QVBoxLayout()
                dlg_layout.addWidget(stage_selection_groupbox)
                dlg_layout.addWidget(distribution_mode_group)
                dlg_layout.addWidget(buttonbox)
                self.setLayout(dlg_layout)
Exemple #54
0
class RangeByNoSettingUI(QDialog):
    def __init__(self, iface, parent=None):
        super(RangeByNoSettingUI, self).__init__()
        self.iface = iface
        self.parent = parent
        self.iface.mapCanvas().currentLayerChanged[QgsMapLayer].connect(
            self.LayerChanged)

        self.color_btn_list = []  # 保存各范围所设置的颜色按钮
        self.delete_btn_list = []  # 保存各范围所设置的删除按钮
        self.range_widget_list = []
        self.setting_list = []  # 保存范围参数设置

        self.initUI()

    # 初始化界面
    def initUI(self):
        self.setWindowTitle(u"分类显示")

        layer_label = QLabel(u"选择图层:")
        self.layer_combo = QComboBox()
        layers_name = getAllLayerName(self.iface)
        self.layer_combo.addItems(layers_name)
        self.layer = getLayerByName(self.layer_combo.currentText(), self.iface)
        self.connect(self.layer_combo, SIGNAL('currentIndexChanged(int)'),
                     self.layerListener)

        field_label = QLabel(u"选择字段:")
        self.field_combo = QComboBox()
        if self.layer != None:
            fields_list = []
            for field in self.layer.pendingFields():
                fields_list.append(field.name().strip())
            self.field_combo.addItems(fields_list)

        ok = QPushButton(u"确定")
        cancel = QPushButton(u"取消")
        self.connect(ok, SIGNAL('clicked()'), self.run)
        self.connect(cancel, SIGNAL('clicked()'), self.accept)

        # 选择图层、字段Widget
        source_grid = QGridLayout()
        source_grid.setSpacing(10)
        source_grid.addWidget(layer_label, 0, 1)
        source_grid.addWidget(self.layer_combo, 0, 2)
        source_grid.addWidget(field_label, 1, 1)
        source_grid.addWidget(self.field_combo, 1, 2)
        source_widget = QWidget()
        source_widget.setLayout(source_grid)

        # 参数设置窗口(带滚动条)
        self.setting_Widget = QWidget()
        self.setting_Widget.setMinimumSize(380, 800)

        self.scroll_vbox = QVBoxLayout()
        self.scroll_vbox.setSpacing(15)

        self.setting_vbox = QVBoxLayout()
        self.setting_vbox.setSpacing(5)
        range_widget = self.createARange()
        self.setting_vbox.addWidget(range_widget)

        self.add_range_btn = QPushButton(u"添加")
        self.connect(self.add_range_btn, SIGNAL("clicked()"),
                     self.add_range_box)

        self.scroll_vbox.addLayout(self.setting_vbox)
        self.scroll_vbox.addWidget(self.add_range_btn)
        self.scroll_vbox.addStretch(1)

        self.setting_Widget.setLayout(self.scroll_vbox)

        self.scroll = QScrollArea()
        self.scroll.setWidget(self.setting_Widget)
        self.scroll.setAutoFillBackground(True)
        self.scroll.setWidgetResizable(True)

        # 确定/取消 按钮 Widget
        btn_hbox = QHBoxLayout()
        btn_hbox.setSpacing(15)
        btn_hbox.addStretch(1)
        btn_hbox.addWidget(ok)
        btn_hbox.addWidget(cancel)
        btn_hbox.addStretch(1)
        btn_widget = QWidget()
        btn_widget.setLayout(btn_hbox)

        vbox = QVBoxLayout()
        vbox.setSpacing(15)
        vbox.addWidget(source_widget)
        vbox.addWidget(self.scroll)
        vbox.addWidget(btn_widget)

        self.setLayout(vbox)
        self.setFixedSize(430, 500)

    # 生成一个范围设置控件组(Wigget)
    def createARange(self,
                     color_value=u"yellow",
                     lower_value=u"",
                     upper_value=u""):
        delete_btn = QPushButton(self)
        delete_icon = QIcon(
            os.path.join(cmd_folder, u"..", u'images', u'delete.png'))
        delete_btn.setIcon(delete_icon)
        delete_btn.setIconSize(QSize(25, 25))
        delete_btn.setFixedSize(30, 30)
        delete_btn.setFocusPolicy(Qt.NoFocus)
        self.connect(delete_btn, SIGNAL("clicked()"), self.delete_range_box)

        color = QColor(color_value)
        color_btn = QPushButton(self)
        color_btn.setStyleSheet('QWidget {background-color:%s}' % color.name())
        color_btn.clicked.connect(self.colordialog)

        lower_edit = QLineEdit(lower_value)  # 下限
        upper_edit = QLineEdit(upper_value)  # 上限
        validator = QDoubleValidator(-9999999.9999, 9999999.9999, 4,
                                     self)  # 取值范围为-9999999.9999~9999999.9999
        lower_edit.setValidator(validator)
        upper_edit.setValidator(validator)

        label1 = QLabel(u" : ")
        label2 = QLabel(u'—')

        range_widget = QWidget()

        range_box = QHBoxLayout()
        range_box.setSpacing(10)
        range_box.addWidget(delete_btn)
        range_box.addWidget(color_btn)
        range_box.addWidget(label1)
        range_box.addWidget(lower_edit)
        range_box.addWidget(label2)
        range_box.addWidget(upper_edit)
        range_box.setStretchFactor(color_btn, 1.5)
        range_box.setStretchFactor(lower_edit, 1)
        range_box.setStretchFactor(upper_edit, 1)
        range_widget.setLayout(range_box)

        self.color_btn_list.append(color_btn)
        self.delete_btn_list.append(delete_btn)
        self.range_widget_list.append(range_widget)

        self.setting_list.append([color, lower_edit, upper_edit])

        return range_widget

    # 新增一个可设置的范围
    def add_range_box(self):
        new_range_widget = self.createARange()
        # 重新布局
        self.setting_vbox.addWidget(new_range_widget)

    # 删除一组范围设置
    def delete_range_box(self):
        delete_index = None
        delete_button = self.sender()  # 获取信号来源
        for (index, button) in enumerate(self.delete_btn_list):
            if button is delete_button:
                delete_index = index
        # 删除 widget
        if delete_index != None:
            range_widget = self.range_widget_list[delete_index]
            self.setting_vbox.removeWidget(range_widget)
            range_widget.deleteLater()
            del self.range_widget_list[delete_index]
            del self.color_btn_list[delete_index]
            del self.delete_btn_list[delete_index]
            del self.setting_list[delete_index]

    # 颜色设置对话框
    def colordialog(self):
        col = QColorDialog.getColor()
        button = self.sender()  # 获取信号来源
        if col.isValid():
            button.setStyleSheet('QWidget{background-color:%s}' % col.name())
        for b in self.color_btn_list:
            if button is b:
                bindex = self.color_btn_list.index(b)
                self.setting_list[bindex][0] = col

    # 图层改变监听事件
    def layerListener(self):
        # 先清空原有的字段选择combobox
        self.field_combo.clear()
        # 获取所选图层名字
        layer_name = self.layer_combo.currentText()
        self.layer = getLayerByName(layer_name, self.iface)
        # 获取所选图层的所有字段
        if self.layer:
            fields_list = []
            for field in self.layer.pendingFields():
                fields_list.append(field.name().strip())
            self.field_combo.addItems(fields_list)

    # 确定按钮监听事件
    def run(self):
        # 先检查是否选中了图层
        if not self.layer:
            self.accept()
            QMessageBox.critical(self, u"错误", u"<b>无法选中图层! <\b>")
            return False
        # 检查范围设置是否规范
        setting_list = []  # 保存处理过的范围设置list (每个范围用元组保存)
        for (color, lower_edit, upper_edit) in self.setting_list:
            lower = lower_edit.text().strip()
            upper = upper_edit.text().strip()
            # 如果上下限其中有一个为空,则提示错误
            if (not lower) or (not upper):
                QMessageBox.critical(self, u"错误", u"<b>分类范围上下限不能为空! <\b>")
                return False
            lower = float(lower)
            upper = float(upper)
            # 检查下限是否大于上线
            if lower > upper:
                QMessageBox.critical(self, u"错误", u"<b>上下限填写有误,请检查! <\b>")
                return False
            setting_list.append((color, lower, upper))

        field = self.field_combo.currentText().strip()  # 获取所设置的字段
        # 显示图例
        self.accept()
        legend = RangeByNoLegend(self.iface)
        legend.showLegend(self.layer, field, setting_list)
        if not legend.isVisible():
            legend.show()
            legend.exec_()

    def LayerChanged(self, currentlayer):
        if currentlayer != self.layer:
            self.iface.messageBar().pushMessage(u'提示', u'切换图层,分析停止',
                                                QgsMessageBar.INFO, 4)
            self.close()
Exemple #55
0
    def __init__(self, parent=None):
        super(VirtualKeyboard, self).__init__(parent)

        self.globalLayout = QVBoxLayout(self)
        self.keysLayout = QGridLayout()
        self.keysLayout.setObjectName("keysLayout")
        self.buttonLayout = QHBoxLayout()
        self.dictOfButtons = {}
        #        self.setStyleSheet("QWidget {"
        #                           "background-color: rgb(118, 118, 118);"
        #                           "color: rgb(240, 240, 240);"
        #                           "}"
        #                           ""
        #                           "QLabel{"
        #                           "color: rgb(240, 240, 240);"
        #                           "}"
        #                           "QPushButton{"
        #                           "background-color: rgb(42, 42, 42);"
        #                           "color: rgb(255, 255, 255);"
        #                           "border-style: solid;"
        #                           "border-color: black;"
        #                           "border-width: 5px;"
        #                           "border-radius: 10px;"
        #                           "font: 63 20pt 'Ubuntu';"
        #                           "}")
        self.keyListByLines = [
            ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', u'ß',
             '?'],  # comment this line if you dont want numbers
            ['q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', u'ü', '+'],
            ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', u'ö', u'ä', '#'],
            ['y', 'x', 'c', 'v', 'b', 'n', 'm', '_', '-', '/', '.', ':'],
        ]
        self.inputString = ""
        self.state = InputState.LOWER

        self.stateButton = QPushButton()
        self.stateButton.setText(self.tr('Shift'))
        self.stateButton.setObjectName("Shift")
        self.stateButton.setFocusPolicy(Qt.NoFocus)
        self.backButton = QPushButton()
        self.backButton.setText(self.tr('Delete'))
        self.backButton.setFocusPolicy(Qt.NoFocus)
        self.backButton.setObjectName("Back")
        self.okButton = QPushButton()
        self.okButton.setText('Ok')
        self.okButton.setFocusPolicy(Qt.NoFocus)
        self.okButton.setObjectName("Ok")
        self.cancelButton = QPushButton()
        self.cancelButton.setText(self.tr("Abort"))
        self.cancelButton.setFocusPolicy(Qt.NoFocus)
        self.cancelButton.setObjectName("Cancel")
        self.spaceButton = SpaceKeyButton(" ")
        self.spaceButton.setText(self.tr("Space"))
        self.spaceButton.setObjectName("Space")
        self.spaceButton.setFocusPolicy(Qt.NoFocus)
        self.dictOfButtons.update({"keyButton ": self.spaceButton})
        self.connect(self.spaceButton, SIGNAL("sigKeyButtonClicked"),
                     self.addInputByKey)

        self.inputLine = QLineEdit()
        self.inputLine.setObjectName("SearchText")
        self.inputLine.setFont(font)

        for lineIndex, line in enumerate(self.keyListByLines):
            for keyIndex, key in enumerate(line):
                buttonName = "keyButton" + key.capitalize()
                self.dictOfButtons.update({buttonName: KeyButton(key)})
                self.keysLayout.addWidget(self.getButtonByKey(key),
                                          self.keyListByLines.index(line),
                                          line.index(key))
                self.getButtonByKey(key).setText(key)
                self.connect(self.getButtonByKey(key),
                             SIGNAL("sigKeyButtonClicked"), self.addInputByKey)
                self.keysLayout.setColumnMinimumWidth(
                    keyIndex, 50)  # needed space for optical feedback
            self.keysLayout.setRowMinimumHeight(lineIndex, 50)

        self.connect(self.stateButton, SIGNAL("clicked()"), self.switchState)
        self.connect(self.backButton, SIGNAL("clicked()"), self.backspace)
        self.connect(self.okButton, SIGNAL("clicked()"), self.emitInputString)
        self.connect(self.cancelButton, SIGNAL("clicked()"), self.emitCancel)

        self.buttonLayout.addWidget(self.cancelButton, 1)
        self.buttonLayout.addWidget(self.backButton, 1)
        self.buttonLayout.addWidget(self.spaceButton,
                                    3)  # replaced with layout (tmpLayout)
        self.buttonLayout.addWidget(self.stateButton, 1)
        self.buttonLayout.addWidget(self.okButton, 1)

        self.globalLayout.addWidget(self.inputLine)
        self.globalLayout.addLayout(self.keysLayout, 1)
        #        # construct a small horizontal layout, to assure that space-bare is in the middle of the keyboard...
        #        tmpLayout = QHBoxLayout()
        #        space = QSpacerItem(0,0)
        #        tmpLayout.addSpacerItem(space)
        #        tmpLayout.addWidget(self.spaceButton)
        #        tmpLayout.addSpacerItem(space)
        #        self.globalLayout.addLayout(tmpLayout)

        self.globalLayout.addLayout(self.buttonLayout)
        self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.inputLine.setFocus()
Exemple #56
0
class QuadView(QWidget):
    def __init__(self, parent, view1, view2, view3, view4 = None):
        QWidget.__init__(self, parent)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.installEventFilter(self)
        
        self.dockableContainer = []
        
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        
        self.splitVertical = QSplitter(Qt.Vertical, self)
        self.layout.addWidget(self.splitVertical)
        self.splitHorizontal1 = QSplitter(Qt.Horizontal, self.splitVertical)
        self.splitHorizontal1.setObjectName("splitter1")
        self.splitHorizontal2 = QSplitter(Qt.Horizontal, self.splitVertical)
        self.splitHorizontal2.setObjectName("splitter2")
        self.splitHorizontal1.splitterMoved.connect(self.horizontalSplitterMoved)
        self.splitHorizontal2.splitterMoved.connect(self.horizontalSplitterMoved)
        
        self.imageView2D_1 = view1
        
        self.imageView2D_2 = view2
        
        self.imageView2D_3 = view3
        
        self.dock1_ofSplitHorizontal1 = ImageView2DDockWidget(self.imageView2D_1)
        self.dock1_ofSplitHorizontal1.connectHud()
        self.dockableContainer.append(self.dock1_ofSplitHorizontal1)
        self.dock1_ofSplitHorizontal1.onDockButtonClicked.connect(lambda arg=self.dock1_ofSplitHorizontal1 : self.on_dock(arg))
        self.dock1_ofSplitHorizontal1.onMaxButtonClicked.connect(lambda arg=self.dock1_ofSplitHorizontal1 : self.on_max(arg))
        self.dock1_ofSplitHorizontal1.onMinButtonClicked.connect(lambda arg=self.dock1_ofSplitHorizontal1 : self.on_min(arg))
        self.splitHorizontal1.addWidget(self.dock1_ofSplitHorizontal1)

        self.dock2_ofSplitHorizontal1 = ImageView2DDockWidget(self.imageView2D_2)
        self.dock2_ofSplitHorizontal1.onDockButtonClicked.connect(lambda arg=self.dock2_ofSplitHorizontal1 : self.on_dock(arg))
        self.dock2_ofSplitHorizontal1.onMaxButtonClicked.connect(lambda arg=self.dock2_ofSplitHorizontal1 : self.on_max(arg))
        self.dock2_ofSplitHorizontal1.onMinButtonClicked.connect(lambda arg=self.dock2_ofSplitHorizontal1 : self.on_min(arg))
        self.dock2_ofSplitHorizontal1.connectHud()
        self.dockableContainer.append(self.dock2_ofSplitHorizontal1)
        self.splitHorizontal1.addWidget(self.dock2_ofSplitHorizontal1)

        self.dock1_ofSplitHorizontal2 = ImageView2DDockWidget(self.imageView2D_3)
        self.dock1_ofSplitHorizontal2.onDockButtonClicked.connect(lambda arg=self.dock1_ofSplitHorizontal2 : self.on_dock(arg))
        self.dock1_ofSplitHorizontal2.onMaxButtonClicked.connect(lambda arg=self.dock1_ofSplitHorizontal2 : self.on_max(arg))
        self.dock1_ofSplitHorizontal2.onMinButtonClicked.connect(lambda arg=self.dock1_ofSplitHorizontal2 : self.on_min(arg))
        self.dock1_ofSplitHorizontal2.connectHud()
        self.dockableContainer.append(self.dock1_ofSplitHorizontal2)
        self.splitHorizontal2.addWidget(self.dock1_ofSplitHorizontal2)

        self.dock2_ofSplitHorizontal2 = ImageView2DDockWidget(view4)
        self.dockableContainer.append(self.dock2_ofSplitHorizontal2)
        self.splitHorizontal2.addWidget(self.dock2_ofSplitHorizontal2)  
        
        #this is a hack: with 0 ms it does not work...
        QTimer.singleShot(250, self._resizeEqual)
        
    def _resizeEqual(self):
        if not all( [dock.isVisible() for dock in self.dockableContainer] ):
            return
        w, h = self.size().width()-self.splitHorizontal1.handleWidth(), self.size().height()-self.splitVertical.handleWidth()

        self.splitVertical.setSizes([h/2, h/2])

        if self.splitHorizontal1.count() == 2 and self.splitHorizontal2.count() == 2:
            #docks = [self.imageView2D_1, self.imageView2D_2, self.imageView2D_3, self.testView4]
            docks = []        
            for splitter in [self.splitHorizontal1, self.splitHorizontal2]:
                for i in range( splitter.count() ):
                    docks.append( splitter.widget(i).graphicsView )
            
            w1  = [docks[i].minimumSize().width() for i in [0,2] ]
            w2  = [docks[i].minimumSize().width() for i in [1,3] ]
            wLeft  = max(w1)
            wRight = max(w2)
            if wLeft > wRight and wLeft > w/2:
                wRight = w - wLeft
            elif wRight >= wLeft and wRight > w/2:
                wLeft = w - wRight
            else:
                wLeft = w/2
                wRight = w/2
            self.splitHorizontal1.setSizes([wLeft, wRight])
            self.splitHorizontal2.setSizes([wLeft, wRight])
        
    def eventFilter(self, obj, event):
        if(event.type() in [QEvent.WindowActivate, QEvent.Show]):
            self._synchronizeSplitter()
        return False

    def _synchronizeSplitter(self):
        sizes1 = self.splitHorizontal1.sizes()
        sizes2 = self.splitHorizontal2.sizes()
        if len(sizes1) > 0 and sizes1[0] > 0:
            self.splitHorizontal2.setSizes(sizes1)
        elif len(sizes2) > 0 and sizes2[0] > 0:
            self.splitHorizontal1.setSizes(sizes2)
    
    def resizeEvent(self, event):
        QWidget.resizeEvent(self, event)
        self._synchronizeSplitter()
    
    def horizontalSplitterMoved(self, x, y):
        if self.splitHorizontal1.count() != 2 or self.splitHorizontal2.count() != 2:
            return 
        sizes = self.splitHorizontal1.sizes()
        #What. Nr2
        if self.splitHorizontal2.closestLegalPosition(x, y) < self.splitHorizontal2.closestLegalPosition(x, y):
            sizeLeft = self.splitHorizontal1.closestLegalPosition(x, y)
        else:
            sizeLeft = self.splitHorizontal2.closestLegalPosition(x, y)
            
        sizeRight = sizes[0] + sizes[1] - sizeLeft
        sizes = [sizeLeft, sizeRight]
        
        self.splitHorizontal1.setSizes(sizes)
        self.splitHorizontal2.setSizes(sizes) 

    def addStatusBar(self, bar):
        self.statusBar = bar
        self.layout.addLayout(self.statusBar)
        
    def setGrayScaleToQuadStatusBar(self, gray):
        self.quadViewStatusBar.setGrayScale(gray)
        
    def setMouseCoordsToQuadStatusBar(self, x, y, z):
        self.quadViewStatusBar.setMouseCoords(x, y, z) 

    def ensureMaximized(self, axis):
        """
        Maximize the view for the given axis if it isn't already maximized.
        """
        axisDict = { 0 : self.dock2_ofSplitHorizontal1,  # x
                     1 : self.dock1_ofSplitHorizontal2,  # y
                     2 : self.dock1_ofSplitHorizontal1 } # z
        
        if not axisDict[axis]._isMaximized:
            self.switchMinMax(axis)

    def switchMinMax(self,axis):
        """Switch an AxisViewWidget between from minimized to maximized and vice
        versa.

        Keyword arguments:
        axis -- the axis which is represented by the widget (no default)
                either string or integer 
                'x' - 2
                'y' - 1
                'z' - 0
        """
        
        #TODO: get the mapping information from where it is set! if this is not
        #done properly - do it properly

        if type(axis) == str:
            axisDict = { 'x' : self.dock2_ofSplitHorizontal1,  # x
                         'y' : self.dock1_ofSplitHorizontal2,  # y
                         'z' : self.dock1_ofSplitHorizontal1 } # z
        elif type(axis) == int:
            axisDict = { 0 : self.dock2_ofSplitHorizontal1,  # x
                         1 : self.dock1_ofSplitHorizontal2,  # y
                         2 : self.dock1_ofSplitHorizontal1 } # z

        dockWidget = axisDict.pop(axis)
        for dWidget in axisDict.values():
            if dWidget._isMaximized:
                dWidget.graphicsView._hud.maximizeButtonClicked.emit()
        dockWidget.graphicsView._hud.maximizeButtonClicked.emit()
    
    def switchXMinMax(self):
        self.switchMinMax('x')
    
    def switchYMinMax(self):
        self.switchMinMax('y')
        
    def switchZMinMax(self):
        self.switchMinMax('z')

    def on_dock(self, dockWidget):
        if dockWidget._isDocked:
            dockWidget.undockView()
            self.on_min(dockWidget)
            dockWidget.minimizeView()
        else:
            dockWidget.dockView()

    def on_max(self, dockWidget):
        dockWidget.setVisible(True)
        for dock in self.dockableContainer:
            if not dockWidget == dock:
                dock.setVisible(False)

        # Force sizes to be updated now
        QApplication.processEvents()
        
        # On linux, the vertical splitter doesn't seem to refresh unless we do so manually
        # Presumably, this is a QT bug.
        self.splitVertical.refresh()

        # Viewport doesn't update automatically...
        view = dockWidget.graphicsView        
        view.viewport().setGeometry( view.rect() )

    def on_min(self, dockWidget):

        for dock in self.dockableContainer:
            dock.setVisible(True)

        # Force sizes to be updated now
        QApplication.processEvents()
        self._resizeEqual()

        # Viewports don't update automatically...
        for dock in self.dockableContainer:
            view = dock.graphicsView
            if hasattr(view, 'viewport'):
                view.viewport().setGeometry( view.rect() )
class ProjectTreeColumn(QWidget):
    def __init__(self, *args, **kwargs):
        super(ProjectTreeColumn, self).__init__(*args, **kwargs)
        self._layout = QVBoxLayout()
        self._layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self.setLayout(self._layout)
        self._vbox = QVBoxLayout()
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)
        self._vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        self._buttons = []

        self._projects_area = QWidget()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        self._projects_area.setLayout(self._vbox)

        self._scroll_area = QScrollArea()
        self.layout().addWidget(self._scroll_area)
        self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self._scroll_area.setWidgetResizable(True)
        self._scroll_area.setEnabled(True)
        self._scroll_area.setWidget(self._projects_area)
        self._scroll_area.setGeometry(self.geometry())
        self._vbox.setGeometry(self.geometry())
        self.projects = []
        self._active_project = None

        connections = ({
            'target': 'main_container',
            'signal_name': 'addToProject(QString)',
            'slot': self._add_file_to_project
        }, )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)

        #FIXME: Should have a ninja settings object that stores tree state
        #FIXME: Or bettter, application data object
        #TODO: check this:
        #self.connect(ide, SIGNAL("goingDown()"),
        #self.tree_projects.shutdown)
        #self.connect(self.tree_projects,
        #SIGNAL("addProjectToConsole(QString)"),
        #self._add_project_to_console)
        #self.connect(self.tree_projects,
        #SIGNAL("removeProjectFromConsole(QString)"),
        #self._remove_project_from_console)

        #def close_project_signal():
        #self.emit(SIGNAL("updateLocator()"))

        #def close_files_related_to_closed_project(project):
        #if project:
        #self.emit(SIGNAL("projectClosed(QString)"), project)
        #self.connect(self.tree_projects, SIGNAL("closeProject(QString)"),
        #close_project_signal)
        #self.connect(self.tree_projects, SIGNAL("refreshProject()"),
        #close_project_signal)
        #self.connect(self.tree_projects,
        #SIGNAL("closeFilesFromProjectClosed(QString)"),
        #close_files_related_to_closed_project)

    def install_tab(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

    def load_session_projects(self, projects):
        for project in projects:
            self._open_project_folder(project)

    def open_project_folder(self):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        folderName = QFileDialog.getExistingDirectory(
            self, self.tr("Open Project Directory"), directory)
        logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            self._open_project_folder(folderName)

    def _open_project_folder(self, folderName):
        ninjaide = IDE.get_service("ide")
        project = NProject(folderName)
        qfsm = ninjaide.filesystem.open_project(project)
        if qfsm:
            self.add_project(project)
            self.emit(SIGNAL("updateLocator()"))

    def _add_file_to_project(self, path):
        """Add the file for 'path' in the project the user choose here."""
        if self._active_project:
            pathProject = [self._active_project.project]
            addToProject = add_to_project.AddToProject(pathProject, self)
            addToProject.exec_()
            if not addToProject.pathSelected:
                return
            main_container = IDE.get_service('main_container')
            if not main_container:
                return
            editorWidget = main_container.get_current_editor()
            if not editorWidget.file_path:
                name = QInputDialog.getText(None,
                                            self.tr("Add File To Project"),
                                            self.tr("File Name:"))[0]
                if not name:
                    QMessageBox.information(
                        self, self.tr("Invalid Name"),
                        self.tr("The file name is empty, please enter a name"))
                    return
            else:
                name = file_manager.get_basename(editorWidget.file_path)
            new_path = file_manager.create_path(addToProject.pathSelected,
                                                name)
            ide_srv = IDE.get_service("ide")
            old_file, ide_srv.get_or_create_nfile(path)
            new_file = old_file.save(editorWidget.get_text(), path)
            #FIXME: Make this file replace the original in the open tab
        else:
            pass
            # Message about no project

    def add_project(self, project):
        if project not in self.projects:
            ptree = TreeProjectsWidget(project)
            self.connect(ptree, SIGNAL("setActiveProject(PyQt_PyObject)"),
                         self._set_active_project)
            self.connect(ptree, SIGNAL("closeProject(PyQt_PyObject)"),
                         self._close_project)
            pmodel = project.model
            ptree.setModel(pmodel)
            ptree.header().title = project.name
            ptree.header().path = project.path
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            #self._widget.layout().addWidget(scrollable_wrapper(ptree))
            self._projects_area.layout().addWidget(ptree)
            if self._active_project is None:
                ptree.set_default_project()
            self.projects.append(ptree)
            ptree.setGeometry(self.geometry())

    def _close_project(self, widget):
        """Close the project related to the tree widget."""
        self.projects.remove(widget)
        if self._active_project == widget and len(self.projects) > 0:
            self.projects[0].set_default_project()
        self._layout.removeWidget(widget)
        ninjaide = IDE.get_service('ide')
        ninjaide.filesystem.close_project(widget.project.path)
        widget.deleteLater()

    def _set_active_project(self, tree_proj):
        if self._active_project is not None:
            self._active_project.set_default_project(False)
        self._active_project = tree_proj

    def close_opened_projects(self):
        for project in reversed(self.projects):
            self._close_project(project)

    def save_project(self):
        """Save all the opened files that belongs to the actual project."""
        if self._active_project:
            path = self._active_project.project.path
            main_container = IDE.get_service('main_container')
            if path and main_container:
                main_container.save_project(path)

    def create_new_project(self):
        if not self.tree_projects:
            QMessageBox.information(
                self, self.tr("Projects Disabled"),
                self.tr("Project support has been disabled from Preferences"))
            return
        wizard = wizard_new_project.WizardNewProject(self)
        wizard.show()

    @property
    def current_project(self):
        if self._active_project:
            return self._active_project.project

    @property
    def current_tree(self):
        return self._active_project
Exemple #58
0
class CommanderWindow(QDialog):
    def __init__(self, parent, canvas):
        self.canvas = canvas
        QDialog.__init__(self, parent, Qt.FramelessWindowHint)
        self.commands = imp.load_source('commands', self.commandsFile())
        self.initGui()

    def commandsFolder(self):
        folder = unicode(os.path.join(userFolder(), 'commander'))
        mkdir(folder)
        return os.path.abspath(folder)

    def commandsFile(self):
        f = os.path.join(self.commandsFolder(), 'commands.py')
        if not os.path.exists(f):
            out = open(f, 'w')
            out.write('from qgis.core import *\n')
            out.write('import processing\n\n')
            out.write('def removeall():\n')
            out.write('\tmapreg = QgsMapLayerRegistry.instance()\n')
            out.write('\tmapreg.removeAllMapLayers()\n\n')
            out.write('def load(*args):\n')
            out.write('\tprocessing.load(args[0])\n')
            out.close()
        return f

    def algsListHasChanged(self):
        self.fillCombo()

    def initGui(self):
        self.combo = ExtendedComboBox()
        self.fillCombo()

        self.combo.setEditable(True)
        self.label = QLabel('Enter command:')
        self.errorLabel = QLabel('Enter command:')
        self.vlayout = QVBoxLayout()
        self.vlayout.setSpacing(2)
        self.vlayout.setMargin(0)
        self.vlayout.addSpacerItem(
            QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding))
        self.hlayout = QHBoxLayout()
        self.hlayout.addWidget(self.label)
        self.vlayout.addLayout(self.hlayout)
        self.hlayout2 = QHBoxLayout()
        self.hlayout2.addWidget(self.combo)
        self.vlayout.addLayout(self.hlayout2)
        self.vlayout.addSpacerItem(
            QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding))
        self.setLayout(self.vlayout)
        self.combo.lineEdit().returnPressed.connect(self.run)
        self.prepareGui()

    def fillCombo(self):
        self.combo.clear()

        # Add algorithms
        for providerName in Processing.algs.keys():
            provider = Processing.algs[providerName]
            algs = provider.values()
            for alg in algs:
                self.combo.addItem('Processing algorithm: ' + alg.name)

        # Add functions
        for command in dir(self.commands):
            if isinstance(self.commands.__dict__.get(command),
                          types.FunctionType):
                self.combo.addItem('Command: ' + command)

        #Add menu entries
        menuActions = []
        actions = iface.mainWindow().menuBar().actions()
        for action in actions:
            menuActions.extend(self.getActions(action))
        for action in menuActions:
            self.combo.addItem('Menu action: ' + unicode(action.text()))

    def prepareGui(self):
        self.combo.setEditText('')
        self.combo.setMaximumSize(
            QSize(self.canvas.rect().width() - 2 * OFFSET, ITEMHEIGHT))
        self.combo.view().setStyleSheet('min-height: 150px')
        self.combo.setFocus(Qt.OtherFocusReason)
        self.label.setMaximumSize(self.combo.maximumSize())
        self.label.setVisible(False)
        self.adjustSize()
        pt = self.canvas.rect().topLeft()
        absolutePt = self.canvas.mapToGlobal(pt)
        self.move(absolutePt)
        self.resize(self.canvas.rect().width(), HEIGHT)
        self.setStyleSheet('CommanderWindow {background-color: #e7f5fe; \
                            border: 1px solid #b9cfe4;}')

    def getActions(self, action):
        menuActions = []
        menu = action.menu()
        if menu is None:
            menuActions.append(action)
            return menuActions
        else:
            actions = menu.actions()
            for subaction in actions:
                if subaction.menu() is not None:
                    menuActions.extend(self.getActions(subaction))
                elif not subaction.isSeparator():
                    menuActions.append(subaction)

        return menuActions

    def run(self):
        s = unicode(self.combo.currentText())
        if s.startswith('Processing algorithm: '):
            algName = s[len('Processing algorithm: '):]
            alg = Processing.getAlgorithmFromFullName(algName)
            if alg is not None:
                self.close()
                self.runAlgorithm(alg)
        elif s.startswith("Command: "):
            command = s[len("Command: "):]
            try:
                self.runCommand(command)
                self.close()
            except Exception as e:
                self.label.setVisible(True)
                self.label.setText('Error:' + unicode(e))

        elif s.startswith('Menu action: '):
            actionName = s[len('Menu action: '):]
            menuActions = []
            actions = iface.mainWindow().menuBar().actions()
            for action in actions:
                menuActions.extend(self.getActions(action))
            for action in menuActions:
                if action.text() == actionName:
                    self.close()
                    action.trigger()
                    return
        else:
            try:
                self.runCommand(s)
                self.close()
            except Exception as e:
                self.label.setVisible(True)
                self.label.setText('Error:' + unicode(e))

    def runCommand(self, command):
        tokens = command.split(' ')
        if len(tokens) == 1:
            method = self.commands.__dict__.get(command)
            if method is not None:
                method()
            else:
                raise Exception('Wrong command')
        else:
            method = self.commands.__dict__.get(tokens[0])
            if method is not None:
                method(*tokens[1:])
            else:
                raise Exception('Wrong command')

    def runAlgorithm(self, alg):
        alg = alg.getCopy()
        message = alg.checkBeforeOpeningParametersDialog()
        if message:
            dlg = MessageDialog()
            dlg.setTitle(self.tr('Missing dependency'))
            dlg.setMessage(message)
            dlg.exec_()
            return
        dlg = alg.getCustomParametersDialog()
        if not dlg:
            dlg = AlgorithmDialog(alg)
        canvas = iface.mapCanvas()
        prevMapTool = canvas.mapTool()
        dlg.show()
        dlg.exec_()
        if canvas.mapTool() != prevMapTool:
            try:
                canvas.mapTool().reset()
            except:
                pass
            canvas.setMapTool(prevMapTool)
    def __init__(self, title, parent=None, key=''):
        QDialog.__init__(self, parent)
        self.setWindowTitle(title)

        self._ert = ERT.ert
        """:type: res.enkf.enkf_main.EnKFMain"""

        self.key_manager = self._ert.getKeyManager()
        """:type: res.enkf.key_manager.KeyManager """

        self.current_key = key

        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowCancelButtonHint)

        self._tab_map = {}
        self._tab_order = []

        layout = QVBoxLayout()

        self._tabs = QTabWidget()
        layout.addWidget(self._tabs)
        layout.setSizeConstraint(QLayout.SetFixedSize)  # not resizable!!!

        self._button_layout = QHBoxLayout()

        self._reset_button = QToolButton()
        self._reset_button.setIcon(resourceIcon("update.png"))
        self._reset_button.setToolTip("Reset all settings back to default")
        self._reset_button.clicked.connect(self.resetSettings)

        self._undo_button = QToolButton()
        self._undo_button.setIcon(resourceIcon("undo.png"))
        self._undo_button.setToolTip("Undo")
        self._undo_button.clicked.connect(self.undoSettings)

        self._redo_button = QToolButton()
        self._redo_button.setIcon(resourceIcon("redo.png"))
        self._redo_button.setToolTip("Redo")
        self._redo_button.clicked.connect(self.redoSettings)
        self._redo_button.setEnabled(False)

        self._copy_from_button = QToolButton()
        self._copy_from_button.setIcon(resourceIcon("copy_from.png"))
        self._copy_from_button.setToolTip("Copy settings from another key")
        self._copy_from_button.setPopupMode(QToolButton.InstantPopup)
        self._copy_from_button.setEnabled(False)

        self._copy_to_button = QToolButton()
        self._copy_to_button.setIcon(resourceIcon("copy_to.png"))
        self._copy_to_button.setToolTip(
            "Copy current plot settings to other keys")
        self._copy_to_button.setPopupMode(QToolButton.InstantPopup)
        self._copy_to_button.clicked.connect(self.initiateCopyStyleToDialog)
        self._copy_to_button.setEnabled(True)

        tool_menu = QMenu(self._copy_from_button)
        self._popup_list = QListWidget(tool_menu)
        self._popup_list.setSortingEnabled(True)
        self._popup_list.itemClicked.connect(self.keySelected)
        action = QWidgetAction(tool_menu)
        action.setDefaultWidget(self._popup_list)
        tool_menu.addAction(action)
        self._copy_from_button.setMenu(tool_menu)

        self._apply_button = QPushButton("Apply")
        self._apply_button.setToolTip("Apply the new settings")
        self._apply_button.clicked.connect(self.applySettings)
        self._apply_button.setDefault(True)

        self._close_button = QPushButton("Close")
        self._close_button.setToolTip("Hide this dialog")
        self._close_button.clicked.connect(self.hide)

        self._button_layout.addWidget(self._reset_button)
        self._button_layout.addStretch()
        self._button_layout.addWidget(self._undo_button)
        self._button_layout.addWidget(self._redo_button)
        self._button_layout.addWidget(self._copy_from_button)
        self._button_layout.addWidget(self._copy_to_button)
        self._button_layout.addStretch()
        self._button_layout.addWidget(self._apply_button)
        self._button_layout.addWidget(self._close_button)

        layout.addStretch()
        layout.addLayout(self._button_layout)

        self.setLayout(layout)
Exemple #60
0
    def __init__(self, bpms = None, cors = None, parent = None):
        super(OrbitCorrDlg, self).__init__(parent)
        # add bpms
        bpmls = bpms
        if bpms is None:
            bpmls = getElements("BPM")
        bpmls = [bpm for bpm in bpmls if bpm.isEnabled()]
        pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in bpmls]
        pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in bpmls]
        #
        #self._update_current_orbit()

        s = [bpm.sb for bpm in bpmls]
        self.bpm_plot = ApCaArrayPlot([pvx, pvy], x = [s, s])
        magprof = getBeamlineProfile()
        self.bpm_plot.setMagnetProfile(magprof)

        self.xc = Qwt.QwtPlotCurve()
        self.xc.setTitle("Target X")
        self.xc.attach(self.bpm_plot)
        #self.xc.setData(s, self.x0)
        self.bpm_plot.showCurve(self.xc, True)

        self.yc = Qwt.QwtPlotCurve()
        self.yc.setTitle("Target Y")
        self.yc.attach(self.bpm_plot)
        #self.yc.setData(s, self.y0)
        self.bpm_plot.showCurve(self.yc, True)

        #self.bpm_plot._cheat = [Qwt.QwtPlotCurve(), Qwt.QwtPlotCurve()]
        #self.bpm_plot._cheat[0].setTitle("_CHEAT_ X")
        #self.bpm_plot._cheat[1].setTitle("_CHEAT_ Y")
        #self.bpm_plot._cheat[0].attach(self.bpm_plot)
        #self.bpm_plot._cheat[1].attach(self.bpm_plot)
        #self.bpm_plot._set_symbol(self.bpm_plot._cheat[0],
        #                          Qwt.QwtSymbol.Triangle, dsize=2)
        #self.bpm_plot._set_symbol(self.bpm_plot._cheat[1],
        #                          Qwt.QwtSymbol.Diamond, dsize=2)
        #self.bpm_plot.showCurve(self.bpm_plot._cheat[0], False)
        #self.bpm_plot.showCurve(self.bpm_plot._cheat[1], False)
        self.bpm_plot.setContentsMargins(12, 10, 10, 10)

        # add corrector plots
        corls = cors
        if cors is None:
            corls = []
            for c in getElements("HCOR") + getElements("VCOR"):
                if c not in corls:
                    corls.append(c)
        pvx = [c.pv(field="x", handle="setpoint")[0]
               for c in getElements("HCOR") if c in corls]
        pvy = [c.pv(field="y", handle="setpoint")[0]
               for c in getElements("VCOR") if c in corls]
        s = [c.sb for c in corls]
        self.cor_plot = ApCaArrayPlot([pvx, pvy], x = [s, s],
                                      labels=["HCOR Sp", "VCOR Sp"])
        #magprof = aphla.getBeamlineProfile()
        self.cor_plot.setMagnetProfile(magprof)
        self.cor_plot.setContentsMargins(12, 10, 10, 10)
        #self.cor_plot.setMinimumHeight(200)
        #self.cor_plot.setMaximumHeight(250)
        #print s, pvx

        # add twiss plots
        self._twiss = getTwiss("*", ["s", "betax", "betay", "etax"])
        #for i in range(len(self._twiss)):
        #    print i, self._twiss[i,0], self._twiss[i,1]

        self.tw_plot = ApCaPlot()
        cbetax = Qwt.QwtPlotCurve()
        pen = cbetax.pen()
        pen.setColor(Qt.red)
        cbetax.setPen(pen)
        cbetay = Qwt.QwtPlotCurve()
        pen.setColor(Qt.green)
        cbetay.setPen(pen)
        cetax  = Qwt.QwtPlotCurve()
        pen.setColor(Qt.blue)
        cetax.setPen(pen)
        cbetax.setData(self._twiss[:,0], self._twiss[:,1])
        cbetay.setData(self._twiss[:,0], self._twiss[:,2])
        cetax.setData(self._twiss[:,0], 10.0*self._twiss[:,3])
        cbetax.attach(self.tw_plot)
        cbetax.setTitle("Beta X")
        cbetay.attach(self.tw_plot)
        cbetay.setTitle("Beta Y")
        cetax.attach( self.tw_plot)
        cetax.setTitle("10*Eta X")
        self.tw_plot.setMagnetProfile(magprof)
        self.tw_plot.setContentsMargins(12, 10, 10, 10)
        self.tw_plot.showCurve(cbetax, True)
        self.tw_plot.showCurve(cbetay, True)
        self.tw_plot.showCurve(cetax, True)

        # top tabs for plotting
        tabs = QtGui.QTabWidget()
        tabs.addTab(self.bpm_plot, "Orbit")
        tabs.addTab(self.cor_plot, "Correctors")
        tabs.addTab(self.tw_plot, "Twiss (Design)")
        tabs.setMinimumHeight(200)
        tabs.setMaximumHeight(280)

        layout = QVBoxLayout()
        layout.addWidget(tabs, 1)

        tabs = QtGui.QTabWidget()
        tab_general_cor = OrbitCorrGeneral(bpmls, corls)
        self.connect(tab_general_cor,
                     SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"),
                     self._update_orbit_plot)
        xobt, yobt = tab_general_cor.getTargetOrbit()
        self._update_orbit_plot(xobt, yobt)
        tabs.addTab(tab_general_cor, "General Bump")

        tab_bump3xcor = Bump3XCor(corls, "x")
        tab_bump3xsrc = Bump3XSrc(corls, "x")
        tab_bump4xcor = Bump4XCor(corls, "x")
        tab_bump4xsrc = Bump4XSrc(corls, "x")
        #plots=[self.bpm_plot, self.cor_plot, self.tw_plot])
        #self.connect(tab_nbump_cor,
        #             SIGNAL("correctorChanged(PyQt_PyObject)"),
        #             self._update_corr_plot)
        tabs.addTab(tab_bump3xcor, "3 Cors. dI")
        tabs.addTab(tab_bump3xsrc, "3 Cors. dX")
        tabs.addTab(tab_bump4xcor, "4 Cors. dI")
        tabs.addTab(tab_bump4xsrc, "4 Cors. dX dTheta")
        layout.addWidget(tabs, 3)

        self.connect(tab_bump3xcor, SIGNAL("zoomInCorrectors(PyQt_PyObject)"),
                     self._zoom_in_cors)
        self.connect(tab_bump3xsrc, SIGNAL("zoomInCorrectors(PyQt_PyObject)"),
                     self._zoom_in_cors)
        self.connect(tab_bump4xcor, SIGNAL("zoomInCorrectors(PyQt_PyObject)"),
                     self._zoom_in_cors)
        self.connect(tab_bump4xsrc, SIGNAL("zoomInCorrectors(PyQt_PyObject)"),
                     self._zoom_in_cors)

        self.connect(tab_bump3xcor, SIGNAL("clearCorrectors(PyQt_PyObject)"),
                     self._clear_cors)
        self.connect(tab_bump3xsrc, SIGNAL("clearCorrectors(PyQt_PyObject)"),
                     self._clear_cors)
        self.connect(tab_bump4xcor, SIGNAL("clearCorrectors(PyQt_PyObject)"),
                     self._clear_cors)
        self.connect(tab_bump4xsrc, SIGNAL("clearCorrectors(PyQt_PyObject)"),
                     self._clear_cors)

        #hln = QtGui.QFrame()
        #hln.setLineWidth(3)
        #hln.setFrameStyle(QtGui.QFrame.Sunken)
        #hln.setFrameShape(QtGui.QFrame.HLine)
        #layout.addWidget(hln)

        # the cheat button
        #hbox = QHBoxLayout()
        #hbox.addStretch()
        #btn = QPushButton("__CHEAT__")
        #self.connect(btn, SIGNAL("clicked()"), self._cheat)
        #hbox.addWidget(btn)
        #layout.addLayout(hbox)

        self.setLayout(layout)
        #self.update_orbit = update_orbit
        #self._x0 = tuple(x)  # save for reset
        #self._y0 = tuple(y)  # save for reset
        #self.val = [s, x, y]
        self.setMinimumWidth(1000)
        self.setWindowFlags(Qt.Window)