def __init__(self,broker,parent = None ):
     super(BrokerWidget,self).__init__(parent)
     
     self.broker = broker
     
     self.dataTable = TableView()
     self.dataTable.setModel(self.broker.dataModel)
     self.dataTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
     #self.dataTable.resizeColumnsToContents()
     dataLabel = QLabel('Price Data')
     dataLabel.setBuddy(self.dataTable)
     
     dataLayout = QVBoxLayout()
     
     dataLayout.addWidget(dataLabel)
     dataLayout.addWidget(self.dataTable)
     
     
     addButton = QPushButton("&Add Symbol")
     saveDataButton = QPushButton("&Save Data")
     #deleteButton = QPushButton("&Delete")
     
     buttonLayout = QVBoxLayout()
     buttonLayout.addWidget(addButton)
     buttonLayout.addWidget(saveDataButton)
     buttonLayout.addStretch()
     
     layout = QHBoxLayout()
     layout.addLayout(dataLayout)
     layout.addLayout(buttonLayout)
     self.setLayout(layout)
     
     self.connect(addButton,SIGNAL('clicked()'),self.addSubscription)
     self.connect(saveDataButton,SIGNAL('clicked()'),self.saveData)
Beispiel #2
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self, None)
        self._setupUi()
        self.model = MainWindowModel()
        self.nameTextBox = LineEdit(view=self.nameTextBoxView)
        self.helloLabel = TextHolder(view=self.helloLabelView)
        self.model.set_children(self.nameTextBox.model, self.helloLabel.model)
        self.randomNameButton.clicked.connect(self.model.select_random_name)
        self.sayHelloButton.clicked.connect(self.model.say_hello)
    
    def _setupUi(self):
        self.setWindowTitle(QCoreApplication.instance().applicationName())
        self.centralwidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.nameTextBoxView = QLineEdit(self.centralwidget)
        self.verticalLayout.addWidget(self.nameTextBoxView)
        self.helloLabelView = QLabel(self.centralwidget)
        self.verticalLayout.addWidget(self.helloLabelView)
        self.buttonLayout = QHBoxLayout()
        self.randomNameButton = QPushButton("Random Name", self.centralwidget)
        self.buttonLayout.addWidget(self.randomNameButton)
        self.sayHelloButton = QPushButton("Say Hello", self.centralwidget)
        self.buttonLayout.addWidget(self.sayHelloButton)
        self.verticalLayout.addLayout(self.buttonLayout)
        self.setCentralWidget(self.centralwidget)
Beispiel #3
0
class PDF(QWidget, Script):
  def __init__(self):
    Script.__init__(self, "pdf")
    self.type = "pdfviewer"
    
  def updateWidget(self):
    pass
  
  def start(self, args):
    self.args = args
    try:
      self.node = args["file"].value()
      f = self.node.open()
      buff = f.read()
      f.close()
      self.document = popplerqt4.Poppler.Document.loadFromData(buff)
    except:
      pass

  def g_display(self):
    QWidget.__init__(self)
    self.hbox = QHBoxLayout()
    self.hbox.setContentsMargins(0, 0, 0, 0)
    pdfPage = self.document.page(1)
    image = pdfPage.renderToImage()
    label = QLabel()
    label.setPixmap(QPixmap.fromImage(image))
    self.hbox.addWidget(label)
    self.setLayout(self.hbox)
 def __init__(self, previous_value=DEFAULT_CONF_LEVEL, parent=None):
     super(ChangeConfLevelDlg, self).__init__(parent)
     
     cl_label = QLabel("Global Confidence Level:")
     
     self.conf_level_spinbox = QDoubleSpinBox()
     self.conf_level_spinbox.setRange(50, 99.999 )
     self.conf_level_spinbox.setSingleStep(0.1)
     self.conf_level_spinbox.setSuffix(QString("%"))
     self.conf_level_spinbox.setValue(previous_value)
     self.conf_level_spinbox.setDecimals(1)
     
     buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     
     hlayout = QHBoxLayout()
     hlayout.addWidget(cl_label)
     hlayout.addWidget(self.conf_level_spinbox)
     vlayout = QVBoxLayout()
     vlayout.addLayout(hlayout)
     vlayout.addWidget(buttonBox)
     self.setLayout(vlayout)
     
     self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
     self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
     self.setWindowTitle("Change Confidence Level")
    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)
    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()
Beispiel #7
0
    def setupUi(self):
        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(0)

        self.__mainLayout = QVBoxLayout()
        self.__mainLayout.setContentsMargins(0, 40, 0, 40)
        self.__mainLayout.setSpacing(65)

        self.layout().addLayout(self.__mainLayout)

        self.setStyleSheet(WELCOME_WIDGET_BUTTON_STYLE)

        bottom_bar = QWidget(objectName="bottom-bar")
        bottom_bar_layout = QHBoxLayout()
        bottom_bar_layout.setContentsMargins(20, 10, 20, 10)
        bottom_bar.setLayout(bottom_bar_layout)
        bottom_bar.setSizePolicy(QSizePolicy.MinimumExpanding,
                                 QSizePolicy.Maximum)

        check = QCheckBox(self.tr("Show at startup"), bottom_bar)
        check.setChecked(False)

        self.__showAtStartupCheck = check

        bottom_bar_layout.addWidget(check, alignment=Qt.AlignVCenter | \
                                    Qt.AlignLeft)

        self.layout().addWidget(bottom_bar, alignment=Qt.AlignBottom,
                                stretch=1)

        self.setSizeGripEnabled(False)
        self.setFixedSize(620, 390)
Beispiel #8
0
    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)
    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)
    def __init__(self, suggested, parent=None):
        super(PythonDetectDialog, self).__init__(parent, Qt.Dialog)
        self.setMaximumSize(QSize(0, 0))
        self.setWindowTitle("Configure Python Path")

        vbox = QVBoxLayout(self)

        lblMessage = QLabel(self.tr("We have detected that you are using " +
            "Windows,\nplease choose the proper " +
            "Python application for you:"))
        vbox.addWidget(lblMessage)

        self.listPaths = QListWidget()
        self.listPaths.setSelectionMode(QListWidget.SingleSelection)
        vbox.addWidget(self.listPaths)

        hbox = QHBoxLayout()
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        btnCancel = QPushButton(self.tr("Cancel"))
        btnAccept = QPushButton(self.tr("Accept"))
        hbox.addWidget(btnCancel)
        hbox.addWidget(btnAccept)
        vbox.addLayout(hbox)

        self.connect(btnAccept, SIGNAL("clicked()"), self._set_python_path)
        self.connect(btnCancel, SIGNAL("clicked()"), self.close)

        for path in suggested:
            self.listPaths.addItem(path)
        self.listPaths.setCurrentRow(0)
Beispiel #11
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("About SIDE-C"))
        self.setMaximumSize(QSize(0, 0))
        

        vbox = QVBoxLayout(self)

        #Create an icon for the Dialog
        # pixmap = QPixmap(":img/icon")
        # self.lblIcon = QLabel()
        # self.lblIcon.setPixmap(pixmap)

        hbox = QHBoxLayout()
        # hbox.addWidget(self.lblIcon)

        lblTitle = QLabel(
                '<h1>SIDE - C</h1>\n<i>Simple Integrated Development Environment for C<i>')
        lblTitle.setTextFormat(Qt.RichText)
        lblTitle.setAlignment(Qt.AlignLeft)
        hbox.addWidget(lblTitle)
        vbox.addLayout(hbox)
        #Add description
        vbox.addWidget(QLabel(
self.tr("""ALGO ACA""")))
        vbox.addWidget(QLabel("Hola"))
        link_ninja = QLabel(
            self.tr('Website: '))
        vbox.addWidget(link_ninja)
        link_source = QLabel(
            self.tr('Source Code'))
        vbox.addWidget(link_source)
Beispiel #12
0
    def  __init__(self, image_width, image_height, parent=None):
        super(UserButtonMenu, self).__init__(parent)
        
        self.image_width = image_width
        self.image_height = image_height

        self.label = QLabel(self)
        self.label.setScaledContents(True)
        self.label.setSizePolicy(
                QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored))

        self.imageLabel = QLabel(self)
        self.imageLabel.setScaledContents(True)
        self.imageLabel.setSizePolicy(
                QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        self.setSizePolicy(
                QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        self.userMenu = QMenu('user accounts menu') # TODO Remove magic

        hbox = QHBoxLayout()
        hbox.addWidget(self.imageLabel)
        hbox.addWidget(self.label)
        self.setLayout(hbox)
        self.setMenu(self.userMenu)
Beispiel #13
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)
Beispiel #14
0
class EkdPathPropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à un chemin
    """
    def __init__(self, prop, name, value, section=None ):
        super(EkdPathPropertie, self).__init__(prop, name, value, EkdPropertie.PATH, section)
        self.label = QLabel(name)
        self.widget = QFrame()
        self.layout = QHBoxLayout(self.widget)
        self.line = QLineEdit(value)
        self.line.setReadOnly(True)
        self.layout.addWidget(self.line)
        self.boutton = QPushButton(u"...")
        self.boutton.setFixedSize(25,25)
        self.layout.addWidget(self.boutton)

        # Quand on clique sur le boutton on défini le path
        self.connect(self.boutton, SIGNAL("clicked()"), self.updatePath)

    def updatePath(self):
        newpath = QFileDialog.getExistingDirectory(None, _(u"Choisissez un chemin"), self.value )
        if newpath:
            self.value = newpath
            self.line.setText(self.value)
            EkdConfig.set(self.section, self.id, self.value)
Beispiel #15
0
class EkdColorPropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à une Couleur
    """
    def __init__(self, prop, name, value, section=None ):
        super(EkdColorPropertie, self).__init__(prop, name, value, EkdPropertie.COLOR, section)
        self.label = QLabel(name)
        self.widget = QFrame()
        self.layout = QHBoxLayout(self.widget)
        self.line = QLineEdit(value)
        self.value = value
        self.line.setReadOnly(True)
        self.layout.addWidget(self.line)
        self.color = QPixmap(15, 15)
        self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16))))
        self.boutton = QPushButton(QIcon(self.color), u"")
        self.boutton.setFixedSize(25,25)
        self.layout.addWidget(self.boutton)

        # Quand on clique sur le boutton on défini la couleur
        self.connect(self.boutton, SIGNAL("clicked()"), self.updateColor)

    def updateColor(self):
        newcolor = QColorDialog.getColor(QColor.fromRgb(int("%d" % int(self.value, 16))), None )# Non supporté sous Jaunty ??
        if newcolor.isValid():
            self.value = str("%x" % newcolor.rgb())[2:]
            self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16))))
            self.boutton.setIcon(QIcon(self.color))
            self.line.setText(self.value)
            EkdConfig.set(self.section, self.id, self.value)
Beispiel #16
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)
Beispiel #17
0
    def __init__(self):
        QWidget.__init__(self)
        self.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.setMinimumHeight(38)
        hbox = QHBoxLayout(self)
        self.btnPrevious = QPushButton(QIcon(resources.IMAGES["nav-code-left"]), "")
        self.btnPrevious.setObjectName("navigation_button")
        self.btnPrevious.setToolTip(self.tr("Right click to change navigation options"))
        self.btnNext = QPushButton(QIcon(resources.IMAGES["nav-code-right"]), "")
        self.btnNext.setObjectName("navigation_button")
        self.btnNext.setToolTip(self.tr("Right click to change navigation options"))
        hbox.addWidget(self.btnPrevious)
        hbox.addWidget(self.btnNext)
        self.setContentsMargins(0, 0, 0, 0)

        self.menuNavigate = QMenu(self.tr("Navigate"))
        self.codeAction = self.menuNavigate.addAction(self.tr("Code Jumps"))
        self.codeAction.setCheckable(True)
        self.codeAction.setChecked(True)
        self.bookmarksAction = self.menuNavigate.addAction(self.tr("Bookmarks"))
        self.bookmarksAction.setCheckable(True)
        self.breakpointsAction = self.menuNavigate.addAction(self.tr("Breakpoints"))
        self.breakpointsAction.setCheckable(True)

        # 0 = Code Jumps
        # 1 = Bookmarks
        # 2 = Breakpoints
        self.operation = 0

        self.connect(self.codeAction, SIGNAL("triggered()"), self._show_code_nav)
        self.connect(self.breakpointsAction, SIGNAL("triggered()"), self._show_breakpoints)
        self.connect(self.bookmarksAction, SIGNAL("triggered()"), self._show_bookmarks)
    def __init__(self, symbol, color, parent = None):

        QFrame.__init__(self, parent)
        self._symbol = symbol
        self.backColor = color

        # define and set stylesheets
        self.setup_stylesheets()
        self.setStyleSheet(self._theStyleSheet)

        # layout
        layout    = QHBoxLayout()
        layout.setContentsMargins( 0, 0, 0, 0 )
        self.setToolTip(symbol["description"])

        # add the symbol's svg
        svgWidget = QSvgWidget(symbol["svgPath"]) 
        svgWidth = int(symbol["width"])
        self.setMinimumWidth(svgWidth * 25)
        self.setMaximumWidth(svgWidth * 25)
        self.setMinimumHeight(25)
        self.setMaximumHeight(25)

        layout.addWidget(svgWidget)
        self.setLayout(layout)
Beispiel #19
0
    def __init__(self):
        QWidget.__init__(self)

        self.__filter_popup = FilterPopup(self)
        self.__filter_popup.filterSettingsChanged.connect(self.onItemChanged)

        layout = QVBoxLayout()

        self.model = DataTypeKeysListModel()
        self.filter_model = DataTypeProxyModel(self.model)

        filter_layout = QHBoxLayout()

        self.search_box = SearchBox()
        self.search_box.filterChanged.connect(self.setSearchString)
        filter_layout.addWidget(self.search_box)

        filter_popup_button = QToolButton()
        filter_popup_button.setIcon(util.resourceIcon("ide/cog_edit.png"))
        filter_popup_button.clicked.connect(self.showFilterPopup)
        filter_layout.addWidget(filter_popup_button)
        layout.addLayout(filter_layout)

        self.data_type_keys_widget = QListView()
        self.data_type_keys_widget.setModel(self.filter_model)
        self.data_type_keys_widget.selectionModel().selectionChanged.connect(self.itemSelected)

        layout.addSpacing(15)
        layout.addWidget(self.data_type_keys_widget, 2)
        layout.addStretch()

        # layout.addWidget(Legend("Default types", DataTypeKeysListModel.DEFAULT_DATA_TYPE))
        layout.addWidget(Legend("Observations available", DataTypeKeysListModel.HAS_OBSERVATIONS))

        self.setLayout(layout)
	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")
Beispiel #21
0
    def __init__(self, parent=None, icon=QIcon(), text="", wordWrap=False,
                 textFormat=Qt.AutoText, standardButtons=NoButton, **kwargs):
        super().__init__(parent, **kwargs)
        self.__text = text
        self.__icon = QIcon()
        self.__wordWrap = wordWrap
        self.__standardButtons = MessageWidget.NoButton
        self.__buttons = []

        layout = QHBoxLayout()
        layout.setContentsMargins(8, 0, 8, 0)

        self.__iconlabel = QLabel(objectName="icon-label")
        self.__iconlabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.__textlabel = QLabel(objectName="text-label", text=text,
                                  wordWrap=wordWrap, textFormat=textFormat)

        if sys.platform == "darwin":
            self.__textlabel.setAttribute(Qt.WA_MacSmallSize)

        layout.addWidget(self.__iconlabel)
        layout.addWidget(self.__textlabel)

        self.setLayout(layout)
        self.setIcon(icon)
        self.setStandardButtons(standardButtons)
 def __init__(self, parent_widget):
     super(CalibrationConfigView, self).__init__(parent=parent_widget)
     btn = QPushButton("Push")
     btn.clicked.connect(self.btnClick)
     layout = QHBoxLayout()
     layout.addWidget(btn)
     self.setLayout(layout)
Beispiel #23
0
    def createWidgets(self, window):
        self.widget = QWidget()
        layout = QVBoxLayout()
        self.widget.setLayout(layout)

        grid = QGridLayout()

        grid.addWidget(QLabel(tr("Label:")), 0, 0)

        self.label = QLineEdit(u"label")
        grid.addWidget(self.label, 0, 1)

        grid.addWidget(QLabel(tr("Type:")), 1, 0)

        self.game_types = QComboBox()
        grid.addWidget(self.game_types, 1, 1)
        layout.addLayout(grid)

        spacer = createVerticalSpacer()
        layout.addItem(spacer)

        button_box = QHBoxLayout()
        layout.addLayout(button_box)

        refresh = QPushButton('&Create')
        button_box.addWidget(refresh)
        window.connect(refresh, SIGNAL('clicked()'), self.create)

        leave = QPushButton('&Leave')
        button_box.addWidget(leave)
        window.connect(leave, SIGNAL('clicked()'), self.abort)
Beispiel #24
0
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.setContentsMargins(0, 0, 0, 0)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(1)
        self._setNameLineEdit = QLineEdit(self)
        layout.addWidget(self._setNameLineEdit)

        self._setListView = QListView(self)
        self._listModel = QStandardItemModel(self)
        self._proxyModel = QSortFilterProxyModel(self)
        self._proxyModel.setSourceModel(self._listModel)

        self._setListView.setModel(self._proxyModel)
        self._setListView.setItemDelegate(ListItemDelegate(self))

        self._setNameLineEdit.textChanged.connect(
            self._proxyModel.setFilterFixedString)

        self._completer = QCompleter(self._listModel, self)

        self._setNameLineEdit.setCompleter(self._completer)

        self._listModel.itemChanged.connect(self._onSetNameChange)
        layout.addWidget(self._setListView)
        buttonLayout = QHBoxLayout()

        self._addAction = QAction(
            "+", self, toolTip="Add a new sort key")
        self._updateAction = QAction(
            "Update", self, toolTip="Update/save current selection")
        self._removeAction = QAction(
            "\u2212", self, toolTip="Remove selected sort key.")

        self._addToolButton = QToolButton(self)
        self._updateToolButton = QToolButton(self)
        self._removeToolButton = QToolButton(self)
        self._updateToolButton.setSizePolicy(
                QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)

        self._addToolButton.setDefaultAction(self._addAction)
        self._updateToolButton.setDefaultAction(self._updateAction)
        self._removeToolButton.setDefaultAction(self._removeAction)

        buttonLayout.addWidget(self._addToolButton)
        buttonLayout.addWidget(self._updateToolButton)
        buttonLayout.addWidget(self._removeToolButton)

        layout.addLayout(buttonLayout)
        self.setLayout(layout)

        self._addAction.triggered.connect(self.addCurrentSelection)
        self._updateAction.triggered.connect(self.updateSelectedSelection)
        self._removeAction.triggered.connect(self.removeSelectedSelection)

        self._setListView.selectionModel().selectionChanged.connect(
            self._onListViewSelectionChanged)
        self.selectionModel = None
        self._selections = []
Beispiel #25
0
    def __init__(self, wintitle="guiqwt plot", icon="guiqwt.png",
                 toolbar=False, options=None, parent=None, panels=None):
        QDialog.__init__(self, parent)
        self.setWindowFlags(Qt.Window)

        # WidgetMixin copy
        PlotManager.__init__(self, main=self)
        
        self.main_layout = QVBoxLayout(self)
        self.color_layout = QHBoxLayout()
        self.plot_layout = QGridLayout()
        self.option_layout = QHBoxLayout()

        self.plot_widget = None

        if panels is not None:
            for panel in panels:
                self.add_panel(panel)

        self.toolbar = QToolBar(_("Tools"))
        if not toolbar:
            self.toolbar.hide()

        # Configuring widget layout
        self._setup_widget_properties(wintitle=wintitle, icon=icon)
        self._setup_widget_layout()
        
        # Options
        self.option_callbacks = {}
        self.legend = None
Beispiel #26
0
    def __init__(self, parent=None, show_fullpath=True, fullpath_sorting=True,
                 show_all_files=True, show_comments=True):
        QWidget.__init__(self, parent)

        self.treewidget = OutlineExplorerTreeWidget(self,
                                            show_fullpath=show_fullpath,
                                            fullpath_sorting=fullpath_sorting,
                                            show_all_files=show_all_files,
                                            show_comments=show_comments)

        self.visibility_action = create_action(self,
                                           _("Show/hide outline explorer"),
                                           icon='outline_explorer_vis.png',
                                           toggled=self.toggle_visibility)
        self.visibility_action.setChecked(True)
        
        btn_layout = QHBoxLayout()
        btn_layout.setAlignment(Qt.AlignRight)
        for btn in self.setup_buttons():
            btn_layout.addWidget(btn)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.treewidget)
        layout.addLayout(btn_layout)
        self.setLayout(layout)
 def _fill_environment_box(self):
     
     # Main Layout
     main_lo = QVBoxLayout()        
     self.environment_gb.setLayout(main_lo)
             
     # Combobox
     lo, self.env_select_cb, lab = GBuilder().label_combobox(self, "Current Environment:", [], self._env_select_changed)
     hl = QHBoxLayout()
     hl.addLayout(lo)
     but = GBuilder().pushbutton(self, "New", self._new_env_hit)
     but.setFixedWidth(40)
     hl.addWidget(but)        
     lab.setFixedWidth(140)
     self.env_select_cb.setFixedHeight(22)  
     self.env_select_cb.setFixedWidth(350)      
     main_lo.addLayout(hl)
     
     # Groupbox (to make it look nicer)
     self.content_gb = EnvironmentView(self.environment_gb)    
     main_lo.addWidget(self.content_gb)
     self.content_gb.setFixedHeight(550)  
     self.content_gb.setFixedWidth(1000)  
     self.content_gb.setLayout(lo)
     
     # QStackedWidget with environments
     self.stacked_env = QStackedWidget()
     lo.addWidget(self.stacked_env)
Beispiel #28
0
    def __init__(self, parent):
        super(ManualInstallWidget, self).__init__()
        self._parent = parent
        vbox = QVBoxLayout(self)
        form = QFormLayout()
        self._txtName = QLineEdit()
        self._txtVersion = QLineEdit()
        form.addRow(self.tr("Plugin Name:"), self._txtName)
        form.addRow(self.tr("Plugin Version:"), self._txtVersion)
        vbox.addLayout(form)
        hPath = QHBoxLayout()
        self._txtFilePath = QLineEdit()
        self._btnFilePath = QPushButton(QIcon(":img/open"), '')
        hPath.addWidget(QLabel(self.tr("Plugin File:")))
        hPath.addWidget(self._txtFilePath)
        hPath.addWidget(self._btnFilePath)
        vbox.addLayout(hPath)
        vbox.addSpacerItem(QSpacerItem(0, 1, QSizePolicy.Expanding,
            QSizePolicy.Expanding))

        hbox = QHBoxLayout()
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        self._btnInstall = QPushButton(self.tr("Install"))
        hbox.addWidget(self._btnInstall)
        vbox.addLayout(hbox)

        #Signals
        self.connect(self._btnFilePath,
            SIGNAL("clicked()"), self._load_plugin_path)
        self.connect(self._btnInstall, SIGNAL("clicked()"),
            self.install_plugin)
Beispiel #29
0
 def __init__(self, parent):
     super(MainWidget, self).__init__(parent)
     
     self.dataDirLineEdit = QLineEdit()
     self.dataLabel = QLabel(self.tr("Data Directory:"))
     self.dataLabel.setBuddy(self.dataDirLineEdit)
     self.dataBrowseButton = QPushButton(self.tr("&Browse..."))
     self.connect(self.dataBrowseButton, SIGNAL('clicked()'), parent.browseClicked)
          
     self.closeButton = QPushButton(self.tr("Close"))
     self.connect(self.closeButton, SIGNAL('clicked()'), parent.onClose)
     
     self.trainButton = QPushButton(self.tr("&Train"))
     self.connect(self.trainButton, SIGNAL('clicked()'), parent.trainClicked)
     
     self.textBrowser = QTextBrowser()
             
     self.dataLayout = QHBoxLayout()
     self.dataLayout.addWidget(self.dataLabel)
     self.dataLayout.addWidget(self.dataDirLineEdit)
     self.dataLayout.addWidget(self.dataBrowseButton)
     
     self.buttonLayout = QHBoxLayout()
     self.buttonLayout.addWidget(self.closeButton)
     self.buttonLayout.addWidget(self.trainButton)
     
     self.mainLayout = QVBoxLayout()
     self.mainLayout.addLayout(self.dataLayout)
     self.mainLayout.addWidget(self.textBrowser)
     self.mainLayout.addLayout(self.buttonLayout)
     
     self.setLayout(self.mainLayout)    
Beispiel #30
0
    def test_toolbox(self):

        w = QWidget()
        layout = QHBoxLayout()

        reg = global_registry()
        qt_reg = QtWidgetRegistry(reg)

        triggered_actions = []

        model = qt_reg.model()

        file_action = qt_reg.action_for_widget(
            "Orange.widgets.data.owfile.OWFile"
        )

        box = WidgetToolBox()
        box.setModel(model)
        box.triggered.connect(triggered_actions.append)
        layout.addWidget(box)

        box.setButtonSize(QSize(50, 80))

        w.setLayout(layout)
        w.show()

        file_action.trigger()

        box.setButtonSize(QSize(60, 80))
        box.setIconSize(QSize(35, 35))
        box.setTabButtonHeight(40)
        box.setTabIconSize(QSize(30, 30))

        self.app.exec_()
Beispiel #31
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self._main_container = main_container.MainContainer()
        self._explorer_container = explorer_container.ExplorerContainer()
        self._result_widget = FindInFilesResult()
        self._open_find_button = QPushButton(self.tr("Find!"))
        self._stop_button = QPushButton(self.tr("Stop"))
        self._clear_button = QPushButton(self.tr("Clear!"))
        self._replace_button = QPushButton(self.tr("Replace"))
        self._find_widget = FindInFilesDialog(self._result_widget, self)
        self._error_label = QLabel(self.tr("No Results"))
        self._error_label.setVisible(False)
        #Replace Area
        self.replace_widget = QWidget()
        hbox_replace = QHBoxLayout(self.replace_widget)
        hbox_replace.setContentsMargins(0, 0, 0, 0)
        self.lbl_replace = QLabel(self.tr("Replace results with:"))
        self.lbl_replace.setTextFormat(Qt.PlainText)
        self.replace_edit = QLineEdit()
        hbox_replace.addWidget(self.lbl_replace)
        hbox_replace.addWidget(self.replace_edit)
        self.replace_widget.setVisible(False)
        #Main Layout
        main_hbox = QHBoxLayout(self)
        #Result Layout
        tree_vbox = QVBoxLayout()
        tree_vbox.addWidget(self._result_widget)
        tree_vbox.addWidget(self._error_label)
        tree_vbox.addWidget(self.replace_widget)

        main_hbox.addLayout(tree_vbox)
        #Buttons Layout
        vbox = QVBoxLayout()
        vbox.addWidget(self._open_find_button)
        vbox.addWidget(self._stop_button)
        vbox.addWidget(self._clear_button)
        vbox.addSpacerItem(
            QSpacerItem(0, 50, QSizePolicy.Fixed, QSizePolicy.Expanding))
        vbox.addWidget(self._replace_button)
        main_hbox.addLayout(vbox)

        self._open_find_button.setFocus()
        #signals
        self.connect(self._open_find_button, SIGNAL("clicked()"), self.open)
        self.connect(self._stop_button, SIGNAL("clicked()"), self._find_stop)
        self.connect(self._clear_button, SIGNAL("clicked()"),
                     self._clear_results)
        self.connect(self._result_widget,
                     SIGNAL("itemClicked(QTreeWidgetItem *, int)"),
                     self._go_to)
        self.connect(self._find_widget, SIGNAL("finished()"),
                     self._find_finished)
        self.connect(self._find_widget, SIGNAL("findStarted()"),
                     self._find_started)
        self.connect(self._replace_button, SIGNAL("clicked()"),
                     self._replace_results)
Beispiel #32
0
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletThermocouple, *args)

        self.thermo = self.device

        self.qtcb_error_state.connect(self.cb_error_state)
        self.thermo.register_callback(self.thermo.CALLBACK_ERROR_STATE,
                                      self.qtcb_error_state.emit)

        self.cbe_temperature = CallbackEmulator(self.thermo.get_temperature,
                                                self.cb_temperature,
                                                self.increase_error_count)

        self.temperature_label = TemperatureLabel()

        self.current_value = None

        plot_list = [['', Qt.red, self.get_current_value]]
        self.plot_widget = PlotWidget('Temperature [%cC]' % 0xB0, plot_list)

        self.averaging_label = QLabel('Averaging:')
        self.averaging_combo = QComboBox()
        self.averaging_combo.addItem('1 sample')
        self.averaging_combo.addItem('2 samples')
        self.averaging_combo.addItem('4 samples')
        self.averaging_combo.addItem('8 samples')
        self.averaging_combo.addItem('16 samples')

        self.type_label = QLabel('Thermocouple Type:')
        self.type_combo = QComboBox()
        self.type_combo.addItem('B')
        self.type_combo.addItem('E')
        self.type_combo.addItem('J')
        self.type_combo.addItem('K')
        self.type_combo.addItem('N')
        self.type_combo.addItem('R')
        self.type_combo.addItem('S')
        self.type_combo.addItem('T')
        self.type_combo.addItem('Gain 8')
        self.type_combo.addItem('Gain 32')

        self.filter_label = QLabel('Noise Rejection Filter:')
        self.filter_combo = QComboBox()
        self.filter_combo.addItem('50Hz')
        self.filter_combo.addItem('60Hz')

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        self.error_label = QLabel('Current errors: None')

        layout_conf = QHBoxLayout()
        layout_conf.addWidget(self.averaging_label)
        layout_conf.addWidget(self.averaging_combo)
        layout_conf.addStretch()
        layout_conf.addWidget(self.type_label)
        layout_conf.addWidget(self.type_combo)
        layout_conf.addStretch()
        layout_conf.addWidget(self.filter_label)
        layout_conf.addWidget(self.filter_combo)

        layout_error = QHBoxLayout()
        layout_error.addStretch()
        layout_error.addWidget(self.error_label)
        layout_error.addStretch()

        layout_h = QHBoxLayout()
        layout_h.addStretch()
        layout_h.addWidget(self.temperature_label)
        layout_h.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h)
        layout.addWidget(self.plot_widget)
        layout.addLayout(layout_conf)
        layout.addWidget(line)
        layout.addLayout(layout_error)

        self.averaging_combo.currentIndexChanged.connect(
            self.configuration_changed)
        self.type_combo.currentIndexChanged.connect(self.configuration_changed)
        self.filter_combo.currentIndexChanged.connect(
            self.configuration_changed)
    def __init__(self, parent, distanceUnit, distanceUnit1=None):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("DistanceBoxPanel" +
                           str(len(parent.findChildren(DistanceBoxPanel))))

        self.distanceUnit = distanceUnit
        self.distanceUnit1 = distanceUnit1

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.frameBoxPanelIn = QFrame(self.frameBoxPanel)
        self.frameBoxPanelIn.setFrameShape(QFrame.StyledPanel)
        self.frameBoxPanelIn.setFrameShadow(QFrame.Raised)
        self.frameBoxPanelIn.setObjectName(("frameBoxPanelIn"))
        self.hLayoutframeBoxPanelIn = QHBoxLayout(self.frameBoxPanelIn)
        self.hLayoutframeBoxPanelIn.setSpacing(0)
        self.hLayoutframeBoxPanelIn.setMargin(0)
        self.hLayoutframeBoxPanelIn.setObjectName(("hLayoutframeBoxPanelIn"))

        self.txtDistance = QLineEdit(self.frameBoxPanelIn)
        self.txtDistance.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtDistance.setFont(font)
        self.txtDistance.setObjectName(self.objectName() + "_txtDistance")
        self.txtDistance.setText("0.0")
        self.txtDistance.setMinimumWidth(70)
        self.txtDistance.setMaximumWidth(70)
        self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance)

        if self.distanceUnit1 != None:
            labelM = QLabel(self.frameBoxPanelIn)
            labelM.setObjectName(("labelM"))
            value = ""
            if self.distanceUnit == DistanceUnits.NM:
                value = " nm "
            elif self.distanceUnit == DistanceUnits.M:
                value = " m "
            elif self.distanceUnit == DistanceUnits.KM:
                value = " km "
            elif self.distanceUnit == DistanceUnits.FT:
                value = " ft "
            elif self.distanceUnit == DistanceUnits.MM:
                value = " mm "
            else:
                value = ""
            labelM.setText(value)
            self.hLayoutframeBoxPanelIn.addWidget(labelM)

            self.txtDistance1 = QLineEdit(self.frameBoxPanelIn)
            self.txtDistance1.setEnabled(True)
            font = QFont()
            font.setBold(False)
            font.setWeight(50)
            self.txtDistance1.setFont(font)
            self.txtDistance1.setObjectName(self.objectName() +
                                            "_txtDistance1")
            self.txtDistance1.setText("0.0")
            self.txtDistance1.setMinimumWidth(70)
            self.txtDistance1.setMaximumWidth(70)
            self.txtDistance1.setText("0.0")
            self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance1)

            label1 = QLabel(self.frameBoxPanelIn)
            label1.setObjectName(("labelFt"))
            value = ""
            if self.distanceUnit1 == DistanceUnits.NM:
                value = " nm "
            elif self.distanceUnit1 == DistanceUnits.M:
                value = " m "
            elif self.distanceUnit1 == DistanceUnits.KM:
                value = " km "
            elif self.distanceUnit1 == DistanceUnits.FT:
                value = " ft "
            elif self.distanceUnit1 == DistanceUnits.MM:
                value = " mm "
            else:
                value = ""
            label1.setText(value)
            self.hLayoutframeBoxPanelIn.addWidget(label1)

            # self.txtDistance.textChanged.connect(self.txtDistanceChanged)
            self.txtDistance1.textChanged.connect(self.txtDistance1Changed)
            self.txtDistance1.editingFinished.connect(
                self.txtDistanceEditingFinished)

        self.btnCaptureDistance = QToolButton(self.frameBoxPanelIn)
        self.btnCaptureDistance.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")),
                       QIcon.Normal, QIcon.Off)
        self.btnCaptureDistance.setIcon(icon)
        self.btnCaptureDistance.setObjectName(("btnDegreeBoxPanel"))
        self.hLayoutframeBoxPanelIn.addWidget(self.btnCaptureDistance)

        self.hLayoutframeBoxPanel.addWidget(self.frameBoxPanelIn)
        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)

        self.txtDistance.textChanged.connect(self.txtDistanceChanged)
        self.txtDistance.editingFinished.connect(
            self.txtDistanceEditingFinished)
        self.btnCaptureDistance.clicked.connect(self.btnCaptureDistanceClicked)

        # self.value = 0.0

        self.flag = 0
        self.txtDistance.setText("0.0")
class DistanceBoxPanel(QWidget):
    def __init__(self, parent, distanceUnit, distanceUnit1=None):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("DistanceBoxPanel" +
                           str(len(parent.findChildren(DistanceBoxPanel))))

        self.distanceUnit = distanceUnit
        self.distanceUnit1 = distanceUnit1

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.frameBoxPanelIn = QFrame(self.frameBoxPanel)
        self.frameBoxPanelIn.setFrameShape(QFrame.StyledPanel)
        self.frameBoxPanelIn.setFrameShadow(QFrame.Raised)
        self.frameBoxPanelIn.setObjectName(("frameBoxPanelIn"))
        self.hLayoutframeBoxPanelIn = QHBoxLayout(self.frameBoxPanelIn)
        self.hLayoutframeBoxPanelIn.setSpacing(0)
        self.hLayoutframeBoxPanelIn.setMargin(0)
        self.hLayoutframeBoxPanelIn.setObjectName(("hLayoutframeBoxPanelIn"))

        self.txtDistance = QLineEdit(self.frameBoxPanelIn)
        self.txtDistance.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtDistance.setFont(font)
        self.txtDistance.setObjectName(self.objectName() + "_txtDistance")
        self.txtDistance.setText("0.0")
        self.txtDistance.setMinimumWidth(70)
        self.txtDistance.setMaximumWidth(70)
        self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance)

        if self.distanceUnit1 != None:
            labelM = QLabel(self.frameBoxPanelIn)
            labelM.setObjectName(("labelM"))
            value = ""
            if self.distanceUnit == DistanceUnits.NM:
                value = " nm "
            elif self.distanceUnit == DistanceUnits.M:
                value = " m "
            elif self.distanceUnit == DistanceUnits.KM:
                value = " km "
            elif self.distanceUnit == DistanceUnits.FT:
                value = " ft "
            elif self.distanceUnit == DistanceUnits.MM:
                value = " mm "
            else:
                value = ""
            labelM.setText(value)
            self.hLayoutframeBoxPanelIn.addWidget(labelM)

            self.txtDistance1 = QLineEdit(self.frameBoxPanelIn)
            self.txtDistance1.setEnabled(True)
            font = QFont()
            font.setBold(False)
            font.setWeight(50)
            self.txtDistance1.setFont(font)
            self.txtDistance1.setObjectName(self.objectName() +
                                            "_txtDistance1")
            self.txtDistance1.setText("0.0")
            self.txtDistance1.setMinimumWidth(70)
            self.txtDistance1.setMaximumWidth(70)
            self.txtDistance1.setText("0.0")
            self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance1)

            label1 = QLabel(self.frameBoxPanelIn)
            label1.setObjectName(("labelFt"))
            value = ""
            if self.distanceUnit1 == DistanceUnits.NM:
                value = " nm "
            elif self.distanceUnit1 == DistanceUnits.M:
                value = " m "
            elif self.distanceUnit1 == DistanceUnits.KM:
                value = " km "
            elif self.distanceUnit1 == DistanceUnits.FT:
                value = " ft "
            elif self.distanceUnit1 == DistanceUnits.MM:
                value = " mm "
            else:
                value = ""
            label1.setText(value)
            self.hLayoutframeBoxPanelIn.addWidget(label1)

            # self.txtDistance.textChanged.connect(self.txtDistanceChanged)
            self.txtDistance1.textChanged.connect(self.txtDistance1Changed)
            self.txtDistance1.editingFinished.connect(
                self.txtDistanceEditingFinished)

        self.btnCaptureDistance = QToolButton(self.frameBoxPanelIn)
        self.btnCaptureDistance.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")),
                       QIcon.Normal, QIcon.Off)
        self.btnCaptureDistance.setIcon(icon)
        self.btnCaptureDistance.setObjectName(("btnDegreeBoxPanel"))
        self.hLayoutframeBoxPanelIn.addWidget(self.btnCaptureDistance)

        self.hLayoutframeBoxPanel.addWidget(self.frameBoxPanelIn)
        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)

        self.txtDistance.textChanged.connect(self.txtDistanceChanged)
        self.txtDistance.editingFinished.connect(
            self.txtDistanceEditingFinished)
        self.btnCaptureDistance.clicked.connect(self.btnCaptureDistanceClicked)

        # self.value = 0.0

        self.flag = 0
        self.txtDistance.setText("0.0")

    def txtDistance1Changed(self):
        try:
            test = float(self.txtDistance1.text())
            if self.flag == 0:
                self.flag = 1
            if self.flag == 2:
                self.flag = 0
            if self.flag == 1:
                try:
                    self.txtDistance.setText(
                        str(
                            round(
                                Unit.ConvertNMToMeter(
                                    float(self.txtDistance1.text())), 4)))
                except:
                    self.txtDistance.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"." % (self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            self.txtDistance.setText("0.0")

    def txtDistanceEditingFinished(self):
        self.emit(SIGNAL("editingFinished"), self)

    def txtDistanceChanged(self):
        if self.distanceUnit1 != None:
            try:
                test = float(self.txtDistance.text())
                if self.flag == 0:
                    self.flag = 2
                if self.flag == 1:
                    self.flag = 0
                if self.flag == 2:
                    try:
                        self.txtDistance1.setText(
                            str(
                                round(
                                    Unit.ConvertMeterToNM(
                                        float(self.txtDistance.text())), 4)))
                    except:
                        self.txtDistance1.setText("0.0")
                    self.emit(SIGNAL("Event_0"), self)
            except:
                str0 = "You must input the float type in \"%s\"." % (
                    self.Caption)
                QMessageBox.warning(self, "Warning", str0)
                self.txtDistance1.setText("0.0")
        else:
            try:
                test = float(self.txtDistance.text())
                self.emit(SIGNAL("Event_0"), self)
            except:
                str0 = "You must input the float type in \"%s\"." % (
                    self.Caption)
                QMessageBox.warning(self, "Warning", str0)
                self.txtDistance.setText("0.0")

    def method_6(self, string_0):
        value = None
        if self.distanceUnit == DistanceUnits.NM:
            value = self.txtDistance.text() + "nm"
        elif self.distanceUnit == DistanceUnits.M:
            value = self.txtDistance.text() + "m"
        elif self.distanceUnit == DistanceUnits.KM:
            value = self.txtDistance.text() + "km"
        elif self.distanceUnit == DistanceUnits.FT:
            value = self.txtDistance.text() + "ft"
        elif self.distanceUnit == DistanceUnits.MM:
            value = self.txtDistance.text() + "mm"
        else:
            value = ""

        return "%s%s\t%s" % (string_0, self.Caption, value)

    def btnCaptureDistanceClicked(self):
        measureDistanceTool = MeasureTool(define._canvas, self.txtDistance,
                                          self.distanceUnit)
        define._canvas.setMapTool(measureDistanceTool)
        self.connect(measureDistanceTool, SIGNAL("captureFinished"),
                     self.txtDistanceEditingFinished)
        self.emit(SIGNAL("Event_1"), self)

    def get_CaptionUnits(self):
        return self.distanceUnit

    def set_CaptionUnits(self, distanceUnit):
        self.distanceUnit = distanceUnit

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        if self.distanceUnit1 == None:
            if self.distanceUnit == DistanceUnits.NM:
                value = captionStr + "(nm)"
            elif self.distanceUnit == DistanceUnits.M:
                value = captionStr + "(m)"
            elif self.distanceUnit == DistanceUnits.KM:
                value = captionStr + "(km)"
            elif self.distanceUnit == DistanceUnits.FT:
                value = captionStr + "(ft)"
            elif self.distanceUnit == DistanceUnits.MM:
                value = captionStr + "(mm)"
            else:
                value = ""
        else:
            value = captionStr
        self.captionLabel.setText(value + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_Value(self):
        try:
            return Distance(float(self.txtDistance.text()), self.distanceUnit)
        except:
            return Distance(0.0)

    def set_Value(self, distance):
        if distance == None:
            self.txtDistance.setText("0.0")
            # self.distanceUnit = DistanceUnits.NM
            return
        if isinstance(distance, Distance):
            if distance.IsNaN():
                self.txtDistance.setText("0.0")
                # self.distanceUnit = DistanceUnits.NM
                return
            if self.distanceUnit == DistanceUnits.NM:
                self.txtDistance.setText(str(round(distance.NauticalMiles, 4)))
                self.distanceUnit = DistanceUnits.NM
            elif self.distanceUnit == DistanceUnits.M:
                self.txtDistance.setText(str(round(distance.Metres, 4)))
                self.distanceUnit = DistanceUnits.M
            elif self.distanceUnit == DistanceUnits.KM:
                self.txtDistance.setText(str(round(distance.Kilometres, 4)))
                self.distanceUnit = DistanceUnits.KM
            elif self.distanceUnit == DistanceUnits.FT:
                self.txtDistance.setText(str(round(distance.Feet, 4)))
                self.distanceUnit = DistanceUnits.FT
            elif self.distanceUnit == DistanceUnits.MM:
                self.txtDistance.setText(str(int(distance.Milimeters)))
                self.distanceUnit = DistanceUnits.MM
            else:
                self.txtDistance.setText("0.0")
                self.distanceUnit = DistanceUnits.NM
        else:
            str0 = "You must input the type of \"Distance\" in \"%s\"." % (
                self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            self.txtDistance.setText("0.0")

    Value = property(get_Value, set_Value, None, None)

    def get_IsEmpty(self):
        return self.txtDistance.text() == "" or self.txtDistance.text() == None

    IsEmpty = property(get_IsEmpty, None, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_ReadOnly(self):
        return self.txtDistance.isReadOnly()

    def set_ReadOnly(self, bool):
        self.txtDistance.setReadOnly(bool)

    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def get_Enabled(self):
        return self.txtDistance.isEnabled()

    def set_Enabled(self, bool):
        self.txtDistance.setEnabled(bool)
        if self.distanceUnit1 != None:
            self.txtDistance1.setEnabled(bool)
        self.btnCaptureDistance.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.btnCaptureDistance.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.btnCaptureDistance.setIcon(icon)
        self.btnCaptureDistance.setVisible(True)

    Button = property(None, set_Button, None, None)
Beispiel #35
0
    def __init__(self,
                 image,
                 imageWidth,
                 connectClickedSlot,
                 nick='',
                 parent=None):
        QWidget.__init__(self, parent)

        self.connectClickedSlot = connectClickedSlot

        # Image
        self.image = QLabel(self)
        self.image.setPixmap(
            QPixmap(qtUtils.getAbsoluteImagePath(image)).scaledToWidth(
                imageWidth, Qt.SmoothTransformation))

        # Nick field
        self.nickLabel = QLabel("Nickname:", self)
        self.nickEdit = QLineEdit(nick, self)
        self.nickEdit.setMaxLength(constants.NICK_MAX_LEN)
        self.nickEdit.returnPressed.connect(self.__connectClicked)

        # Connect button
        self.connectButton = QPushButton("Connect", self)
        self.connectButton.resize(self.connectButton.sizeHint())
        self.connectButton.setAutoDefault(False)
        self.connectButton.clicked.connect(self.__connectClicked)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.nickLabel)
        hbox.addWidget(self.nickEdit)
        hbox.addStretch(1)

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.addWidget(self.connectButton)
        vbox.addStretch(1)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.image)
        hbox.addSpacing(10)
        hbox.addLayout(vbox)
        hbox.addStretch(1)

        self.setLayout(hbox)
Beispiel #36
0
class IO(QDockWidget):
    def __init__(self, mainWindow):
        super(IO, self).__init__()
        self.__mainWindow = mainWindow
        self.addAction()
        self.configure()
        self.io = self.initIO()
        self.sigout = "IOOUTputtext"
        self.connect(self, SIGNAL(self.sigout), self.puttextout)
        self.sigerr = "IOERRputtext"
        self.connect(self, SIGNAL(self.sigerr), self.puttexterr)
        self.redirect = RedirectIO(self)
        self.cioout = CIO(self, sys.__stdout__.fileno(), self.sigout)
        self.cioout.start()
        self.cioerr = CIO(self, sys.__stderr__.fileno(), self.sigerr)
        self.cioerr.start()

    def configure(self):
        self.setAllowedAreas(Qt.AllDockWidgetAreas)
        self.setObjectName("dockWidgetBrowser")
        self.setWindowTitle(
            QApplication.translate("Log", "Log", None,
                                   QApplication.UnicodeUTF8))

    def addAction(self):
        self.__action = QAction(self)
        self.__action.setCheckable(True)
        self.__action.setChecked(True)
        self.__action.setObjectName("actionCoreInformations")
        self.__action.setText(
            QApplication.translate("MainWindow", "Log", None,
                                   QApplication.UnicodeUTF8))
        self.__mainWindow.menuWindow.addAction(self.__action)
        self.connect(self.__action, SIGNAL("triggered()"),
                     self.changeVisibleInformations)

    def changeVisibleInformations(self):
        if not self.isVisible():
            self.setVisible(True)
            self.__action.setChecked(True)
        else:
            self.setVisible(False)
            self.__action.setChecked(False)

    def visibilityChanged(self, bool):
        if not self.isVisible():
            self.__action.setChecked(False)
        else:
            self.__action.setChecked(True)

    def initIO(self):
        self.iowidget = QWidget(self)
        self.layout = QHBoxLayout(self.iowidget)
        self.iowidget.setLayout(self.layout)
        self.tabwidget = QTabWidget(self)
        self.tabwidget.setElideMode(Qt.ElideRight)

        self.textOut = QTextEdit(self)
        self.textOut.setReadOnly(1)
        self.textOut.name = "output"
        self.setWidget(self.textOut)
        self.tabwidget.addTab(self.textOut, "Output")

        self.textErr = QTextEdit(self)
        self.textErr.setReadOnly(1)
        self.textErr.name = "error"
        self.setWidget(self.textErr)
        self.tabwidget.addTab(self.textErr, "Error")

        self.layout.addWidget(self.tabwidget)
        self.setWidget(self.iowidget)

    def puttextout(self, text):
        self.textOut.append(text)

    def puttexterr(self, text):
        self.textErr.append(text)
Beispiel #37
0
class BatchOutputSelectionPanel(QWidget):
    def __init__(self, output, alg, row, col, panel):
        super(BatchOutputSelectionPanel, self).__init__(None)
        self.alg = alg
        self.row = row
        self.col = col
        self.output = output
        self.panel = panel
        self.table = self.panel.tblParameters
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.text = QLineEdit()
        self.text.setText('')
        self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.horizontalLayout.addWidget(self.text)
        self.pushButton = QPushButton()
        self.pushButton.setText('...')
        self.pushButton.clicked.connect(self.showSelectionDialog)
        self.horizontalLayout.addWidget(self.pushButton)
        self.setLayout(self.horizontalLayout)

    def showSelectionDialog(self):
        filefilter = self.output.getFileFilter(self.alg)
        settings = QSettings()
        if settings.contains('/Processing/LastBatchOutputPath'):
            path = unicode(settings.value('/Processing/LastBatchOutputPath'))
        else:
            path = ''
        filename = QFileDialog.getSaveFileName(self, self.tr('Save file'),
                                               path, filefilter)
        if filename:
            filename = unicode(filename)
            settings.setValue('/Processing/LastBatchOutputPath',
                              os.path.dirname(filename))
            dlg = AutofillDialog(self.alg)
            dlg.exec_()
            if dlg.mode is not None:
                try:
                    if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL:
                        self.table.cellWidget(self.row,
                                              self.col).setValue(filename)
                    elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS:
                        n = self.table.rowCount() - self.row
                        for i in range(n):
                            name = filename[:filename.rfind('.')] \
                                + str(i + 1) + filename[filename.rfind('.'):]
                            self.table.cellWidget(i + self.row,
                                                  self.col).setValue(name)
                    elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER:
                        n = self.table.rowCount() - self.row
                        for i in range(n):
                            widget = self.table.cellWidget(
                                i + self.row, dlg.param)
                            param = self.alg.parameters[dlg.param]
                            if isinstance(
                                    param,
                                (ParameterRaster, ParameterVector,
                                 ParameterTable, ParameterMultipleInput)):
                                s = unicode(widget.getText())
                                s = os.path.basename(s)
                                s = os.path.splitext(s)[0]
                            elif isinstance(param, ParameterBoolean):
                                s = str(widget.currentIndex() == 0)
                            elif isinstance(param, ParameterSelection):
                                s = unicode(widget.currentText())
                            elif isinstance(param, ParameterFixedTable):
                                s = unicode(widget.table)
                            else:
                                s = unicode(widget.text())
                            name = filename[:filename.rfind('.')] + s \
                                + filename[filename.rfind('.'):]
                            self.table.cellWidget(i + self.row,
                                                  self.col).setValue(name)
                except:
                    pass

    def setValue(self, text):
        return self.text.setText(text)

    def getValue(self):
        return unicode(self.text.text())
Beispiel #38
0
    def __init__(self):
        QWidget.__init__(self)
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(0, 0, 0, 0)
        self.btnClose = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.completer = QCompleter(self)
        self.pathLine = ui_tools.LineEditTabCompleter(self.completer)
        fileModel = QFileSystemModel(self.completer)
        fileModel.setRootPath("")
        self.completer.setModel(fileModel)
        self.pathLine.setCompleter(self.completer)
        self.btnOpen = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowRight), 'Open!')
        hbox.addWidget(self.btnClose)
        hbox.addWidget(QLabel(self.tr("Path:")))
        hbox.addWidget(self.pathLine)
        hbox.addWidget(self.btnOpen)

        self.connect(self.pathLine, SIGNAL("returnPressed()"), self._open_file)
        self.connect(self.btnOpen, SIGNAL("clicked()"), self._open_file)
Beispiel #39
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self._parent = parent
        hSearch = QHBoxLayout(self)
        hSearch.setContentsMargins(0, 0, 0, 0)
        self._checkSensitive = QCheckBox(self.tr("Respect Case Sensitive"))
        self._checkWholeWord = QCheckBox(self.tr("Find Whole Words"))
        self._line = TextLine(self)
        self._line.setMinimumWidth(250)
        self._btnClose = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self._btnFind = QPushButton(QIcon(resources.IMAGES['find']), '')
        self.btnPrevious = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowLeft), '')
        self.btnPrevious.setToolTip(
            self.tr(u"Press %s".format(
                resources.get_shortcut("Find-previous").toString(
                    QKeySequence.NativeText))))
        self.btnNext = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowRight), '')
        self.btnNext.setToolTip(
            self.tr(u"Press %s".format(
                resources.get_shortcut("Find-next").toString(
                    QKeySequence.NativeText))))
        hSearch.addWidget(self._btnClose)
        hSearch.addWidget(self._line)
        hSearch.addWidget(self._btnFind)
        hSearch.addWidget(self.btnPrevious)
        hSearch.addWidget(self.btnNext)
        hSearch.addWidget(self._checkSensitive)
        hSearch.addWidget(self._checkWholeWord)

        self.totalMatches = 0
        self.index = 0
        self._line.counter.update_count(self.index, self.totalMatches)

        self.connect(self._btnClose, SIGNAL("clicked()"),
                     self._parent.hide_status)
        self.connect(self._btnFind, SIGNAL("clicked()"), self.find_next)
        self.connect(self.btnNext, SIGNAL("clicked()"), self.find_next)
        self.connect(self.btnPrevious, SIGNAL("clicked()"), self.find_previous)
        self.connect(self._checkSensitive, SIGNAL("stateChanged(int)"),
                     self._checks_state_changed)
        self.connect(self._checkWholeWord, SIGNAL("stateChanged(int)"),
                     self._checks_state_changed)
Beispiel #40
0
    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
                                       self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)
Beispiel #41
0
class MainWidget(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip("Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Close |
            QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))

    def closeEvent(self, event):
        ' Ask to Quit '
        the_conditional_is_true = QMessageBox.question(
            self, __doc__.title(), 'Quit ?.', QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        event.accept() if the_conditional_is_true else event.ignore()

    def sleep(self):
        """Method to make the computer Sleep."""
        try:
            sysfsFP = open("/sys/power/state", 'w')
        except:
            log.err("Couldn't open kernel interface")
            return False
        else:
            try:
                sysfsFP.write("mem")
            except:
                log.err("Couldn't write to kernel interface")
                return False

    def hibernate(self):
        """Method to make the computer Hibernate."""
        try:
            sysfsFP = open("/sys/power/state", 'w')
        except:
            log.err("Couldn't open kernel interface")
            return False
        else:
            try:
                sysfsFP.write("disk")
            except:
                log.err("Couldn't write to kernel interface")
                return False

    def writeConfig(self):
        """Method to get a configuration for the App."""
        finalResult = True
        for eachWriteOption in tuple(self.configOptions.keys()):
            checkBoxName = "checkBox_" + eachWriteOption
            if self.checkBoxList[checkBoxName].isChecked() is True:
                val = 1
            else:
                val = 0
            ret = self.populateValues(self.configOptions[eachWriteOption], val)

            if ret is False:
                log.debug("Couldn't apply setting for %s" % checkBoxName)
                finalResult = False

        if finalResult is False:
            QMessageBox.critical(self, "Error",
                                       "Couldn't apply all requested settings")
        else:
            QMessageBox.information(self, "Success",
                                          "Applied all requested settings")

    def populateValues(self, _path, value):
        """Method to populate values from a file path."""
        try:
            readHandle = open(_path, 'r')
            writeHandle = open(_path + ".tmp", 'w')
            for line in readHandle.readlines():
                if line.startswith(CONTROL_IDENTIFIER):
                    newline = line.split("=")[0] + "=" + str(value)
                    writeHandle.write(newline)
                    # You need this newline, otherwise the next line gets
                    # overlapped here
                    writeHandle.write("\n")
                else:
                    writeHandle.write(line)
            readHandle.close()
            writeHandle.close()
            move(_path + ".tmp", _path)
            return True
        except:
            log.debug("Failed in populateValues() when operating on %s" % _path)
            return False

    def findConfig(self, configDir):
        """Take a configDir and find the configuration for the App."""
        if configDir is None:
            return False

        # TODO: Do we need to take care of the vendor specific overrides ???
        for configFile in listdir(configDir):
            if access(path.join(configDir, configFile), F_OK) is True:
                fn = path.join(configDir, configFile)
                self.configOptions[configFile.split(".")[0]] = fn
            else:
                pass

    def readConfig(self, key, configOptionsDict):
        """Take a key and dict and read the configurations for the App."""
        self.tooltip = ''

        if key is None or configOptionsDict is None:
            return False

        try:
            fileHandle = open(configOptionsDict[key], 'r')
        except:
            return False

        for line in fileHandle.readlines():
            if line.startswith(COMMENT_IDENTIFIER):
                self.tooltip = self.tooltip + line.lstrip(COMMENT_IDENTIFIER)
            elif line.startswith(CONTROL_IDENTIFIER):
                boolValue = line.split("=")[1]
                # Bloody boolValue could inherit the '\n' new line
                boolValue = boolValue.rstrip("\n")

                if boolValue == str(1) or "\"auto\"" in boolValue:
                    self.configBool = True
                else:
                    self.configBool = False

        # This will ensure that even if we don't read any string, tooltip
        # doesn't fail
        self.tooltip = self.tooltip + ''
Beispiel #42
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     hReplace = QHBoxLayout(self)
     hReplace.setContentsMargins(0, 0, 0, 0)
     self._lineReplace = QLineEdit()
     self._lineReplace.setMinimumWidth(250)
     self._btnCloseReplace = QPushButton(
         self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
     self._btnReplace = QPushButton(self.tr("Replace"))
     self._btnReplaceAll = QPushButton(self.tr("Replace All"))
     self._btnReplaceSelection = QPushButton(self.tr("Replace Selection"))
     hReplace.addWidget(self._btnCloseReplace)
     hReplace.addWidget(self._lineReplace)
     hReplace.addWidget(self._btnReplace)
     hReplace.addWidget(self._btnReplaceAll)
     hReplace.addWidget(self._btnReplaceSelection)
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A Generic object.
        :type parameter: GenericParameter

        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Create elements
        # Label (name)
        self._label = QLabel(self._parameter.name)

        # Label (help text)
        self._help_text_label = QLabel(self._parameter.help_text)
        self._help_text_label.setWordWrap(True)

        # Label (description)
        self._description_label = QLabel(self._parameter.description)
        self._description_label.setWordWrap(True)
        self._description_label.hide()

        # Flag for show-status of description
        self._hide_description = True

        # Tool button for showing and hide detail description
        self._switch_button = QToolButton()
        self._switch_button.setArrowType(4)  # 2=down arrow, 4=right arrow
        # noinspection PyUnresolvedReferences
        self._switch_button.clicked.connect(self.show_hide_description)
        self._switch_button.setToolTip('Click for detail description')
        self._switch_button_stylesheet = 'border: none;'
        self._switch_button.setStyleSheet(self._switch_button_stylesheet)
        # Layouts
        self._main_layout = QVBoxLayout()
        self._input_layout = QHBoxLayout()
        self._help_layout = QGridLayout()
        # _inner_input_layout must be filled with widget in the child class
        self._inner_input_layout = QHBoxLayout()
        self._inner_help_layout = QVBoxLayout()

        # spacing
        self._main_layout.setSpacing(0)
        self._input_layout.setSpacing(0)
        self._help_layout.setSpacing(0)
        self._inner_input_layout.setSpacing(7)
        self._inner_help_layout.setSpacing(0)

        # Put elements into layouts
        self._input_layout.addWidget(self._label)
        self._input_layout.addLayout(self._inner_input_layout)
        # self._input_layout.addSpacing(100)

        self._help_layout.addWidget(self._switch_button, 0, 0)
        self._help_layout.addWidget(self._help_text_label, 0, 1)
        self._help_layout.addWidget(self._description_label, 1, 1)

        self._main_layout.addLayout(self._input_layout)
        self._main_layout.addLayout(self._help_layout)

        self.setLayout(self._main_layout)

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
Beispiel #44
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip("Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Close |
            QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
Beispiel #45
0
   def runInputDialog(self, title, c1Text, c2Text, opText,
                      outText, cell1, cell2, outCell):
      rows = []
      cols = []
      for r in range(self.table.rowCount()):
         rows.append(str(r + 1))
      for c in range(self.table.columnCount()):
         cols.append(chr(ord('A') + c))
      addDialog = QDialog(self)
      addDialog.setWindowTitle(title)
      group = QGroupBox(title, addDialog)
      group.setMinimumSize(250, 100)
      cell1Label = QLabel(c1Text, group)
      cell1RowInput = QComboBox(group)
      c1Row, c1Col = decode_pos(cell1)
      cell1RowInput.addItems(rows)
      cell1RowInput.setCurrentIndex(c1Row)
      cell1ColInput = QComboBox(group)
      cell1ColInput.addItems(cols)
      cell1ColInput.setCurrentIndex(c1Col)
      operatorLabel = QLabel(opText, group)
      operatorLabel.setAlignment(Qt.AlignHCenter)
      cell2Label = QLabel(c2Text, group)
      cell2RowInput = QComboBox(group)
      c2Row, c2Col = decode_pos(cell2)
      cell2RowInput.addItems(rows)
      cell2RowInput.setCurrentIndex(c2Row)
      cell2ColInput = QComboBox(group)
      cell2ColInput.addItems(cols)
      cell2ColInput.setCurrentIndex(c2Col)
      equalsLabel = QLabel("=", group)
      equalsLabel.setAlignment(Qt.AlignHCenter)
      outLabel = QLabel(outText, group)
      outRowInput = QComboBox(group)
      outRow, outCol = decode_pos(outCell)
      outRowInput.addItems(rows)
      outRowInput.setCurrentIndex(outRow)
      outColInput = QComboBox(group)
      outColInput.addItems(cols)
      outColInput.setCurrentIndex(outCol)

      cancelButton = QPushButton("Cancel", addDialog)
      cancelButton.clicked.connect(addDialog.reject)
      okButton = QPushButton("OK", addDialog)
      okButton.setDefault(True)
      okButton.clicked.connect(addDialog.accept)
      buttonsLayout = QHBoxLayout()
      buttonsLayout.addStretch(1)
      buttonsLayout.addWidget(okButton)
      buttonsLayout.addSpacing(10)
      buttonsLayout.addWidget(cancelButton)

      dialogLayout = QVBoxLayout(addDialog)
      dialogLayout.addWidget(group)
      dialogLayout.addStretch(1)
      dialogLayout.addItem(buttonsLayout)

      cell1Layout = QHBoxLayout()
      cell1Layout.addWidget(cell1Label)
      cell1Layout.addSpacing(10)
      cell1Layout.addWidget(cell1ColInput)
      cell1Layout.addSpacing(10)
      cell1Layout.addWidget(cell1RowInput)

      cell2Layout = QHBoxLayout()
      cell2Layout.addWidget(cell2Label)
      cell2Layout.addSpacing(10)
      cell2Layout.addWidget(cell2ColInput)
      cell2Layout.addSpacing(10)
      cell2Layout.addWidget(cell2RowInput)
      outLayout = QHBoxLayout()
      outLayout.addWidget(outLabel)
      outLayout.addSpacing(10)
      outLayout.addWidget(outColInput)
      outLayout.addSpacing(10)
      outLayout.addWidget(outRowInput)
      vLayout = QVBoxLayout(group)
      vLayout.addItem(cell1Layout)
      vLayout.addWidget(operatorLabel)
      vLayout.addItem(cell2Layout)
      vLayout.addWidget(equalsLabel)
      vLayout.addStretch(1)
      vLayout.addItem(outLayout)
      if addDialog.exec_():
         cell1 = cell1ColInput.currentText() + cell1RowInput.currentText()
         cell2 = cell2ColInput.currentText() + cell2RowInput.currentText()
         outCell = outColInput.currentText() + outRowInput.currentText()
         return True, cell1, cell2, outCell

      return False, None, None, None
Beispiel #46
0
    def __init__(self, parent=None):
        super(Preferences, self).__init__(parent, Qt.Dialog)
        self.setWindowTitle(translations.TR_PREFERENCES_TITLE)
        self.setMinimumSize(QSize(900, 600))
        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        vbox.setContentsMargins(0, 0, 5, 5)
        hbox.setContentsMargins(0, 0, 0, 0)

        self.tree = QTreeWidget()
        self.tree.header().setHidden(True)
        self.tree.setSelectionMode(QTreeWidget.SingleSelection)
        self.tree.setAnimated(True)
        self.tree.header().setHorizontalScrollMode(
            QAbstractItemView.ScrollPerPixel)
        self.tree.header().setResizeMode(0, QHeaderView.ResizeToContents)
        self.tree.header().setStretchLastSection(False)
        self.tree.setFixedWidth(200)
        self.stacked = QStackedLayout()
        hbox.addWidget(self.tree)
        hbox.addLayout(self.stacked)
        vbox.addLayout(hbox)

        hbox_footer = QHBoxLayout()
        self._btnSave = QPushButton(translations.TR_SAVE)
        self._btnCancel = QPushButton(translations.TR_CANCEL)
        hbox_footer.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        hbox_footer.addWidget(self._btnCancel)
        hbox_footer.addWidget(self._btnSave)
        vbox.addLayout(hbox_footer)

        self.connect(self.tree, SIGNAL("itemSelectionChanged()"),
                     self._change_current)
        self.connect(self._btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(self._btnSave, SIGNAL("clicked()"),
                     self._save_preferences)

        self.load_ui()
        self.tree.setCurrentItem(self.tree.topLevelItem(0))
Beispiel #47
0
    def __init__(self, label, color):
        QWidget.__init__(self)

        self.setMinimumWidth(140)
        self.setMaximumHeight(25)

        layout = QHBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(2)

        self.color_box = ColorBox(color)
        self.color_box.setToolTip("Click to change color.")
        self.color_box.colorChanged.connect(self.colorChanged)

        layout.addWidget(self.color_box)
        self.color_label = QLabel(label)
        layout.addWidget(self.color_label)
        layout.addStretch()

        self.setLayout(layout)
        self.label = label
Beispiel #48
0
    def __init__(self, parent=None):
        super(ErrorsWidget, self).__init__(parent, Qt.WindowStaysOnTopHint)
        self.pep8 = None
        self._outRefresh = True

        vbox = QVBoxLayout(self)
        self.listErrors = QListWidget()
        self.listErrors.setSortingEnabled(True)
        self.listPep8 = QListWidget()
        self.listPep8.setSortingEnabled(True)
        hbox_lint = QHBoxLayout()
        if settings.FIND_ERRORS:
            self.btn_lint_activate = QPushButton(self.tr("Lint: ON"))
        else:
            self.btn_lint_activate = QPushButton(self.tr("Lint: OFF"))
        self.errorsLabel = QLabel(self.tr("Static Errors: %s") % 0)
        hbox_lint.addWidget(self.errorsLabel)
        hbox_lint.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        hbox_lint.addWidget(self.btn_lint_activate)
        vbox.addLayout(hbox_lint)
        vbox.addWidget(self.listErrors)
        hbox_pep8 = QHBoxLayout()
        if settings.CHECK_STYLE:
            self.btn_pep8_activate = QPushButton(self.tr("PEP8: ON"))
        else:
            self.btn_pep8_activate = QPushButton(self.tr("PEP8: OFF"))
        self.pep8Label = QLabel(self.tr("PEP8 Errors: %s") % 0)
        hbox_pep8.addWidget(self.pep8Label)
        hbox_pep8.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        hbox_pep8.addWidget(self.btn_pep8_activate)
        vbox.addLayout(hbox_pep8)
        vbox.addWidget(self.listPep8)

        self.connect(self.listErrors, SIGNAL("itemSelectionChanged()"),
                     self.errors_selected)
        self.connect(self.listPep8, SIGNAL("itemSelectionChanged()"),
                     self.pep8_selected)
        self.connect(self.btn_lint_activate, SIGNAL("clicked()"),
                     self._turn_on_off_lint)
        self.connect(self.btn_pep8_activate, SIGNAL("clicked()"),
                     self._turn_on_off_pep8)

        IDE.register_service('tab_errors', self)
        ExplorerContainer.register_tab(translations.TR_TAB_ERRORS, self)
class ParameterContainer(QWidget, object):
    """Container to hold Parameter Widgets."""
    def __init__(self,
                 parameters=None,
                 description_text='',
                 extra_parameters=None,
                 parent=None,
                 vertical=True):
        """Constructor

        .. versionadded:: 2.2

        :param parameters: List of Parameter Widget
        :type parameters: list

        :param description_text: Text for description of the parameter
            container.
        :type description_text: str

        """
        QWidget.__init__(self, parent)
        # attributes
        if not parameters:
            self.parameters = []
        else:
            self.parameters = parameters
        self.description_text = description_text
        self.extra_parameters = extra_parameters
        self.parent = parent
        self.validators = []
        self.validators_kwargs = []

        # UI
        if vertical:
            self.vertical_layout = QVBoxLayout()
        else:
            self.vertical_layout = QHBoxLayout()
        self.widget = QWidget()
        self.description_label = QLabel()
        self.scroll_area = QScrollArea()
        self.group_frame = QFrame()
        self.qt4_parameter_factory = Qt4ParameterFactory()
        self.main_layout = QGridLayout()

# NOTES(IS) : These functions are commented since the architecture is not
#  ready yet.
# def register_widget(self, parameter, parameter_widget):
#     """Register new custom widget.
#
#     :param parameter:
#     :type parameter: GenericParameter
#
#     :param parameter_widget:
#     :type parameter_widget: GenericParameterWidget
#     """
#     self.qt4_parameter_factory.register_widget(
# parameter, parameter_widget)
#
# def remove_widget(self, parameter):
#     """Register new custom widget.
#
#     :param parameter:
#     :type parameter: GenericParameter
#     """
#     if parameter.__name__ in self.dict_widget.keys():
#         self.dict_widget.pop(parameter.__name__)

    def get_parameters(self, validate=True):
        """Return list of parameters from the current state of widget.

        :param validate: If true, run validator, else no.
        :type validate: bool

        :returns: List of parameter
        :rtype: list
        """
        if validate:
            validation_result = self.validate()
            if not validation_result['valid']:
                raise InvalidValidationException(validation_result['message'])

        parameter_widgets = self.get_parameter_widgets()

        parameters = []

        for widget_item in parameter_widgets:
            parameter_widget = widget_item.widget()

            parameter = parameter_widget.get_parameter()
            parameters.append(parameter)

        # returns based on the object type of self.parameters
        if isinstance(self.parameters, list):
            return parameters
        else:
            # just return single parameter
            return parameters[0]

    def get_parameter_widgets(self):
        """Return list of parameter widgets from the current state of widget.

        :returns: List of parameter widget
        :rtype: list
        """

        parameter_widgets = [
            self.vertical_layout.itemAt(i)
            for i in range(self.vertical_layout.count())
        ]

        return parameter_widgets

    def setup_ui(self, must_scroll=True):
        """Setup the UI of this parameter container.
        """
        # Vertical layout to place the parameter widgets
        self.vertical_layout.setContentsMargins(0, 0, 0, 0)
        self.vertical_layout.setSpacing(0)

        # Widget to hold the vertical layout
        self.widget = QWidget()
        self.widget.setLayout(self.vertical_layout)

        # Label for description
        self.description_label.setText(self.description_text)

        self.group_frame.setLineWidth(0)
        self.group_frame.setFrameStyle(QFrame.NoFrame)
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.setSpacing(0)
        self.group_frame.setLayout(vlayout)

        if must_scroll:
            vlayout.addWidget(self.scroll_area)
            self.scroll_area.setWidgetResizable(True)
            self.scroll_area.setWidget(self.widget)
        else:
            vlayout.addWidget(self.widget)

        # Main layout of the container
        if self.description_text:
            self.main_layout.addWidget(self.description_label)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.main_layout)

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)

        if not isinstance(self.parameters, list):
            parameters = [self.parameters]
        else:
            parameters = self.parameters

        if len(parameters) == 0:
            self.set_empty_parameters()
            return

        self.main_layout.addWidget(self.group_frame)

        self.qt4_parameter_factory = Qt4ParameterFactory()
        if self.extra_parameters is not None:
            for extra_parameter in self.extra_parameters:
                if (type(extra_parameter) == tuple
                        and len(extra_parameter) == 2):
                    self.qt4_parameter_factory.register_widget(
                        extra_parameter[0], extra_parameter[1])

        color_odd = QColor(220, 220, 220)
        color_even = QColor(192, 192, 192)

        i = 0
        for parameter in parameters:
            parameter_widget = self.qt4_parameter_factory.get_widget(parameter)
            if i % 2:
                color = color_even
            else:
                color = color_odd
            i += 1
            parameter_widget.setAutoFillBackground(True)
            # palette = parameter_widget.palette()
            # palette.setColor(parameter_widget.backgroundRole(), color)
            # parameter_widget.setPalette(palette)
            self.vertical_layout.addWidget(parameter_widget)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def set_description(self, description):
        """Set description of the parameter container.

        :param description: A new description fot the parameter container.
        :type description: str
        """
        self.description_text = description
        self.description_label.setText(self.description_text)

    def set_empty_parameters(self):
        """Update UI if there is no parameters in the container.
        """
        new_description = self.description_text
        new_description += '\n'
        new_description += 'But, currently there is no parameters available.'
        self.description_label.setText(new_description)

    def add_validator(self, validator, **kwargs):
        """Add validator for this parameter container.

        :param validator: validator function for this parameter container.
        :type validator: function
        """
        validator.parent = self
        self.validators.append(validator)
        if kwargs:
            self.validators_kwargs.append(kwargs)
        else:
            self.validators_kwargs.append({})

    def validate(self):
        """Validate of all rule for all parameter in this container.

        :return: True if all valid, False
        :rtype: dict
        """
        for i in range(len(self.validators)):
            validator = self.validators[i]
            validator_kwargs = self.validators_kwargs[i]
            validation_result = validator(self, **validator_kwargs)
            if not validation_result['valid']:
                return validation_result

        return {'valid': True, 'message': ''}

    def get_parameter_by_guid(self, parameter_guid):
        """Return a parameter based on its uuid

        :param parameter_guid: The parameter uuid
        :type parameter_guid: str

        :returns: The parameter or None if not exist
        :rtype: GenericParameter, None
        """
        parameters = self.get_parameters(validate=False)
        for parameter in parameters:
            if parameter.guid == parameter_guid:
                return parameter
        return None

    def get_parameter_widget_by_guid(self, parameter_guid):
        """Return a parameter widget based on its uuid

        :param parameter_guid: The parameter uuid
        :type parameter_guid: str

        :returns: The parameter widget or None if not exist
        :rtype: GenericParameterWidget, None
        """
        parameter_widgets = self.get_parameter_widgets()
        for parameter_widget in parameter_widgets:
            if (parameter_widget.widget().get_parameter().guid ==
                    parameter_guid):
                return parameter_widget.widget()
        return None
Beispiel #50
0
  def __init__ ( self, conf, parent=None ):
    QWidget.__init__ ( self, parent )
    self._conf = conf
    self._projects = []
    for project in self._conf.projects:
        self._projects += [ ProjectWidgets(project) ]
    
    gLayout = QGridLayout()
    column  = 0
    for iproject in range(len(self._projects)):
      column += self._projects[iproject].addToLayout( column, gLayout )
    toolsGroup = QGroupBox( 'Projects && Tools' )
    toolsGroup.setLayout( gLayout )

    scrollToolsGroup = QScrollArea()
    scrollToolsGroup.setMinimumHeight( 350 )
   #scrollToolsGroup.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOn )
    scrollToolsGroup.setWidget( toolsGroup )

    self._buildMode = QComboBox()
    self._buildMode.addItems( ('Release', 'Debug') )
   #self._svnUpdate   = QCheckBox( 'SVN Update' )
   #self._svnStatus   = QCheckBox( 'SVN Status' )
    self._make        = QCheckBox( 'Build' )
    self._enableDoc   = QCheckBox( 'Build Documentation' )
    self._devtoolset2 = QCheckBox( 'Build with devtoolset 2' )
    self._qt5         = QCheckBox( 'Build with Qt 5 (Qt 4 default)' )
    self._noCache     = QCheckBox( 'Remove previous CMake cache' )
    self._rmBuild     = QCheckBox( 'Cleanup Build Directory' )
    self._verbose     = QCheckBox( 'Display Compiler Commands' )
    self._threads     = QComboBox()
    for j in range(16):
        self._threads.addItem( '-j%d'%(j+1), j+1 )

    self._commandGroup = QButtonGroup()
    self._commandGroup.setExclusive( True )
   #self._commandGroup.addButton( self._svnUpdate )
   #self._commandGroup.addButton( self._svnStatus )
    self._commandGroup.addButton( self._make )

    vLayout = QVBoxLayout()
   #vLayout.addWidget( self._svnUpdate )
   #vLayout.addWidget( self._svnStatus )
    vLayout.addWidget( self._make )
    vLayout.addStretch()
    commandGroup = QGroupBox( 'Command' )
    commandGroup.setLayout( vLayout )

    vLayout = QVBoxLayout()
    vLayout.addWidget( self._buildMode )
    vLayout.addWidget( self._enableDoc )
    vLayout.addWidget( self._devtoolset2 )
    vLayout.addWidget( self._qt5 )
    vLayout.addWidget( self._noCache )
    vLayout.addWidget( self._rmBuild )
    vLayout.addStretch()
    optionsGroup = QGroupBox( 'Command Options' )
    optionsGroup.setLayout( vLayout )

    vLayout = QVBoxLayout()
    vLayout.addWidget( self._threads )
    vLayout.addWidget( self._verbose )
    vLayout.addStretch()
    miscGroup = QGroupBox( 'Misc. Options' )
    miscGroup.setLayout( vLayout )

    hLayout = QHBoxLayout()
    hLayout.addWidget( commandGroup )
    hLayout.addWidget( optionsGroup )
    hLayout.addWidget( miscGroup )
    commands = QWidget()
    commands.setLayout( hLayout )

    vLayout = QVBoxLayout()
    vLayout.addWidget( commands )
    vLayout.addWidget( scrollToolsGroup )
    vLayout.addStretch()
    self.setLayout( vLayout )

    self.readSettings()
    return
Beispiel #51
0
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #self.prm = prm

        self.pchs = [
            "o", "s", "v", "p", "h", "8", "*", "x", "+", "d", ",", "^", "<",
            ">", "1", "2", "3", "4", "H", "D", ".", "|", "_"
        ]

        mpl.rcParams['xtick.major.size'] = 6
        mpl.rcParams['xtick.minor.size'] = 4
        mpl.rcParams['xtick.major.width'] = 1
        mpl.rcParams['xtick.minor.width'] = 1
        mpl.rcParams['ytick.major.size'] = 9
        mpl.rcParams['ytick.minor.size'] = 5
        mpl.rcParams['ytick.major.width'] = 0.8
        mpl.rcParams['ytick.minor.width'] = 0.8
        mpl.rcParams['xtick.direction'] = 'out'
        mpl.rcParams['ytick.direction'] = 'out'
        mpl.rcParams['font.size'] = 14
        mpl.rcParams['figure.facecolor'] = 'white'
        mpl.rcParams['lines.color'] = 'black'
        mpl.rcParams['axes.color_cycle'] = [
            "#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2",
            "#D55E00", "#CC79A7"
        ]  #['k', 'b', 'g', 'r', 'c', 'm', 'y']

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(
            figsize=(8, 8))  #facecolor=self.canvasColor, dpi=self.dpi)
        self.ax1 = self.fig.add_subplot(221)
        self.ax2 = self.fig.add_subplot(222)
        self.ax3 = self.fig.add_subplot(223)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
        self.ntb = NavigationToolbar(self.canvas, self.mw)

        self.logAxisMidpoint = QCheckBox(self.tr("Midpoint Log Axis"))
        self.logAxisMidpoint.stateChanged[int].connect(
            self.toggleMidpointLogAxis)

        self.logAxisSlope = QCheckBox(self.tr("Slope Log Axis"))
        self.logAxisSlope.stateChanged[int].connect(self.toggleSlopeLogAxis)

        self.logAxisLapse = QCheckBox(self.tr("Lapse Log Axis"))
        self.logAxisLapse.stateChanged[int].connect(self.toggleLapseLogAxis)

        self.updateButton = QPushButton(self.tr("Update"), self)
        self.updateButton.setIcon(
            QIcon.fromTheme("view-refresh", QIcon(":/view-refresh")))
        self.updateButton.clicked.connect(self.onClickUpdateButton)

        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.logAxisMidpoint)
        self.ntbBox.addWidget(self.logAxisSlope)
        self.ntbBox.addWidget(self.logAxisLapse)
        self.ntbBox.addWidget(self.updateButton)
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)

        self.getUMLPars()
        if self.stimScaling == "Linear":
            self.logAxisMidpoint.setChecked(False)
            self.plotDataMidpoint()
        elif self.stimScaling == "Logarithmic":
            self.logAxisMidpoint.setChecked(True)
            self.plotDataMidpointLogAxis()

        if self.slopeSpacing == "Linear":
            self.logAxisSlope.setChecked(False)
            self.plotDataSlope()
        elif self.slopeSpacing == "Logarithmic":
            self.logAxisSlope.setChecked(True)
            self.plotDataSlopeLogAxis()

        if self.lapseSpacing == "Linear":
            self.logAxisLapse.setChecked(False)
            self.plotDataLapse()
        elif self.lapseSpacing == "Logarithmic":
            self.logAxisLapse.setChecked(True)
            self.plotDataLapseLogAxis()

        self.fig.suptitle(self.tr("UML Parameter Space"))
        self.show()
        self.canvas.draw()
    def __init__(self, analysis_module_name, parent=None):
        QWidget.__init__(self, parent)

        self._analysis_module_name = analysis_module_name

        layout = QFormLayout()
        variable_names = AnalysisModuleVariablesModel.getVariableNames(self._analysis_module_name)

        if len(variable_names) == 0:
            label = QLabel("No variables found to edit")
            boxlayout = QHBoxLayout()
            layout.addRow(label, boxlayout)

        else:
            analysis_module_variables_model = AnalysisModuleVariablesModel
            self.blockSignals(True)

            variable_names2 = self.sortVariables(variable_names)
            for variable_name in variable_names2:
                variable_type = analysis_module_variables_model.getVariableType(variable_name)
                variable_value = analysis_module_variables_model.getVariableValue(self._analysis_module_name,
                                                                                  variable_name)

                label_name = analysis_module_variables_model.getVariableLabelName(variable_name)
                if variable_type == bool:
                    spinner = self.createCheckBox(variable_name, variable_value, variable_type)

                elif variable_type == float:
                    spinner = self.createDoubleSpinBox(variable_name, variable_value, variable_type,
                                                       analysis_module_variables_model)

                elif variable_type == str:
                    spinner = self.createLineEdit(variable_name, variable_value, variable_type)

                elif variable_type == int:
                    spinner = self.createSpinBox(variable_name, variable_value, variable_type,
                                                 analysis_module_variables_model)

                layout.addRow(label_name, spinner)
                if variable_name == "LAMBDA0":
                    label = QLabel(
                        "<span style=\"font-size:12pt; font-weight:300;font-style:italic;\"> Initial Lambda of -1.00 signifies that the value will be calculated</span>")
                    layout.addRow(label, None)

                if variable_name == "IES_INVERSION":
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   0: Exact inversion with diagonal R=I</span>")
                    layout.addRow(label, None)
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   1: Subspace inversion with exact R  </span>")
                    layout.addRow(label, None)
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   2: Subspace inversion using R=EE'   </span>")
                    layout.addRow(label, None)
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   3: Subspace inversion using E       </span>")
                    layout.addRow(label, None)

                if variable_name == "IES_DEC_STEPLENGTH":
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   A good start is max steplength of 0.6, min steplength of 0.3, and decline of 2.5</span>")
                    layout.addRow(label, None)
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   A steplength of 1.0 and one iteration results in ES update</span>")
                    layout.addRow(label, None)
                    
                if variable_name == "IES_AAPROJECTION":
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   Only impacts estimate when n less than N-1</span>")
                    label = QLabel("<span style=\"font-size:10pt; font-weight:300;font-style:italic;\">   Any benefit of using the projection is unclear</span>")
                    layout.addRow(label, None)

        self.setLayout(layout)
        self.blockSignals(False)
Beispiel #53
0
    def __createLayout(self):
        " Creates the toolbar and layout "

        # Buttons
        self.__toggleViewButton = QAction(
            PixmapCache().getIcon('tableview.png'), 'Switch to table view',
            self)
        self.__toggleViewButton.setCheckable(True)
        self.__toggleViewButton.toggled.connect(self.__switchView)

        self.__togglePathButton = QAction(
            PixmapCache().getIcon('longpath.png'),
            'Show full paths for item location', self)
        self.__togglePathButton.setCheckable(True)
        self.__togglePathButton.toggled.connect(self.__togglePath)
        self.__togglePathButton.setEnabled(False)

        self.__printButton = QAction(PixmapCache().getIcon('printer.png'),
                                     'Print', self)
        self.__printButton.triggered.connect(self.__onPrint)
        self.__printButton.setEnabled(False)

        self.__printPreviewButton = QAction(
            PixmapCache().getIcon('printpreview.png'), 'Print preview', self)
        self.__printPreviewButton.triggered.connect(self.__onPrintPreview)
        self.__printPreviewButton.setEnabled(False)

        fixedSpacer = QWidget()
        fixedSpacer.setFixedHeight(16)

        self.__zoomInButton = QAction(PixmapCache().getIcon('zoomin.png'),
                                      'Zoom in (Ctrl+=)', self)
        self.__zoomInButton.setShortcut('Ctrl+=')
        self.__zoomInButton.triggered.connect(self.onZoomIn)

        self.__zoomOutButton = QAction(PixmapCache().getIcon('zoomout.png'),
                                       'Zoom out (Ctrl+-)', self)
        self.__zoomOutButton.setShortcut('Ctrl+-')
        self.__zoomOutButton.triggered.connect(self.onZoomOut)

        self.__zoomResetButton = QAction(
            PixmapCache().getIcon('zoomreset.png'), 'Zoom reset (Ctrl+0)',
            self)
        self.__zoomResetButton.setShortcut('Ctrl+0')
        self.__zoomResetButton.triggered.connect(self.onZoomReset)

        # Toolbar
        toolbar = QToolBar(self)
        toolbar.setOrientation(Qt.Vertical)
        toolbar.setMovable(False)
        toolbar.setAllowedAreas(Qt.RightToolBarArea)
        toolbar.setIconSize(QSize(16, 16))
        toolbar.setFixedWidth(28)
        toolbar.setContentsMargins(0, 0, 0, 0)

        toolbar.addAction(self.__toggleViewButton)
        toolbar.addAction(self.__togglePathButton)
        toolbar.addAction(self.__printPreviewButton)
        toolbar.addAction(self.__printButton)
        toolbar.addWidget(fixedSpacer)
        toolbar.addAction(self.__zoomInButton)
        toolbar.addAction(self.__zoomOutButton)
        toolbar.addAction(self.__zoomResetButton)

        hLayout = QHBoxLayout()
        hLayout.setContentsMargins(0, 0, 0, 0)
        hLayout.setSpacing(0)
        hLayout.addWidget(self.__profTable)
        hLayout.addWidget(self.__profGraph)
        hLayout.addWidget(toolbar)

        self.setLayout(hLayout)
        return
Beispiel #54
0
    def __init__(self):
        super(mainwindow, self).__init__()
        self.setWindowTitle('组件设计工具')
        self.setWindowIcon(QIcon(':/image/组件设计工具.png'))

        self.setMinimumWidth(1024)
        self.setMinimumHeight(800)

        self.showMaximized()
        self.menuBar().show()
        self.createMenus()

        #self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)

        labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        editSizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)

        cwVLayout = QVBoxLayout()
        cwHLayout = QHBoxLayout()

        lLayout = QVBoxLayout()
        rLayout = QVBoxLayout()
        self.lw = QListWidget()
        self.lw.setSelectionMode(QAbstractItemView.SingleSelection)

        lLayout.addWidget(self.lw)
        self.lw.itemSelectionChanged.connect(self.on_select)

        lGroup = QGroupBox('项目列表')
        lGroup.setLayout(lLayout)
        cwHLayout.addWidget(lGroup, 2)
        lGroup.setContentsMargins(0, 12, 0, 22)

        tLayout = QVBoxLayout()
        bLayout = QHBoxLayout()

        self.tGroup = QGroupBox('配置信息')
        self.bGroup = QGroupBox('生成代码')
        self.tGroup.setLayout(tLayout)
        self.tGroup.setEnabled(False)
        self.bGroup.setLayout(bLayout)
        self.bGroup.setEnabled(False)

        cwHLayout.addWidget(self.tGroup, 8)
        cwVLayout.addLayout(cwHLayout)
        cwVLayout.addWidget(self.bGroup)

        self.tw_config = QTreeWidget()
        headerLabels = QStringList()
        headerLabels.append('       项目')
        headerLabels.append('       值')
        self.tw_config.setHeaderLabels(headerLabels)
        self.tw_config.setColumnWidth(0, 312)
        self.tw_config.setColumnWidth(1, 660)
        thLayout = QHBoxLayout()
        thLayout.setContentsMargins(0, 6, 0, 0)
        thLayout.addSpacing(10)
        modify_btn = QPushButton('')  #修改
        modify_btn.setObjectName('modify_btn')
        modify_btn.clicked.connect(self.on_modify)
        del_btn = QPushButton('')  #删除
        del_btn.setObjectName('del_btn')
        del_btn.clicked.connect(self.on_del)
        thLayout.addWidget(modify_btn)
        thLayout.addWidget(del_btn)
        thLayout.addStretch(0)

        tLayout.addLayout(thLayout)
        tLayout.addWidget(self.tw_config)

        bhLayout = QHBoxLayout()

        lable1 = QLabel('工程名称:')
        lable1.setSizePolicy(labelSizePolicy)
        self.et_project_name = QLineEdit()
        self.et_project_name.setSizePolicy(editSizePolicy)
        bhLayout.addWidget(lable1)
        bhLayout.addWidget(self.et_project_name)
        bhLayout.addSpacing(16)

        lable2 = QLabel('工程位置:')
        lable2.setSizePolicy(labelSizePolicy)
        self.et_project_location = QLineEdit()
        self.et_project_location.setReadOnly(True)
        self.et_project_location.setSizePolicy(editSizePolicy)
        btn_location = QPushButton('')  #打开
        btn_location.setObjectName('btn_location')
        btn_location.setSizePolicy(labelSizePolicy)
        btn_location.clicked.connect(self.getProjectLocation)
        bhLayout.addWidget(lable2)
        bhLayout.addWidget(self.et_project_location)
        bhLayout.addSpacing(10)
        bhLayout.addWidget(btn_location)

        #bhLayout.addStretch(0)
        gen_btn = QPushButton('')  # 生成
        gen_btn.setObjectName('gen_btn')
        gen_btn.setSizePolicy(labelSizePolicy)
        gen_btn.clicked.connect(self.on_gen)
        bhLayout.addSpacing(45)
        bhLayout.addWidget(gen_btn)

        bLayout.addLayout(bhLayout)
        bLayout.setContentsMargins(10, 24, 22, 34)

        statusBar = self.statusBar()
        sBH = QHBoxLayout()
        copyright = QLabel('')
        copyright.setAlignment(QtCore.Qt.AlignCenter)
        copyright.setStyleSheet("color:#acacac")
        statusBar.setMinimumHeight(30)
        statusBar.addWidget(copyright, 10)

        cw = QWidget()
        cw.setLayout(cwVLayout)
        self.setCentralWidget(cw)
        self._initByConfig()
        self.setMinimumSize(400, 200)
Beispiel #55
0
    def create_layout(self):
        """displays the menu objects"""
        grid = QGridLayout()

        grid.addWidget(self.icase, 0, 0)
        grid.addWidget(self.icase_edit, 0, 1)

        grid.addWidget(self.scale, 1, 0)
        grid.addWidget(self.scale_edit, 1, 1)
        grid.addWidget(self.scale_button, 1, 2)

        grid.addWidget(self.time, 2, 0)
        grid.addWidget(self.time_edit, 2, 1)
        grid.addWidget(self.time_button, 2, 2)

        # spacer
        spacer = QLabel('')

        grid.addWidget(self.fps, 3, 0)
        grid.addWidget(self.fps_edit, 3, 1)
        grid.addWidget(self.fps_button, 3, 2)

        grid.addWidget(self.resolution, 4, 0)
        grid.addWidget(self.resolution_edit, 4, 1)
        grid.addWidget(self.resolution_button, 4, 2)

        grid.addWidget(self.browse_folder, 5, 0)
        grid.addWidget(self.browse_folder_edit, 5, 1)
        grid.addWidget(self.browse_folder_button, 5, 2)

        grid.addWidget(self.gif, 6, 0)
        grid.addWidget(self.gif_edit, 6, 1)
        grid.addWidget(self.gif_button, 6, 2)

        grid.addWidget(self.animation_type, 7, 0)
        grid.addWidget(self.animation_type_edit, 7, 1)

        grid.addWidget(spacer, 8, 0)

        #----------
        #Time
        grid_time = QGridLayout()
        grid_time.addWidget(self.icase_start, 0, 0)
        grid_time.addWidget(self.icase_start_edit, 0, 1)
        #grid_time.addWidget(self.icase_start_button, 0, 2)

        grid_time.addWidget(self.icase_end, 1, 0)
        grid_time.addWidget(self.icase_end_edit, 1, 1)
        #grid_time.addWidget(self.icase_end_button, 1, 2)

        grid_time.addWidget(self.icase_delta, 2, 0)
        grid_time.addWidget(self.icase_delta_edit, 2, 1)
        #grid_time.addWidget(self.icase_delta_button, 2, 2)

        #grid_time.addWidget(self.min_value, 3, 0)
        #grid_time.addWidget(self.min_value_edit, 3, 1)
        #grid_time.addWidget(self.min_value_button, 3, 2)

        #grid_time.addWidget(self.max_value, 4, 0)
        #grid_time.addWidget(self.max_value_edit, 4, 1)
        #grid_time.addWidget(self.max_value_button, 4, 2)
        grid_time.addWidget(spacer, 5, 0)

        #--------------
        grid_scale = QGridLayout()
        grid_scale.addWidget(self.animation_profile, 0, 0)
        grid_scale.addWidget(self.animation_profile_edit, 0, 1)

        #grid_scale.addWidget(self.csv_profile, 1, 0)
        #grid_scale.addWidget(self.csv_profile_edit, 1, 1)
        #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2)

        self.csv_profile = QLabel("CSV profile:")
        self.csv_profile_edit = QLineEdit()
        self.csv_profile_button = QPushButton('Browse')

        #box_time = QVBoxLayout()
        # TODO: It's super annoying that the animate time box doesn't
        #       line up with the previous box
        box_scale = QGroupBox('Animate Scale')
        box_scale.setLayout(grid_scale)

        box_time = QGroupBox('Animate Time')
        box_time.setLayout(grid_time)
        #----------


        grid2 = QGridLayout()
        #grid2.addWidget(self.animate_scale_radio, 8, 0)
        #grid2.addWidget(self.animate_phase_radio, 8, 1)
        #grid2.addWidget(self.animate_time_radio, 8, 2)
        #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3)

        grid2.addWidget(self.make_images_checkbox, 10, 0)
        #grid2.addWidget(self.overwrite_images_checkbox, 10, 0)
        grid2.addWidget(self.delete_images_checkbox, 10, 1)
        grid2.addWidget(self.make_gif_checkbox, 10, 2)
        grid2.addWidget(self.repeat_checkbox, 11, 0)


        grid2.addWidget(spacer, 12, 0)
        grid_hbox = QHBoxLayout()
        grid_hbox.addWidget(spacer)
        grid_hbox.addLayout(grid2)
        grid_hbox.addWidget(spacer)

        # bottom buttons
        step_run_box = QHBoxLayout()
        step_run_box.addWidget(self.step_button)
        step_run_box.addWidget(self.run_button)

        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.cancel_button)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addWidget(box_scale)
        vbox.addWidget(box_time)
        #vbox.addLayout(checkboxes)
        vbox.addLayout(grid_hbox)
        vbox.addStretch()
        vbox.addLayout(step_run_box)
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)
Beispiel #56
0
class UMLParSpacePlot(QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #self.prm = prm

        self.pchs = [
            "o", "s", "v", "p", "h", "8", "*", "x", "+", "d", ",", "^", "<",
            ">", "1", "2", "3", "4", "H", "D", ".", "|", "_"
        ]

        mpl.rcParams['xtick.major.size'] = 6
        mpl.rcParams['xtick.minor.size'] = 4
        mpl.rcParams['xtick.major.width'] = 1
        mpl.rcParams['xtick.minor.width'] = 1
        mpl.rcParams['ytick.major.size'] = 9
        mpl.rcParams['ytick.minor.size'] = 5
        mpl.rcParams['ytick.major.width'] = 0.8
        mpl.rcParams['ytick.minor.width'] = 0.8
        mpl.rcParams['xtick.direction'] = 'out'
        mpl.rcParams['ytick.direction'] = 'out'
        mpl.rcParams['font.size'] = 14
        mpl.rcParams['figure.facecolor'] = 'white'
        mpl.rcParams['lines.color'] = 'black'
        mpl.rcParams['axes.color_cycle'] = [
            "#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2",
            "#D55E00", "#CC79A7"
        ]  #['k', 'b', 'g', 'r', 'c', 'm', 'y']

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(
            figsize=(8, 8))  #facecolor=self.canvasColor, dpi=self.dpi)
        self.ax1 = self.fig.add_subplot(221)
        self.ax2 = self.fig.add_subplot(222)
        self.ax3 = self.fig.add_subplot(223)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
        self.ntb = NavigationToolbar(self.canvas, self.mw)

        self.logAxisMidpoint = QCheckBox(self.tr("Midpoint Log Axis"))
        self.logAxisMidpoint.stateChanged[int].connect(
            self.toggleMidpointLogAxis)

        self.logAxisSlope = QCheckBox(self.tr("Slope Log Axis"))
        self.logAxisSlope.stateChanged[int].connect(self.toggleSlopeLogAxis)

        self.logAxisLapse = QCheckBox(self.tr("Lapse Log Axis"))
        self.logAxisLapse.stateChanged[int].connect(self.toggleLapseLogAxis)

        self.updateButton = QPushButton(self.tr("Update"), self)
        self.updateButton.setIcon(
            QIcon.fromTheme("view-refresh", QIcon(":/view-refresh")))
        self.updateButton.clicked.connect(self.onClickUpdateButton)

        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.logAxisMidpoint)
        self.ntbBox.addWidget(self.logAxisSlope)
        self.ntbBox.addWidget(self.logAxisLapse)
        self.ntbBox.addWidget(self.updateButton)
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)

        self.getUMLPars()
        if self.stimScaling == "Linear":
            self.logAxisMidpoint.setChecked(False)
            self.plotDataMidpoint()
        elif self.stimScaling == "Logarithmic":
            self.logAxisMidpoint.setChecked(True)
            self.plotDataMidpointLogAxis()

        if self.slopeSpacing == "Linear":
            self.logAxisSlope.setChecked(False)
            self.plotDataSlope()
        elif self.slopeSpacing == "Logarithmic":
            self.logAxisSlope.setChecked(True)
            self.plotDataSlopeLogAxis()

        if self.lapseSpacing == "Linear":
            self.logAxisLapse.setChecked(False)
            self.plotDataLapse()
        elif self.lapseSpacing == "Logarithmic":
            self.logAxisLapse.setChecked(True)
            self.plotDataLapseLogAxis()

        self.fig.suptitle(self.tr("UML Parameter Space"))
        self.show()
        self.canvas.draw()

    def getUMLPars(self):
        self.psyFun = self.parent().psyFunChooser.currentText()
        self.loStim = self.parent().currLocale.toDouble(
            self.parent().loStim.text())[0]
        self.hiStim = self.parent().currLocale.toDouble(
            self.parent().hiStim.text())[0]
        self.stimScaling = self.parent().stimScalingChooser.currentText()
        self.loMidPoint = self.parent().currLocale.toDouble(
            self.parent().loMidPoint.text())[0]
        self.hiMidPoint = self.parent().currLocale.toDouble(
            self.parent().hiMidPoint.text())[0]
        self.threshGridStep = self.parent().currLocale.toDouble(
            self.parent().threshGridStep.text())[0]
        self.threshPrior = self.parent().threshPriorChooser.currentText()
        self.threshPriorMu = self.parent().currLocale.toDouble(
            self.parent().threshPriorMu.text())[0]
        self.threshPriorSTD = self.parent().currLocale.toDouble(
            self.parent().threshPriorSTD.text())[0]
        self.loSlope = self.parent().currLocale.toDouble(
            self.parent().loSlope.text())[0]
        self.hiSlope = self.parent().currLocale.toDouble(
            self.parent().hiSlope.text())[0]
        self.slopeGridStep = self.parent().currLocale.toDouble(
            self.parent().slopeGridStep.text())[0]
        self.slopeSpacing = self.parent().slopeSpacingChooser.currentText()
        self.slopePrior = self.parent().slopePriorChooser.currentText()
        self.slopePriorMu = self.parent().currLocale.toDouble(
            self.parent().slopePriorMu.text())[0]
        self.slopePriorSTD = self.parent().currLocale.toDouble(
            self.parent().slopePriorSTD.text())[0]
        self.loLapse = self.parent().currLocale.toDouble(
            self.parent().loLapse.text())[0]
        self.hiLapse = self.parent().currLocale.toDouble(
            self.parent().hiLapse.text())[0]
        self.lapseGridStep = self.parent().currLocale.toDouble(
            self.parent().lapseGridStep.text())[0]
        self.lapseSpacing = self.parent().lapseSpacingChooser.currentText()
        self.lapsePrior = self.parent().lapsePriorChooser.currentText()
        self.lapsePriorMu = self.parent().currLocale.toDouble(
            self.parent().lapsePriorMu.text())[0]
        self.lapsePriorSTD = self.parent().currLocale.toDouble(
            self.parent().lapsePriorSTD.text())[0]
        self.nAlternatives = int(
            self.parent().nAlternativesChooser.currentText())

        if self.stimScaling == "Linear":
            self.UML = setupUML(model=self.psyFun,
                                swptRule="Up-Down",
                                nDown=2,
                                centTend="Mean",
                                stimScale=self.stimScaling,
                                x0=1,
                                xLim=(self.loStim, self.hiStim),
                                alphaLim=(self.loMidPoint, self.hiMidPoint),
                                alphaStep=self.threshGridStep,
                                alphaSpacing="Linear",
                                alphaDist=self.threshPrior,
                                alphaMu=self.threshPriorMu,
                                alphaSTD=self.threshPriorSTD,
                                betaLim=(self.loSlope, self.hiSlope),
                                betaStep=self.slopeGridStep,
                                betaSpacing=self.slopeSpacing,
                                betaDist=self.slopePrior,
                                betaMu=self.slopePriorMu,
                                betaSTD=self.slopePriorSTD,
                                gamma=1 / self.nAlternatives,
                                lambdaLim=(self.loLapse, self.hiLapse),
                                lambdaStep=self.lapseGridStep,
                                lambdaSpacing=self.lapseSpacing,
                                lambdaDist=self.lapsePrior,
                                lambdaMu=self.lapsePriorMu,
                                lambdaSTD=self.lapsePriorSTD)
        elif self.stimScaling == "Logarithmic":
            self.UML = setupUML(model=self.psyFun,
                                swptRule="Up-Down",
                                nDown=2,
                                centTend="Mean",
                                stimScale=self.stimScaling,
                                x0=1,
                                xLim=(abs(self.loStim), abs(self.hiStim)),
                                alphaLim=(abs(self.loMidPoint),
                                          abs(self.hiMidPoint)),
                                alphaStep=self.threshGridStep,
                                alphaSpacing="Linear",
                                alphaDist=self.threshPrior,
                                alphaMu=abs(self.threshPriorMu),
                                alphaSTD=self.threshPriorSTD,
                                betaLim=(self.loSlope, self.hiSlope),
                                betaStep=self.slopeGridStep,
                                betaSpacing=self.slopeSpacing,
                                betaDist=self.slopePrior,
                                betaMu=self.slopePriorMu,
                                betaSTD=self.slopePriorSTD,
                                gamma=1 / self.nAlternatives,
                                lambdaLim=(self.loLapse, self.hiLapse),
                                lambdaStep=self.lapseGridStep,
                                lambdaSpacing=self.lapseSpacing,
                                lambdaDist=self.lapsePrior,
                                lambdaMu=self.lapsePriorMu,
                                lambdaSTD=self.lapsePriorSTD)

    def plotDataMidpoint(self):
        self.ax1.clear()
        self.A = setPrior(self.UML["a"], self.UML["par"]["alpha"])

        if self.stimScaling == "Linear":
            markerline, stemlines, baseline = self.ax1.stem(
                self.UML["alpha"], self.A[:, 0, 0], 'k')
        elif self.stimScaling == "Logarithmic":  #logarithmic spaced plotted on linear coords
            markerline, stemlines, baseline = self.ax1.stem(
                exp(self.UML["alpha"]),
                self.A[:, 0, 0] / exp(self.UML["alpha"]), 'k')
            if self.loStim < 0:
                self.ax1.set_xticklabels(list(map(str,
                                                  -self.ax1.get_xticks())))

        plt.setp(markerline, 'markerfacecolor', 'k')
        nAlpha = len(self.A[:, 0, 0])
        self.ax1.set_title("Midpoint, #Points " + str(nAlpha))

    def plotDataSlope(self):
        self.ax2.clear()
        self.B = setPrior(self.UML["b"], self.UML["par"]["beta"])
        if self.UML["par"]["beta"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax2.stem(
                self.UML["beta"], self.B[0, :, 0], 'k')
        elif self.UML["par"]["beta"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax2.stem(
                self.UML["beta"], self.B[0, :, 0] / self.UML["beta"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nBeta = len(self.B[0, :, 0])
        self.ax2.set_title("Slope, #Points " + str(nBeta))

    def plotDataLapse(self):
        self.ax3.clear()
        L = setPrior(self.UML["l"], self.UML["par"]["lambda"])
        if self.UML["par"]["lambda"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax3.stem(
                self.UML["lambda"], L[0, 0, :], 'k')
        elif self.UML["par"]["lambda"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax3.stem(
                self.UML["lambda"], L[0, 0, :] / self.UML["lambda"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nLambda = len(L[0, 0, :])
        self.ax3.set_title("Lapse, #Points " + str(nLambda))

    def plotDataMidpointLogAxis(self):
        self.ax1.clear()
        self.A = setPrior(self.UML["a"], self.UML["par"]["alpha"])

        if self.stimScaling == "Logarithmic":
            x = self.UML["alpha"]
            markerline, stemlines, baseline = self.ax1.stem(
                x, self.A[:, 0, 0], 'k')
        elif self.stimScaling == "Linear":
            x = log(self.UML["alpha"])
            markerline, stemlines, baseline = self.ax1.stem(
                x, self.A[:, 0, 0] * self.UML["alpha"], 'k')

        setLogTicks(self.ax1, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        nAlpha = len(self.A[:, 0, 0])
        self.ax1.set_title("Midpoint, #Points " + str(nAlpha))

    def plotDataSlopeLogAxis(self):
        self.ax2.clear()
        self.B = setPrior(self.UML["b"], self.UML["par"]["beta"])
        if self.UML["par"]["beta"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax2.stem(
                log(self.UML["beta"]), self.B[0, :, 0], 'k')
        elif self.UML["par"]["beta"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax2.stem(
                log(self.UML["beta"]), self.B[0, :, 0] * self.UML["beta"], 'k')

        setLogTicks(self.ax2, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')

        nBeta = len(self.B[0, :, 0])
        self.ax2.set_title("Slope, #Points " + str(nBeta))

    def plotDataLapseLogAxis(self):
        self.ax3.clear()
        L = setPrior(self.UML["l"], self.UML["par"]["lambda"])
        if self.UML["par"]["lambda"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax3.stem(
                log(self.UML["lambda"]), L[0, 0, :], 'k')
        elif self.UML["par"]["lambda"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax3.stem(
                log(self.UML["lambda"]), L[0, 0, :] * self.UML["lambda"], 'k')
        setLogTicks(self.ax3, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')

        nLambda = len(L[0, 0, :])
        self.ax3.set_title("Lapse, #Points " + str(nLambda))

    def onClickUpdateButton(self):
        self.getUMLPars()

        if self.logAxisMidpoint.isChecked() == False:
            self.plotDataMidpoint()
        else:
            self.plotDataMidpointLogAxis()

        if self.logAxisSlope.isChecked() == False:
            self.plotDataSlope()
        else:
            self.plotDataSlopeLogAxis()

        if self.logAxisLapse.isChecked() == False:
            self.plotDataLapse()
        else:
            self.plotDataLapseLogAxis()

        self.canvas.draw()

    def toggleMidpointLogAxis(self):
        if self.logAxisMidpoint.isChecked() == True:
            self.plotDataMidpointLogAxis()
        else:
            self.plotDataMidpoint()
        self.canvas.draw()

    def toggleSlopeLogAxis(self):
        if self.logAxisSlope.isChecked() == True:
            self.plotDataSlopeLogAxis()
        else:
            self.plotDataSlope()
        self.canvas.draw()

    def toggleLapseLogAxis(self):
        if self.logAxisLapse.isChecked() == True:
            self.plotDataLapseLogAxis()
        else:
            self.plotDataLapse()
        self.canvas.draw()
Beispiel #57
0
class DoProfile(QWidget):

    def __init__(self, iface, dockwidget1 , tool1 , plugin, parent = None):
        QWidget.__init__(self, parent)
        self.profiles = None        #dictionary where is saved the plotting data {"l":[l],"z":[z], "layer":layer1, "curve":curve1}
        self.xAxisSteps = None
        self.xAxisStepType = "numeric"
        self.iface = iface
        self.tool = tool1
        self.dockwidget = dockwidget1
        self.pointstoDraw = None
        self.plugin = plugin
        #init scale widgets
        self.dockwidget.sbMaxVal.setValue(0)
        self.dockwidget.sbMinVal.setValue(0)
        self.dockwidget.sbMaxVal.setEnabled(False)
        self.dockwidget.sbMinVal.setEnabled(False)
        self.dockwidget.sbMinVal.valueChanged.connect(self.reScalePlot)
        self.dockwidget.sbMaxVal.valueChanged.connect(self.reScalePlot)


    #**************************** function part *************************************************

    # remove layers which were removed from QGIS
    def removeClosedLayers(self, model1):
        qgisLayerNames = []
        for i in range(0, self.iface.mapCanvas().layerCount()):
                qgisLayerNames.append(self.iface.mapCanvas().layer(i).name())

        for i in range(0 , model1.rowCount()):
            layerName = model1.item(i,2).data(Qt.EditRole)
            if not layerName in qgisLayerNames:
                self.plugin.removeLayer(i)
                self.removeClosedLayers(model1)
                break

    def calculatePointProfile(self, point, model, library):
        self.model = model
        self.library = library
        
        statName = self.getPointProfileStatNames()[0]

        self.removeClosedLayers(model)
        if point == None:
            return
        PlottingTool().clearData(self.dockwidget, model, library)
        self.profiles = []
        
        #creating the plots of profiles
        for i in range(0 , model.rowCount()):
            self.profiles.append( {"layer": model.item(i,3).data(Qt.EditRole) } )
            self.profiles[i][statName] = []
            self.profiles[i]["l"] = []
            layer = self.profiles[i]["layer"]

            if layer:
                try:
                    ident = layer.dataProvider().identify(point, QgsRaster.IdentifyFormatValue )
                except:
                    ident = None
            else:
                ident = None
            #if ident is not None and ident.has_key(choosenBand+1):
            if ident is not None:
                self.profiles[i][statName] = ident.results().values()
                self.profiles[i]["l"] = ident.results().keys()
        
        self.setXAxisSteps()
        PlottingTool().attachCurves(self.dockwidget, self.profiles, model, library)
        PlottingTool().reScalePlot(self.dockwidget, self.profiles, model, library)
        self.setupTableTab(model)

    def getPointProfileStatNames(self):
        return ["value"]

    # The code is based on the approach of ZonalStatistics from Processing toolbox 
    def calculatePolygonProfile(self, geometry, crs, model, library):
        self.model = model
        self.library = library
        
        self.removeClosedLayers(model)
        if geometry is None or geometry.isEmpty():
            return
        
        PlottingTool().clearData(self.dockwidget, model, library)
        self.profiles = []

        #creating the plots of profiles
        for i in range(0 , model.rowCount()):
            self.profiles.append( {"layer": model.item(i,3).data(Qt.EditRole) } )
            self.profiles[i]["l"] = []
            for statistic in self.getPolygonProfileStatNames():
                self.profiles[i][statistic] = []
            
            # Get intersection between polygon geometry and raster following ZonalStatistics code
            rasterDS = gdal.Open(self.profiles[i]["layer"].source(), gdal.GA_ReadOnly)
            geoTransform = rasterDS.GetGeoTransform()
            
    
            cellXSize = abs(geoTransform[1])
            cellYSize = abs(geoTransform[5])
            rasterXSize = rasterDS.RasterXSize
            rasterYSize = rasterDS.RasterYSize
    
            rasterBBox = QgsRectangle(geoTransform[0], geoTransform[3] - cellYSize
                                      * rasterYSize, geoTransform[0] + cellXSize
                                      * rasterXSize, geoTransform[3])
            rasterGeom = QgsGeometry.fromRect(rasterBBox)
            
            memVectorDriver = ogr.GetDriverByName('Memory')
            memRasterDriver = gdal.GetDriverByName('MEM')
            
            intersectedGeom = rasterGeom.intersection(geometry)
            ogrGeom = ogr.CreateGeometryFromWkt(intersectedGeom.exportToWkt())
            
            bbox = intersectedGeom.boundingBox()

            xMin = bbox.xMinimum()
            xMax = bbox.xMaximum()
            yMin = bbox.yMinimum()
            yMax = bbox.yMaximum()

            (startColumn, startRow) = self.mapToPixel(xMin, yMax, geoTransform)
            (endColumn, endRow) = self.mapToPixel(xMax, yMin, geoTransform)

            width = endColumn - startColumn
            height = endRow - startRow

            if width == 0 or height == 0:
                return

            srcOffset = (startColumn, startRow, width, height)

            newGeoTransform = (
                geoTransform[0] + srcOffset[0] * geoTransform[1],
                geoTransform[1],
                0.0,
                geoTransform[3] + srcOffset[1] * geoTransform[5],
                0.0,
                geoTransform[5],
            )
            
            # Create a temporary vector layer in memory
            memVDS = memVectorDriver.CreateDataSource('out')
            memLayer = memVDS.CreateLayer('poly', crs, ogr.wkbPolygon)

            ft = ogr.Feature(memLayer.GetLayerDefn())
            ft.SetGeometry(ogrGeom)
            memLayer.CreateFeature(ft)
            ft.Destroy()
            
            # Rasterize it
            rasterizedDS = memRasterDriver.Create('', srcOffset[2],
                    srcOffset[3], 1, gdal.GDT_Byte)
            rasterizedDS.SetGeoTransform(newGeoTransform)
            gdal.RasterizeLayer(rasterizedDS, [1], memLayer, burn_values=[1])
            rasterizedArray = rasterizedDS.ReadAsArray()
            
            for bandNumber in range(1, rasterDS.RasterCount+1): 
                rasterBand = rasterDS.GetRasterBand(bandNumber)
                noData = rasterBand.GetNoDataValue()
                if noData is None:
                    noData = np.nan
                scale = rasterBand.GetScale()
                if scale is None:
                    scale = 1.0
                offset = rasterBand.GetOffset()
                if offset is None:
                    offset = 0.0
                srcArray = rasterBand.ReadAsArray(*srcOffset)
                srcArray = srcArray*scale+offset 
                masked = np.ma.MaskedArray(srcArray,
                            mask=np.logical_or.reduce((
                             srcArray == noData,
                             np.logical_not(rasterizedArray),
                             np.isnan(srcArray))))

                self.profiles[i]["l"].append(bandNumber)
                self.profiles[i]["count"].append(float(masked.count()))
                self.profiles[i]["max"].append(float(masked.max()))
                self.profiles[i]["mean"].append(float(masked.mean()))
                self.profiles[i]["median"].append(float(np.ma.median(masked)))
                self.profiles[i]["min"].append(float(masked.min()))
                self.profiles[i]["range"].append(float(masked.max()) - float(masked.min()))
                self.profiles[i]["std"].append(float(masked.std()))
                self.profiles[i]["sum"].append(float(masked.sum()))
                self.profiles[i]["unique"].append(np.unique(masked.compressed()).size)
                self.profiles[i]["var"].append(float(masked.var()))
                
            memVDS = None
            rasterizedDS = None
        
        rasterDS = None
        
        self.setXAxisSteps()
        PlottingTool().attachCurves(self.dockwidget, self.profiles, model, library)
        PlottingTool().reScalePlot(self.dockwidget, self.profiles, model, library)
        self.setupTableTab(model)

    def getPolygonProfileStatNames(self):
        return ["count", "max", "mean", "median", "min", "range", "std", "sum", "unique", "var"]

    def setXAxisSteps(self):
        if self.xAxisSteps == None:
            self.changeXAxisStepType("numeric")
            return
        
        elif self.xAxisSteps[0] == "Timesteps":
            self.changeXAxisStepType("numeric")
            for profile in self.profiles:
                stepsNum = len(profile["l"])
                startTime = self.xAxisSteps[1]
                step = self.xAxisSteps[2]
                stepType = self.xAxisSteps[3]
                useNetcdfTime = self.xAxisSteps[4]
                if stepType == "years":
                    stepType = "days"
                    step = step * 365
                elif stepType == "months":
                    stepType = "days"
                    step = step * 365/12

                profile["l"] = []
                if useNetcdfTime and (profile["layer"].source().startswith("NETCDF:") or
                                      profile["layer"].source().endswith(".nc")):
                    try:
                        import netCDF4
                        if profile["layer"].source().startswith("NETCDF:"):
                            filename = re.match('NETCDF:\"(.*)\":.*$', profile["layer"].source()).group(1)
                        else:
                            filename = profile["layer"].source()
                        nc = netCDF4.Dataset(filename, mode='r')
                        profile["l"] = netCDF4.num2date(nc.variables["time"][:],
                                                        units = nc.variables["time"].units,
                                                        calendar = nc.variables["time"].calendar)
                        nc.close()
                    except ImportError:
                        text = "Temporal/Spectral Profile Tool: netCDF4 module is required to read NetCDF " + \
                               "time dimension. Please use pip install netCDF4"
                        self.iface.messageBar().pushWidget(self.iface.messageBar().createMessage(text), 
                                                           QgsMessageBar.WARNING, 5)
                        profile["l"] = []
                    except KeyError:
                        text = "Temporal/Spectral Profile Tool: NetCDF file does not have " + \
                               "time dimension."
                        self.iface.messageBar().pushWidget(self.iface.messageBar().createMessage(text), 
                                                           QgsMessageBar.WARNING, 5)
                        nc.close()
                        profile["l"] = []
                if profile["l"] == []:
                    for i in range(stepsNum):
                        timedeltaParams = {stepType: step*i}
                        profile["l"].append(startTime + timedelta(**timedeltaParams))
                self.changeXAxisStepType("timedate")        
        else:
            for profile in self.profiles:
                # Truncate the profiles to the minimum of the length of each profile
                # or length of provided x-axis steps
                stepsNum = min(len(self.xAxisSteps), len(profile["l"]))
                profile["l"] = self.xAxisSteps[:stepsNum]
                for stat in profile.keys():
                    if stat == "l" or stat == "layer":
                        continue
                    profile[stat] = profile[stat][:stepsNum]
                    
                # If any x-axis step is a NaN then remove the corresponding
                # value from profile
                nans = [i for i, x in enumerate(profile["l"]) if math.isnan(x)]
                for stat in profile.keys():
                    if stat == "layer":
                        continue
                    profile[stat] = [x for i, x in enumerate(profile[stat]) if i not in nans]
            
            self.changeXAxisStepType("numeric")
            
    def changeXAxisStepType(self, newType):
        if self.xAxisStepType == newType:
            return
        else:
            self.xAxisStepType = newType
            PlottingTool().resetAxis(self.dockwidget, self.library)
    
    def mapToPixel(self, mX, mY, geoTransform):
        (pX, pY) = gdal.ApplyGeoTransform(
            gdal.InvGeoTransform(geoTransform), mX, mY)
            
        return (int(pX), int(pY))            
    
    def setupTableTab(self, model1):
        #*********************** TAble tab *************************************************
        try:                                                                    #Reinitializing the table tab
            self.VLayout = self.dockwidget.scrollAreaWidgetContents.layout()
            while 1:
                child = self.VLayout.takeAt(0)
                if not child:
                    break
                child.widget().deleteLater()
        except:
            self.VLayout = QVBoxLayout(self.dockwidget.scrollAreaWidgetContents)
            self.VLayout.setContentsMargins(9, -1, -1, -1)
        #Setup the table tab
        self.groupBox = []
        self.profilePushButton = []
        self.tableView = []
        self.verticalLayout = []
        for i in range(0 , model1.rowCount()):
            self.groupBox.append( QGroupBox(self.dockwidget.scrollAreaWidgetContents) )
            sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.groupBox[i].sizePolicy().hasHeightForWidth())
            self.groupBox[i].setSizePolicy(sizePolicy)
            self.groupBox[i].setMinimumSize(QSize(0, 150))
            self.groupBox[i].setMaximumSize(QSize(16777215, 350))
            self.groupBox[i].setTitle(QApplication.translate("GroupBox" + str(i), self.profiles[i]["layer"].name(), None, QApplication.UnicodeUTF8))
            self.groupBox[i].setObjectName("groupBox" + str(i))

            self.verticalLayout.append( QVBoxLayout(self.groupBox[i]) )
            self.verticalLayout[i].setObjectName("verticalLayout")
            #The table
            self.tableView.append( QTableView(self.groupBox[i]) )
            self.tableView[i].setObjectName("tableView" + str(i))
            font = QFont("Arial", 8)
            columns = len(self.profiles[i]["l"])
            rowNames = self.profiles[i].keys()
            rowNames.remove("layer") # holds the QgsMapLayer instance
            rowNames.remove("l") # holds the band number
            rows = len(rowNames)
            self.mdl = QStandardItemModel(rows+1, columns)
            self.mdl.setVerticalHeaderLabels(["band"] + rowNames)
            for j in range(columns):
                self.mdl.setData(self.mdl.index(0, j, QModelIndex()), str(self.profiles[i]["l"][j]))
                self.mdl.setData(self.mdl.index(0, j, QModelIndex()), font ,Qt.FontRole)
                for k in range(rows):
                    self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), str(self.profiles[i][rowNames[k]][j]))
                    self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), font ,Qt.FontRole)
            #self.tableView[i].setVerticalHeaderLabels(rowNames)
            self.tableView[i].verticalHeader().setDefaultSectionSize(18)
            self.tableView[i].horizontalHeader().setDefaultSectionSize(60)
            self.tableView[i].setModel(self.mdl)
            self.verticalLayout[i].addWidget(self.tableView[i])

            self.horizontalLayout = QHBoxLayout()

            #the copy to clipboard button
            self.profilePushButton.append( QPushButton(self.groupBox[i]) )
            sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.profilePushButton[i].sizePolicy().hasHeightForWidth())
            self.profilePushButton[i].setSizePolicy(sizePolicy)
            self.profilePushButton[i].setText(QApplication.translate("GroupBox", "Copy to clipboard", None, QApplication.UnicodeUTF8))
            self.profilePushButton[i].setObjectName(str(i))
            self.horizontalLayout.addWidget(self.profilePushButton[i])

            self.horizontalLayout.addStretch(0)
            self.verticalLayout[i].addLayout(self.horizontalLayout)

            self.VLayout.addWidget(self.groupBox[i])
            QObject.connect(self.profilePushButton[i], SIGNAL("clicked()"), self.copyTable)

    def copyTable(self):                            #Writing the table to clipboard in excel form
        nr = int( self.sender().objectName() )
        self.clipboard = QApplication.clipboard()
        text = "band"
        rowNames = self.profiles[nr].keys()
        rowNames.remove("layer")
        rowNames.remove("l")
        for name in rowNames:
            text += "\t"+name
        text += "\n"
        for i in range( len(self.profiles[nr]["l"]) ):
            text += str(self.profiles[nr]["l"][i])
            for j in range(len(rowNames)):
                text += "\t" + str(self.profiles[nr][rowNames[j]][i])
            text += "\n"
        self.clipboard.setText(text)

    def reScalePlot(self, param):                         # called when a spinbox value changed
        if type(param) != float:    
            # don't execute it twice, for both valueChanged(int) and valueChanged(str) signals
            return
        if self.dockwidget.sbMinVal.value() == self.dockwidget.sbMaxVal.value() == 0:
            # don't execute it on init
            return
        PlottingTool().reScalePlot(self.dockwidget, self.profiles, self.model, self.library, autoMode = False)
Beispiel #58
0
class CtrlWidget(QWidget):
    msPlayAFrame = pyqtSignal(str, name='msPlayAFrame')

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.mLayout = QVBoxLayout()
        self.mInfoLayout = QVBoxLayout()
        self.mButtonLayout = QHBoxLayout()
        self.mPlayAFrameButton = QPushButton("放映一帧")
        self.mRunButton = QPushButton("运行")

        self.mInfograoupBox = QGroupBox("链路信息")
        self.GetALabelWithLineEditWidgets()

        for widget in self.mWidgets:
            self.mInfoLayout.addWidget(widget)

        self.mInfograoupBox.setLayout(self.mInfoLayout)
        self.mButtonLayout.addWidget(self.mPlayAFrameButton)
        self.mButtonLayout.addWidget(self.mRunButton)

        self.mLayout.addWidget(self.mInfograoupBox)
        self.mLayout.addStretch()
        self.mLayout.addLayout(self.mButtonLayout)

        self.setLayout(self.mLayout)

        self.setMaximumWidth(300)

        self.mPlayAFrameButton.clicked.connect(self.PlayAFrameButtonSlot)

    def GetALabelWithLineEditWidgets(self):
        cfgFile = open(gCfgName, "r", encoding="utf8")
        self.mWidgets = []

        for line in cfgFile:
            #print(line)

            p = re.compile(gParrern)
            m = p.match(line)

            #print(m.group(1))
            #print(m.group(2))

            labelStr = m.group(1) + ":"
            lineEditStr = m.group(2)
            widget = LabelWithLineEditWidget(self, labelStr, lineEditStr)
            self.mWidgets.append(widget)

        cfgFile.close()

    def PlayAFrameButtonSlot(self):
        echoFileName = self.GetEchoFileName()
        self.PlayAFrame(echoFileName)

    def PlayAFrame(self, echoFileName):
        self.msPlayAFrame.emit(echoFileName)

    def GetEchoFileName(self):
        rst = None

        cfgFile = open(gCfgName, "r", encoding="utf8")

        for line in cfgFile:
            p = re.compile(gParrern)
            m = p.match(line)

            labelStr = m.group(1)
            lineEditStr = m.group(2)
            if gCfgNameEchoFileStr == labelStr:
                rst = lineEditStr

        cfgFile.close()
        if None == rst:
            assert 0, gCfgName + "中找不到回波文件的配置"

        return rst
Beispiel #59
0
    def setupTableTab(self, model1):
        #*********************** TAble tab *************************************************
        try:                                                                    #Reinitializing the table tab
            self.VLayout = self.dockwidget.scrollAreaWidgetContents.layout()
            while 1:
                child = self.VLayout.takeAt(0)
                if not child:
                    break
                child.widget().deleteLater()
        except:
            self.VLayout = QVBoxLayout(self.dockwidget.scrollAreaWidgetContents)
            self.VLayout.setContentsMargins(9, -1, -1, -1)
        #Setup the table tab
        self.groupBox = []
        self.profilePushButton = []
        self.tableView = []
        self.verticalLayout = []
        for i in range(0 , model1.rowCount()):
            self.groupBox.append( QGroupBox(self.dockwidget.scrollAreaWidgetContents) )
            sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.groupBox[i].sizePolicy().hasHeightForWidth())
            self.groupBox[i].setSizePolicy(sizePolicy)
            self.groupBox[i].setMinimumSize(QSize(0, 150))
            self.groupBox[i].setMaximumSize(QSize(16777215, 350))
            self.groupBox[i].setTitle(QApplication.translate("GroupBox" + str(i), self.profiles[i]["layer"].name(), None, QApplication.UnicodeUTF8))
            self.groupBox[i].setObjectName("groupBox" + str(i))

            self.verticalLayout.append( QVBoxLayout(self.groupBox[i]) )
            self.verticalLayout[i].setObjectName("verticalLayout")
            #The table
            self.tableView.append( QTableView(self.groupBox[i]) )
            self.tableView[i].setObjectName("tableView" + str(i))
            font = QFont("Arial", 8)
            columns = len(self.profiles[i]["l"])
            rowNames = self.profiles[i].keys()
            rowNames.remove("layer") # holds the QgsMapLayer instance
            rowNames.remove("l") # holds the band number
            rows = len(rowNames)
            self.mdl = QStandardItemModel(rows+1, columns)
            self.mdl.setVerticalHeaderLabels(["band"] + rowNames)
            for j in range(columns):
                self.mdl.setData(self.mdl.index(0, j, QModelIndex()), str(self.profiles[i]["l"][j]))
                self.mdl.setData(self.mdl.index(0, j, QModelIndex()), font ,Qt.FontRole)
                for k in range(rows):
                    self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), str(self.profiles[i][rowNames[k]][j]))
                    self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), font ,Qt.FontRole)
            #self.tableView[i].setVerticalHeaderLabels(rowNames)
            self.tableView[i].verticalHeader().setDefaultSectionSize(18)
            self.tableView[i].horizontalHeader().setDefaultSectionSize(60)
            self.tableView[i].setModel(self.mdl)
            self.verticalLayout[i].addWidget(self.tableView[i])

            self.horizontalLayout = QHBoxLayout()

            #the copy to clipboard button
            self.profilePushButton.append( QPushButton(self.groupBox[i]) )
            sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.profilePushButton[i].sizePolicy().hasHeightForWidth())
            self.profilePushButton[i].setSizePolicy(sizePolicy)
            self.profilePushButton[i].setText(QApplication.translate("GroupBox", "Copy to clipboard", None, QApplication.UnicodeUTF8))
            self.profilePushButton[i].setObjectName(str(i))
            self.horizontalLayout.addWidget(self.profilePushButton[i])

            self.horizontalLayout.addStretch(0)
            self.verticalLayout[i].addLayout(self.horizontalLayout)

            self.VLayout.addWidget(self.groupBox[i])
            QObject.connect(self.profilePushButton[i], SIGNAL("clicked()"), self.copyTable)
class PSIEstGuessRateParSpacePlot(QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #self.prm = prm
     
            
        self.pchs = ["o", "s", "v", "p", "h", "8", "*", "x", "+", "d", ",", "^", "<", ">", "1", "2", "3", "4", "H", "D", ".", "|", "_"]  


        mpl.rcParams['xtick.major.size'] = 6
        mpl.rcParams['xtick.minor.size'] = 4
        mpl.rcParams['xtick.major.width'] = 1
        mpl.rcParams['xtick.minor.width'] = 1
        mpl.rcParams['ytick.major.size'] = 9
        mpl.rcParams['ytick.minor.size'] = 5
        mpl.rcParams['ytick.major.width'] = 0.8
        mpl.rcParams['ytick.minor.width'] = 0.8
        mpl.rcParams['xtick.direction'] = 'out'
        mpl.rcParams['ytick.direction'] = 'out'
        mpl.rcParams['font.size'] = 14
        mpl.rcParams['figure.facecolor'] = 'white'
        mpl.rcParams['lines.color'] = 'black'
        mpl.rcParams['axes.prop_cycle'] = cycler('color', ["#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"])

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(figsize=(8,8))#facecolor=self.canvasColor, dpi=self.dpi)
        self.ax4 = self.fig.add_subplot(231) #stimulus
        self.ax1 = self.fig.add_subplot(232) #midpoint
        self.ax2 = self.fig.add_subplot(233) #slope
        self.ax5 = self.fig.add_subplot(234) #guess
        self.ax3 = self.fig.add_subplot(235) #lapse

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
        self.ntb = NavigationToolbar(self.canvas, self.mw)
      

        self.logAxisMidpoint = QCheckBox(self.tr("Stim./Midpoint Log Axis"))
        self.logAxisMidpoint.stateChanged[int].connect(self.toggleMidpointLogAxis)

        self.logAxisSlope = QCheckBox(self.tr("Slope Log Axis"))
        self.logAxisSlope.stateChanged[int].connect(self.toggleSlopeLogAxis)

        self.logAxisGuess = QCheckBox(self.tr("Guess Log Axis"))
        self.logAxisGuess.stateChanged[int].connect(self.toggleGuessLogAxis)

        self.logAxisLapse = QCheckBox(self.tr("Lapse Log Axis"))
        self.logAxisLapse.stateChanged[int].connect(self.toggleLapseLogAxis)

        self.updateButton = QPushButton(self.tr("Update"), self)
        self.updateButton.setIcon(QIcon.fromTheme("view-refresh", QIcon(":/view-refresh")))
        self.updateButton.clicked.connect(self.onClickUpdateButton)
        
        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.logAxisMidpoint)
        self.ntbBox.addWidget(self.logAxisSlope)
        self.ntbBox.addWidget(self.logAxisGuess)
        self.ntbBox.addWidget(self.logAxisLapse)
        self.ntbBox.addWidget(self.updateButton)
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)

        self.getPSIPars()
        if self.stimScaling == "Linear":
            self.logAxisMidpoint.setChecked(False)
            self.plotDataMidpoint()
            self.plotDataStimulus()
        elif self.stimScaling == "Logarithmic":
            self.logAxisMidpoint.setChecked(True)
            self.plotDataMidpointLogAxis()
            self.plotDataStimulusLogAxis()

        if self.slopeSpacing == "Linear":
            self.logAxisSlope.setChecked(False)
            self.plotDataSlope()
        elif self.slopeSpacing == "Logarithmic":
            self.logAxisSlope.setChecked(True)
            self.plotDataSlopeLogAxis()

        if self.guessSpacing == "Linear":
            self.logAxisGuess.setChecked(False)
            self.plotDataGuess()
        elif self.guessSpacing == "Logarithmic":
            self.logAxisGuess.setChecked(True)
            self.plotDataGuessLogAxis()

        if self.lapseSpacing == "Linear":
            self.logAxisLapse.setChecked(False)
            self.plotDataLapse()
        elif self.lapseSpacing == "Logarithmic":
            self.logAxisLapse.setChecked(True)
            self.plotDataLapseLogAxis()

        self.fig.suptitle(self.tr("PSI Parameter Space"))
        self.show()
        self.canvas.draw()

    def getPSIPars(self):

        self.psyFun = self.parent().psyFunChooser.currentText()
        self.loStim = self.parent().currLocale.toDouble(self.parent().loStim.text())[0]
        self.hiStim = self.parent().currLocale.toDouble(self.parent().hiStim.text())[0]
        self.stimGridStep = self.parent().currLocale.toDouble(self.parent().stimGridStep.text())[0]
        self.stimScaling = self.parent().stimScalingChooser.currentText()
        self.loMidPoint = self.parent().currLocale.toDouble(self.parent().loMidPoint.text())[0]
        self.hiMidPoint = self.parent().currLocale.toDouble(self.parent().hiMidPoint.text())[0]
        self.threshGridStep = self.parent().currLocale.toDouble(self.parent().threshGridStep.text())[0]
        self.threshPrior = self.parent().threshPriorChooser.currentText()
        self.threshPriorMu = self.parent().currLocale.toDouble(self.parent().threshPriorMu.text())[0]
        self.threshPriorSTD = self.parent().currLocale.toDouble(self.parent().threshPriorSTD.text())[0]
        self.loSlope = self.parent().currLocale.toDouble(self.parent().loSlope.text())[0]
        self.hiSlope = self.parent().currLocale.toDouble(self.parent().hiSlope.text())[0]
        self.slopeGridStep =  self.parent().currLocale.toDouble(self.parent().slopeGridStep.text())[0]
        self.slopeSpacing = self.parent().slopeSpacingChooser.currentText()
        self.slopePrior = self.parent().slopePriorChooser.currentText()
        self.slopePriorMu = self.parent().currLocale.toDouble(self.parent().slopePriorMu.text())[0]
        self.slopePriorSTD = self.parent().currLocale.toDouble(self.parent().slopePriorSTD.text())[0]

        self.loGuess = self.parent().currLocale.toDouble(self.parent().loGuess.text())[0]
        self.hiGuess = self.parent().currLocale.toDouble(self.parent().hiGuess.text())[0]
        self.guessGridStep =  self.parent().currLocale.toDouble(self.parent().guessGridStep.text())[0]
        self.guessSpacing = self.parent().guessSpacingChooser.currentText()
        self.guessPrior = self.parent().guessPriorChooser.currentText()
        self.guessPriorMu = self.parent().currLocale.toDouble(self.parent().guessPriorMu.text())[0]
        self.guessPriorSTD = self.parent().currLocale.toDouble(self.parent().guessPriorSTD.text())[0]
        
        self.loLapse = self.parent().currLocale.toDouble(self.parent().loLapse.text())[0]
        self.hiLapse = self.parent().currLocale.toDouble(self.parent().hiLapse.text())[0]
        self.lapseGridStep =  self.parent().currLocale.toDouble(self.parent().lapseGridStep.text())[0]
        self.lapseSpacing = self.parent().lapseSpacingChooser.currentText()
        self.lapsePrior = self.parent().lapsePriorChooser.currentText()
        self.lapsePriorMu = self.parent().currLocale.toDouble(self.parent().lapsePriorMu.text())[0]
        self.lapsePriorSTD = self.parent().currLocale.toDouble(self.parent().lapsePriorSTD.text())[0]
        ##self.nAlternatives = int(self.parent().nAlternativesChooser.currentText())

        self.margLapse = self.parent().margLapseChooser.currentText()
        self.margSlope = self.parent().margSlopeChooser.currentText()
        self.margGuess = self.parent().margGuessChooser.currentText()
        self.margThresh = self.parent().margThreshChooser.currentText()

        if self.margThresh == "Yes" or self.margSlope == "Yes" or self.margGuess == "Yes" or self.margLapse == "Yes":
            ax = np.array([])
            if self.margThresh == "Yes":
                ax = numpy.append(ax, 0)
            if self.margSlope == "Yes":
                ax = numpy.append(ax, 1)
            if self.margGuess == "Yes":
                ax = numpy.append(ax, 2)
            if self.margLapse == "Yes":
                ax = numpy.append(ax, 3)
            ax = tuple(np.sort(ax))
        else:
            ax = None

        if self.stimScaling == "Linear":
            self.PSI = setupPSIEstGuessRate(model=self.psyFun,
                                x0=1,
                                xLim=(self.loStim, self.hiStim),
                                xStep=self.stimGridStep,
                                stimScale=self.stimScaling,
                                alphaLim=(self.loMidPoint, self.hiMidPoint),
                                alphaStep=self.threshGridStep,
                                alphaSpacing="Linear",
                                alphaDist=self.threshPrior,
                                alphaMu=self.threshPriorMu,
                                alphaSTD=self.threshPriorSTD,
                                betaLim=(self.loSlope, self.hiSlope),
                                betaStep=self.slopeGridStep,
                                betaSpacing=self.slopeSpacing,
                                betaDist=self.slopePrior,
                                betaMu=self.slopePriorMu,
                                betaSTD=self.slopePriorSTD,
                                gammaLim=(self.loGuess, self.hiGuess),
                                gammaStep=self.guessGridStep,
                                gammaSpacing=self.guessSpacing,
                                gammaDist=self.guessPrior,
                                gammaMu=self.guessPriorMu,
                                gammaSTD=self.guessPriorSTD,
                                lambdaLim=(self.loLapse, self.hiLapse),
                                lambdaStep=self.lapseGridStep,
                                lambdaSpacing=self.lapseSpacing,
                                lambdaDist=self.lapsePrior,
                                lambdaMu=self.lapsePriorMu,
                                lambdaSTD=self.lapsePriorSTD,
                                marginalize = ax)
        elif self.stimScaling == "Logarithmic":
            self.PSI = setupPSIEstGuessRate(model=self.psyFun,
                                x0=1,
                                xLim=(abs(self.loStim), abs(self.hiStim)),
                                xStep=self.stimGridStep,
                                stimScale=self.stimScaling,
                                alphaLim=(abs(self.loMidPoint), abs(self.hiMidPoint)),
                                alphaStep=self.threshGridStep,
                                alphaSpacing="Linear",
                                alphaDist=self.threshPrior,
                                alphaMu=abs(self.threshPriorMu),
                                alphaSTD=self.threshPriorSTD,
                                betaLim=(self.loSlope, self.hiSlope),
                                betaStep=self.slopeGridStep,
                                betaSpacing=self.slopeSpacing,
                                betaDist=self.slopePrior,
                                betaMu=self.slopePriorMu,
                                betaSTD=self.slopePriorSTD,
                                gammaLim=(self.loGuess, self.hiGuess),
                                gammaStep=self.guessGridStep,
                                gammaSpacing=self.guessSpacing,
                                gammaDist=self.guessPrior,
                                gammaMu=self.guessPriorMu,
                                gammaSTD=self.guessPriorSTD,
                                lambdaLim=(self.loLapse, self.hiLapse),
                                lambdaStep=self.lapseGridStep,
                                lambdaSpacing=self.lapseSpacing,
                                lambdaDist=self.lapsePrior,
                                lambdaMu=self.lapsePriorMu,
                                lambdaSTD=self.lapsePriorSTD,
                                marginalize = ax)

    
    def plotDataMidpoint(self):
        self.ax1.clear()
        self.A = setPrior(self.PSI["a"], self.PSI["par"]["alpha"])
        
        if self.stimScaling == "Linear":
            markerline, stemlines, baseline = self.ax1.stem(self.PSI["alpha"], self.A[:,0,0,0], 'k')
        elif self.stimScaling == "Logarithmic":
            markerline, stemlines, baseline = self.ax1.stem(exp(self.PSI["alpha"]), self.A[:,0,0,0]/exp(self.PSI["alpha"]), 'k')
            if self.loStim < 0:
                self.ax1.set_xticklabels(list(map(str, -self.ax1.get_xticks())))
                
        plt.setp(markerline, 'markerfacecolor', 'k')
        nAlpha = len(self.A[:,0,0])
        self.ax1.set_title("Midpoint, #Points " + str(nAlpha))

    def plotDataSlope(self):
        self.ax2.clear()
        self.B = setPrior(self.PSI["b"], self.PSI["par"]["beta"])
        if self.PSI["par"]["beta"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax2.stem(self.PSI["beta"], self.B[0,:,0,0], 'k')
        elif self.PSI["par"]["beta"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax2.stem(self.PSI["beta"], self.B[0,:,0,0]/self.PSI["beta"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nBeta = len(self.B[0,:,0,0])
        self.ax2.set_title("Slope, #Points " + str(nBeta))

    def plotDataGuess(self):
        self.ax5.clear()
        self.G = setPrior(self.PSI["g"], self.PSI["par"]["gamma"])
        if self.PSI["par"]["gamma"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax5.stem(self.PSI["gamma"], self.G[0,0,:,0], 'k')
        elif self.PSI["par"]["gamma"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax5.stem(self.PSI["gamma"], self.G[0,0,:,0]/self.PSI["gamma"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nGamma = len(self.G[0,0,:,0])
        self.ax5.set_title("Guess, #Points " + str(nGamma))

    def plotDataLapse(self):
        self.ax3.clear()
        L = setPrior(self.PSI["l"], self.PSI["par"]["lambda"])
        if self.PSI["par"]["lambda"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax3.stem(self.PSI["lambda"], L[0,0,0,:], 'k')
        elif self.PSI["par"]["lambda"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax3.stem(self.PSI["lambda"], L[0,0,0,:]/self.PSI["lambda"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nLambda = len(L[0,0,0,:])
        self.ax3.set_title("Lapse, #Points " + str(nLambda))

    def plotDataStimulus(self):
        self.ax4.clear()

        nStim = len(self.PSI["stims"])
        if self.stimScaling == "Linear":
            markerline, stemlines, baseline = self.ax4.stem(self.PSI["stims"], np.ones(nStim), 'k')
        elif self.stimScaling == "Logarithmic":
            markerline, stemlines, baseline = self.ax4.stem(exp(self.PSI["stims"]), np.ones(nStim), 'k')
            if self.loStim < 0:
                self.ax4.set_xticklabels(list(map(str, -self.ax4.get_xticks())))
            
        plt.setp(markerline, 'markerfacecolor', 'k')
        self.ax4.set_title("Stimulus, #Points " + str(nStim))


    def plotDataMidpointLogAxis(self):
        self.ax1.clear()
        self.A = setPrior(self.PSI["a"], self.PSI["par"]["alpha"])

        if self.stimScaling == "Logarithmic":
            x = self.PSI["alpha"]
            markerline, stemlines, baseline = self.ax1.stem(x, self.A[:,0,0,0], 'k')
        elif self.stimScaling == "Linear":
            x = log(self.PSI["alpha"])
            markerline, stemlines, baseline = self.ax1.stem(x, self.A[:,0,0,0]*self.PSI["alpha"], 'k')

        setLogTicks(self.ax1, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        nAlpha = len(self.A[:,0,0,0])
        self.ax1.set_title("Midpoint, #Points " + str(nAlpha))

    def plotDataSlopeLogAxis(self):
        self.ax2.clear()
        self.B = setPrior(self.PSI["b"], self.PSI["par"]["beta"])
        if self.PSI["par"]["beta"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax2.stem(log(self.PSI["beta"]), self.B[0,:,0,0], 'k')
        elif self.PSI["par"]["beta"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax2.stem(log(self.PSI["beta"]), self.B[0,:,0,0]*self.PSI["beta"], 'k')

        setLogTicks(self.ax2, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        
        nBeta = len(self.B[0,:,0,0])
        self.ax2.set_title("Slope, #Points " + str(nBeta))

    def plotDataGuessLogAxis(self):
        self.ax5.clear()
        self.G = setPrior(self.PSI["g"], self.PSI["par"]["gamma"])
        if self.PSI["par"]["gamma"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax5.stem(log(self.PSI["gamma"]), self.G[0,0,:,0], 'k')
        elif self.PSI["par"]["gamma"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax5.stem(log(self.PSI["gamma"]), self.G[0,0,:,0]*self.PSI["gamma"], 'k')
        setLogTicks(self.ax5, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        nGamma = len(self.G[0,0,:,0])
        self.ax5.set_title("Guess, #Points " + str(nGamma))

    def plotDataLapseLogAxis(self):
        self.ax3.clear()
        L = setPrior(self.PSI["l"], self.PSI["par"]["lambda"])
        if self.PSI["par"]["lambda"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax3.stem(log(self.PSI["lambda"]), L[0,0,0,:], 'k')
        elif self.PSI["par"]["lambda"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax3.stem(log(self.PSI["lambda"]), L[0,0,0,:]*self.PSI["lambda"], 'k')
        setLogTicks(self.ax3, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        nLambda = len(L[0,0,0,:])
        self.ax3.set_title("Lapse, #Points " + str(nLambda))

    def plotDataStimulusLogAxis(self):
        self.ax4.clear()

        nStim = len(self.PSI["stims"])
        if self.stimScaling == "Logarithmic":
            x = self.PSI["stims"]
        elif self.stimScaling == "Linear":
            x = log(self.PSI["stims"])
            
        markerline, stemlines, baseline = self.ax4.stem(x, np.ones(nStim), 'k')
        setLogTicks(self.ax4, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        self.ax4.set_title("Stimulus, #Points " + str(nStim))

    def onClickUpdateButton(self):
        self.getPSIPars()
        
        if self.logAxisMidpoint.isChecked() == False:
            self.plotDataMidpoint()
            self.plotDataStimulus()
        else:
            self.plotDataMidpointLogAxis()
            self.plotDataStimulusLogAxis()

        if self.logAxisSlope.isChecked() == False:
            self.plotDataSlope()
        else:
            self.plotDataSlopeLogAxis()

        if self.logAxisGuess.isChecked() == False:
            self.plotDataGuess()
        else:
            self.plotDataGuessLogAxis()

        if self.logAxisLapse.isChecked() == False:
            self.plotDataLapse()
        else:
            self.plotDataLapseLogAxis()

        self.canvas.draw()
        
    def toggleMidpointLogAxis(self):
        if self.logAxisMidpoint.isChecked() == True:
            self.plotDataMidpointLogAxis()
            self.plotDataStimulusLogAxis()
        else:
            self.plotDataMidpoint()
            self.plotDataStimulus()
        self.canvas.draw()

    def toggleSlopeLogAxis(self):
        if self.logAxisSlope.isChecked() == True:
            self.plotDataSlopeLogAxis()
        else:
            self.plotDataSlope()
        self.canvas.draw()

    def toggleGuessLogAxis(self):
        if self.logAxisGuess.isChecked() == True:
            self.plotDataGuessLogAxis()
        else:
            self.plotDataGuess()
        self.canvas.draw()

    def toggleLapseLogAxis(self):
        if self.logAxisLapse.isChecked() == True:
            self.plotDataLapseLogAxis()
        else:
            self.plotDataLapse()
        self.canvas.draw()