예제 #1
0
파일: plot_panel.py 프로젝트: blattms/ert
    def __init__(self, name, debug_name, plot_url):
        QWidget.__init__(self)

        self.__name = name
        self.__debug_name = debug_name
        self.__ready = False
        self.__html_ready = False
        self.__data = PlotData("invalid", parent=self)

        root_path = os.getenv("ERT_SHARE_PATH")
        path = os.path.join(root_path, plot_url)

        layout = QGridLayout()

        self.web_view = PlotWebView(debug_name)
        self.applyContextObject()
        # self.web_view.page().mainFrame().javaScriptWindowObjectCleared.connect(self.applyContextObject)
        self.web_view.loadFinished.connect(self.loadFinished)

        layout.addWidget(self.web_view)

        self.setLayout(layout)

        self.web_view.setUrl(QUrl("file://%s" % path))

        self.__plot_is_visible = True
예제 #2
0
 def __InitUi(self):
     SetWidgetBackgroundColor(COLOR_WIDGET_7, self)
     self.setFixedHeight(120)
     
     self.__grdLayout = QGridLayout()
     self.setLayout(self.__grdLayout)
     self.__grdLayout.setContentsMargins(30,0,30,30)
     self.__grdLayout.setHorizontalSpacing(0)
     self.__grdLayout.setVerticalSpacing(0)
     
     self.__wdgBar = QWidget()
     self.__grdLayout.addWidget(self.__wdgBar)
     SetWidgetBackgroundColor(COLOR_WIDGET_3, self.__wdgBar)
     
     self.__grdBarLayout = QGridLayout()
     self.__wdgBar.setLayout(self.__grdBarLayout)
     self.__grdBarLayout.setContentsMargins(30,30,30,30)
     self.__grdBarLayout.setHorizontalSpacing(30)
     self.__grdBarLayout.setVerticalSpacing(0)
     
     self.__intOpenChats = 0
     
     self.__AddButton("Computerfreaks")
     self.__AddButton("Computerfreaks")
     self.__AddButton("Computerfreaks")
     self.__AddButton("Computerfreaks")
     self.__AddButton("Computerfreaks")
     self.__AddButton("Computerfreaks")
예제 #3
0
파일: utils.py 프로젝트: albfan/mikidown
    def __init__(self, path, parent=None):
        super(LineEditDialog, self).__init__(parent)
        self.path = path

        # newPage/newSubpage
        if parent.objectName() in ["mikiWindow", "notesTree"]:
            editorLabel = QLabel("Page Name:")
            self.extNames = [".md", ".markdown", ".mkd"]
        # Copy Image to notesEdit
        elif parent.objectName() == "notesEdit":
            editorLabel = QLabel("File Name:")
            self.extNames = ["", ".jpg"]
        else:
            return

        self.editor = QLineEdit()
        editorLabel.setBuddy(self.editor)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        layout = QGridLayout()
        layout.addWidget(editorLabel, 0, 0)
        layout.addWidget(self.editor, 0, 1)
        layout.addWidget(self.buttonBox, 1, 1)
        self.setLayout(layout)

        self.editor.textEdited.connect(self.updateUi)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
예제 #4
0
    def __init__(self, zeros):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.__zeros = zeros
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Zeros"))
        self.__layout = QGridLayout()

        self.__zeroLabels = []
        self.__zeroChecks = []

        displayButton = False

        self.__scrollLayout = QGridLayout()

        for i in range(len(self.__zeros)):
            msg = "- vertex " + str(self.__zeros[i][0])
            msg += QCoreApplication.translate("VDLTools", ", elevation : '0', ")
            if self.__zeros[i][1] is not None:
                msg += QCoreApplication.translate("VDLTools", "interpolated elevation : ")
                msg += str(self.__zeros[i][1]) + "m"
                if self.__zeros[i][2] > 1:
                    msg += QCoreApplication.translate("VDLTools", " (and apply to point)")
                msgCheck = QCheckBox()
                msgCheck.setChecked(True)
                self.__zeroChecks.append(msgCheck)
                self.__scrollLayout.addWidget(self.__zeroChecks[i], i+1, 2)
                displayButton = True
            else:
                msg += QCoreApplication.translate("VDLTools", "no interpolated elevation")
                self.__zeroChecks.append(None)

            zeroLabel = QLabel(msg)
            self.__zeroLabels.append(zeroLabel)
            self.__scrollLayout.addWidget(self.__zeroLabels[i], i+1, 0, 1, 2)

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

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(widget)

        self.__layout.addWidget(scroll, 1, 0, 1, 2)

        self.__passButton = QPushButton(QCoreApplication.translate("VDLTools", "Pass"))
        self.__passButton.setMinimumHeight(20)
        self.__passButton.setMinimumWidth(100)

        pos = len(self.__zeros) + 1
        self.__layout.addWidget(self.__passButton, pos, 0)

        self.__applyButton = QPushButton(QCoreApplication.translate("VDLTools", "Apply interpolation"))
        self.__applyButton.setMinimumHeight(20)
        self.__applyButton.setMinimumWidth(100)
        if displayButton:
            self.__layout.addWidget(self.__applyButton, pos, 1)

        self.setLayout(self.__layout)
예제 #5
0
    def __init__(self, vertexes, colors, colormap=None, parent=None):
        from graphics.pyqtgraph.GradientWidget import BlackWhiteSlider

        QWidget.__init__(self, parent)
        v=QGridLayout(self)
        v.addWidget(MSGLCanvas3D(vertexes, colors, parent=self),0,0)
        #v.addWidget(BlackWhiteSlider(self),0,1)
예제 #6
0
class ViewAnimationForm(QWidget):
    def __init__(self, visualization, parent_widget = None):
        
        QWidget.__init__(self, parent_widget)
        self.inGui = False
        self.visualization = visualization

        size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.widgetLayout = QGridLayout(self)
        self.setSizePolicy(size)

        self.scroll = QScrollArea()
        file_path = self.visualization.get_file_path()       
        self.label = QLabel()
        
        movie = QMovie(QString(file_path), QByteArray(), self)
        movie.setCacheMode(QMovie.CacheAll)
        self.label.setMovie(movie)
        movie.start() 
        
        self.scroll.setWidget(self.label)
        self.widgetLayout.addWidget(self.scroll)

        self.tabIcon = QIcon(":/Images/Images/map.png")
        self.tabLabel = visualization.table_name

    def removeElement(self):
        return True
 def __init__(self, value, parent=None):
     QGridLayout.__init__(self)
     font = tuple_to_qfont(value)
     assert font is not None
     
     # Font family
     self.family = QFontComboBox(parent)
     self.family.setCurrentFont(font)
     self.addWidget(self.family, 0, 0, 1, -1)
     
     # Font size
     self.size = QComboBox(parent)
     self.size.setEditable(True)
     sizelist = range(6, 12) + range(12, 30, 2) + [36, 48, 72]
     size = font.pointSize()
     if size not in sizelist:
         sizelist.append(size)
         sizelist.sort()
     self.size.addItems([str(s) for s in sizelist])
     self.size.setCurrentIndex(sizelist.index(size))
     self.addWidget(self.size, 1, 0)
     
     # Italic or not
     self.italic = QCheckBox(self.tr("Italic"), parent)
     self.italic.setChecked(font.italic())
     self.addWidget(self.italic, 1, 1)
     
     # Bold or not
     self.bold = QCheckBox(self.tr("Bold"), parent)
     self.bold.setChecked(font.bold())
     self.addWidget(self.bold, 1, 2)
예제 #8
0
파일: deleteview.py 프로젝트: Ciwara/GCiss
    def __init__(self, table_p, obj, parent, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

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

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

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

        # Create the QVBoxLayout contenaire.
        vbox = QVBoxLayout()
        vbox.addLayout(title_hbox)
        vbox.addLayout(report_hbox)
        vbox.addLayout(Button_hbox)
        self.setLayout(vbox)
예제 #9
0
class EditPane(QWidget):
    def __init__(self, model):
        QWidget.__init__(self)
        self._setupUi()
        self.model = model
        self.model.view = self
        
        self.normalButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Normal))
        self.titleButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Title))
        self.footnoteButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Footnote))
        self.ignoreButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Ignored))
        self.tofixButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.ToFix))
        self.hideIgnoredCheckBox.stateChanged.connect(self.hideIgnoredCheckBoxStateChanged)
        self.textEdit.textChanged.connect(self.textEditTextChanged)
        self.saveEditsButton.clicked.connect(self.model.save_edits)
        self.cancelEditsButton.clicked.connect(self.model.cancel_edits)
        
    def _setupUi(self):
        self.mainLayout = QVBoxLayout(self)
        self.buttonLayout = QGridLayout()
        self.normalButton = QPushButton("Normal")
        self.buttonLayout.addWidget(self.normalButton, 0, 0)
        self.titleButton = QPushButton("Title")
        self.buttonLayout.addWidget(self.titleButton, 1, 0)
        self.footnoteButton = QPushButton("Footnote")
        self.buttonLayout.addWidget(self.footnoteButton, 2, 0)
        self.ignoreButton = QPushButton("Ignore")
        self.buttonLayout.addWidget(self.ignoreButton, 0, 1)
        self.tofixButton = QPushButton("To Fix")
        self.buttonLayout.addWidget(self.tofixButton, 1, 1)
        self.mainLayout.addLayout(self.buttonLayout)
        
        self.rightLayout = QVBoxLayout()
        self.hideIgnoredCheckBox = QCheckBox("Hide Ignored Elements")
        self.rightLayout.addWidget(self.hideIgnoredCheckBox)
        self.textEdit = QTextEdit()
        self.textEdit.setAcceptRichText(False)
        self.rightLayout.addWidget(self.textEdit)
        self.editButtonLayout = QHBoxLayout()
        self.editButtonLayout.addItem(horizontalSpacer())
        self.saveEditsButton = QPushButton("Save")
        self.editButtonLayout.addWidget(self.saveEditsButton)
        self.cancelEditsButton = QPushButton("Cancel")
        self.editButtonLayout.addWidget(self.cancelEditsButton)
        self.rightLayout.addLayout(self.editButtonLayout)
        self.mainLayout.addLayout(self.rightLayout)
        
    #--- Signals
    def hideIgnoredCheckBoxStateChanged(self, state):
        self.model.app.hide_ignored = state == Qt.Checked
    
    def textEditTextChanged(self):
        self.model.edit_text = self.textEdit.toPlainText()
    
    #--- model -> view
    def refresh_edit_text(self):
        self.textEdit.setText(self.model.edit_text)
        self.textEdit.setEnabled(self.model.edit_enabled)
        self.saveEditsButton.setEnabled(self.model.edit_enabled)
        self.cancelEditsButton.setEnabled(self.model.edit_enabled)
예제 #10
0
    def __init__(self, show_strength=True, parent=None):
        super(PinMatrixWidget, self).__init__(parent)
        
        self.password = QLineEdit()
        self.password.setValidator(QRegExpValidator(QRegExp('[1-9]+'), None))
        self.password.setEchoMode(QLineEdit.Password)
        QObject.connect(self.password, SIGNAL('textChanged(QString)'), self._password_changed)

        self.strength = QLabel()
        self.strength.setMinimumWidth(75)
        self.strength.setAlignment(Qt.AlignCenter)
        self._set_strength(0)

        grid = QGridLayout()
        grid.setSpacing(0)
        for y in range(3)[::-1]:
            for x in range(3):
                button = PinButton(self.password, x + y * 3 + 1)
                button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
                button.setFocusPolicy(Qt.NoFocus)
                grid.addWidget(button, 3 - y, x)

        hbox = QHBoxLayout()
        hbox.addWidget(self.password)
        if show_strength:
            hbox.addWidget(self.strength)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
예제 #11
0
    def _add_component_boxes(self):
        
        # ECU Box
        self.ecu_box_wid = QScrollArea()
        wid = QWidget()
        self.ecu_box_wid.setWidget(wid)        
        self.ecu_box_wid.setWidgetResizable(True)               
        self.ecu_box = QGridLayout()
        wid.setLayout(self.ecu_box)   
        self.ecu_box_wid_wid = wid     
        self.comps_layout.addWidget(self.ecu_box_wid)

        # Bus Box
        self.bus_box_wid = QScrollArea()
        wid = QWidget()
        self.bus_box_wid.setWidget(wid)        
        self.bus_box_wid.setWidgetResizable(True)             
        self.bus_box = QGridLayout()
        wid.setLayout(self.bus_box)    
        self.bus_box_wid_wid = wid      
        self.comps_layout.addWidget(self.bus_box_wid)

        # Others Box
        self.others_box_wid = QScrollArea()
        wid = QWidget()
        self.others_box_wid.setWidget(wid)        
        self.others_box_wid.setWidgetResizable(True)       
        self.others_box = QGridLayout()
        wid.setLayout(self.others_box)
        self.others_box_wid_wid = wid  
        self.comps_layout.addWidget(self.others_box_wid)
예제 #12
0
def main():
    """Main function to run the example."""
    app = QApplication([])

    default_value_parameter = DefaultValueParameter()
    default_value_parameter.name = 'Value parameter'
    default_value_parameter.help_text = 'Help text'
    default_value_parameter.description = 'Description'
    default_value_parameter.labels = [
        'Setting', 'Do not report', 'Custom']
    default_value_parameter.options = [0, 1, None]

    parameters = [
        default_value_parameter
    ]

    extra_parameters = [
        (DefaultValueParameter, DefaultValueParameterWidget)
    ]

    parameter_container = ParameterContainer(
        parameters, extra_parameters=extra_parameters)
    parameter_container.setup_ui()

    widget = QWidget()
    layout = QGridLayout()
    layout.addWidget(parameter_container)

    widget.setLayout(layout)
    widget.setGeometry(0, 0, 500, 500)

    widget.show()

    sys.exit(app.exec_())
예제 #13
0
파일: gui.py 프로젝트: robertbasic/ape
    def __init__(self, parent):
        self.parent = parent

        self.parent.setAttribute(Qt.WA_DeleteOnClose)
        
        text = QPlainTextEdit(self.parent)

        lineNumbers = QPlainTextEdit(self.parent)
        lineNumbers.setMaximumWidth(20)
        lineNumbers.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        lineNumbers.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        lineNumbers.setFrameShape(QFrame.StyledPanel)
        lineNumbers.setFrameShadow(QFrame.Plain)
        lineNumbers.setEnabled(False)

        grid = QGridLayout(self.parent)
        grid.addWidget(lineNumbers, 0, 0, 1, 1)
        grid.addWidget(text, 0, 1, 1, 1)

        text.blockCountChanged.connect(self.parent.setLineNumbers)
        text.updateRequest.connect(self.parent.scrollLineNumbers)
        text.cursorPositionChanged.connect(self.parent.highlightCurrentLine)
        text.document().contentsChanged.connect(self.parent.documentModified)

        self.parent.text = text
        self.parent.lineNumbers = lineNumbers
예제 #14
0
 def __init__(self, strip, parent=None):
     super(LEDDialog,self).__init__(parent)
     self.strip = strip
     self.buttons = []
     layout = QVBoxLayout()
     btnlayout = QGridLayout()
     self.btnmapper = QSignalMapper()
     for i in xrange(int(self.strip.config['nleds'])):
         p = QPushButton()
         p.setFixedWidth(40)
         p.setFlat(True)
         p.setAutoFillBackground(True)
         self.btnmapper.setMapping( p, i)
         p.clicked.connect( self.btnmapper.map)
         self.buttons += [[p,QColor()]]
         btnlayout.addWidget(p, i/self.rowwidth, i%self.rowwidth)
     self.btnmapper.mapped['int'].connect(self.chooseColor)
     layout.addLayout(btnlayout)
     ctrllayout = QHBoxLayout()
     p = QPushButton("Refresh")
     p.clicked.connect(self.refresh)
     ctrllayout.addWidget(p)
     p = QPushButton("Set")
     p.clicked.connect(self.set)
     ctrllayout.addWidget(p)
     p = QPushButton("Close")
     p.clicked.connect(self.close)
     ctrllayout.addWidget(p)
     layout.addLayout(ctrllayout)
     self.setLayout( layout)
     self.refresh()
예제 #15
0
  def __init__( self, wizard, title, fields ):

    ## construct a new QWizardPage
    QWizardPage.__init__( self, wizard )
    self.wizard = wizard

    ## this will store widgets created from fields
    self.widgets = {}

    self.setTitle( title )

    layout = QGridLayout( self )
    self.setLayout( layout )

    ## create and add widget for each field at this page
    ## for each field we add a label with it's name and the widget 
    ## describing the field
    ## @sa Field
    i = 0
    for field in fields:
      item = Field( self, field.name, field.value, field.extra )
      self.widgets[field.name] = item
      self.widgets[field.name].id = i

      if not callable( field.value ):
        label = QLabel( field.name.replace( '_', ' ' ) )
        layout.addWidget( label, i , 0 )

      layout.addWidget( self.widgets[field.name].widget, i, 1 )
      i+=1
예제 #16
0
class AboutDialog(QDialog):
    """
    Common About Dialog for the Freeseer Project. This should be used for the
    about dialog when including one in GUIs.


    Grid Layout:

    Logo  |  About Infos
    ------|-------------
          |  Close Button
    """
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.aboutWidget = AboutWidget()

        icon = QIcon()
        icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.layout.addWidget(self.aboutWidget)

        # Right Bottom corner of grid, Close Button
        self.buttonBox = QDialogButtonBox()
        self.closeButton = self.buttonBox.addButton("Close", QDialogButtonBox.AcceptRole)
        self.layout.addWidget(self.buttonBox, 1, 1)
        self.connect(self.closeButton, SIGNAL("clicked()"), self.close)

        self.setWindowTitle("About Freeseer")
예제 #17
0
class Option(QWidget):
   
    def __init__(self):
        QWidget.__init__(self)
        self.resize(168, 86)
        self.name = "Progress"
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setMargin(0)
        self.label_2 = QLabel(self)
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.spinBox = QSpinBox(self)
        self.spinBox.setMinimum(60)
        self.spinBox.setMaximum(600)
        self.gridLayout.addWidget(self.spinBox, 0, 2, 1, 1)
        self.spinBox_2 = QSpinBox(self)
        self.spinBox_2.setMinimum(120)
        self.spinBox_2.setMaximum(600)
        self.spinBox_2.setProperty("value", 600)
        self.gridLayout.addWidget(self.spinBox_2, 1, 2, 1, 1)
        self.label = QLabel(self)

        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)

        self.label_2.setText(u"Max Süre(dk):")
        self.label.setText(u"Min. Süre(dk):")
예제 #18
0
class QuadHistogram(QWidget):
    '''A class which uses ColorHistogram to draw
    the 4 histograms of an image. R, G, B, and Value.

    The 4 histograms are layout out in a grid,
    and can be specified horizontal or vertical,
    and in which order ie. ['R', 'G', 'B', 'V']
    '''

    def __init__(self, img, layout='vertical', order=['R', 'G', 'B', 'V']):
        QWidget.__init__(self)
        r, g, b, v = histograms(img, 100)
        self.r_hist = ColorHistogram(r, (255, 0, 0))
        self.g_hist = ColorHistogram(g, (0, 255, 0))
        self.b_hist = ColorHistogram(b, (0, 0, 255))
        self.v_hist = ColorHistogram(v, (0, 0, 0))

        self.layout = QGridLayout(self)

        order_map = {'R': self.r_hist, 'G': self.g_hist, 'B': self.b_hist,
                     'V': self.v_hist}

        if layout=='vertical':
            for i in range(len(order)):
                self.layout.addWidget(order_map[order[i]], i, 0)
        elif layout=='horizontal':
            for i in range(len(order)):
                self.layout.addWidget(order_map[order[i]], 0, i)

    def update_hists(self, img):
        r, g, b, v = histograms(img, 100)
        self.r_hist.update_hist(r, (255, 0, 0))
        self.g_hist.update_hist(g, (0, 255, 0))
        self.b_hist.update_hist(b, (0, 0, 255))
        self.v_hist.update_hist(v, (0, 0, 0))
예제 #19
0
파일: mail.py 프로젝트: maximerobin/Ufwi
    def __init__(self, client, parent):
        ScrollArea.__init__(self)
        self.client = client
        self.mainwindow = parent
        self._modified = False
        self.error_message = ''
        self.config = None
        frame = QFrame(self)
        layout = QGridLayout(frame)

        title = QLabel(u'<H1>%s</H1>' % tr('Contact Configuration'))
        layout.addWidget(title, 0, 0)

        self.admin_mail = self.buildAdminMail(layout, 1, 0)
        self.sender_mail = self.buildSenderMail(layout, 2, 0)
        self.smarthost_group, self.use_smarthost, self.mail_relay = \
            self.buildOutgoing(layout, 3, 0)
        self.language = self.buildChooseLanguage(layout, 4, 0)
        self.buildTestMail(layout, 5, 0)
        layout.setRowStretch(6, 15)

        self.setWidget(frame)
        self.setWidgetResizable(True)

        self.resetConf()
        self.mainwindow.addToInfoArea(tr('Contact interface enabled'))
예제 #20
0
class StrokesWatcher(QWidget):
    """Main module's widget"""
    def __init__(self, path):
        super(StrokesWatcher, self).__init__()
        self.path = path
        self.strokes_order, letters = get_letters(path)
        self.setup_ui()
        self.stroke_list = StrokeList(letters,
                                      self.strokes_order,
                                      self.display)

        self.letter_selector.setModel(self.stroke_list.keys_model)

        self.list_view.setModel(self.stroke_list)

        self.letter_selector.currentIndexChanged.connect(self.select_letter)

        self.set_letter_btn.clicked.connect(self.change_letter)

    def change_letter(self):
        new_key = str(self.letter_edt.text())

        indexes = self.list_view.selectedIndexes()

        if new_key and indexes:
            new_key = new_key[0]
            self.stroke_list.change_stroke_key(indexes[0], new_key, self.path)

    def select_letter(self):
        # set stroke_list key_letter to the one
        # choosen by letter_selector
        new_letter = self.letter_selector.currentText()
        self.stroke_list.set_key_letter(new_letter)

    def setup_ui(self):
        self.resize(800, 480)
        self.grid = QGridLayout(self)

        self.display = pg.PlotWidget(name='st', background='w')

        add_circles(self.display, (1, 2))

        self.grid.addWidget(self.display, 0, 0, 2, 2)

        self.display.getViewBox().setXRange(-np.pi, np.pi)
        self.display.getViewBox().setYRange(-np.pi / 2, np.pi / 2)
        self.display.getViewBox().setAspectLocked()

        self.list_view = QListView(self)
        self.grid.addWidget(self.list_view, 0, 2, 1, 2)

        self.letter_selector = QComboBox(self)
        self.grid.addWidget(self.letter_selector, 1, 2, 1, 2)

        self.letter_edt = QLineEdit(self)
        self.grid.addWidget(self.letter_edt, 2, 2, 1, 1)

        self.set_letter_btn = QPushButton(self)
        self.set_letter_btn.setText('Set')
        self.grid.addWidget(self.set_letter_btn, 2, 3, 1, 1)
예제 #21
0
    def createElectricalSimulationSettingsTab(self):

        widget = QWidget()
        layout = QtGui.QGridLayout()
        widget.setLayout(layout)

        layout.addWidget(QLabel('Simulation dt'), 0, 0)
        layout.addWidget(self.electricalSimulationDt, 0, 1)

        layout.addWidget(QLabel('Plot Update Interval'), 2, 0)
        layout.addWidget(self.electricalPlotUpdateInterval, 2, 1)

        layout.addWidget(QLabel('GUI Update Interval'), 3, 0)
        layout.addWidget(self.electricalGuiUpdateInterval, 3, 1)

        # layout.addWidget(QLabel('Default Runtime'), 4, 0)
        # layout.addWidget(self.electricalDefaultSimulationRuntime, 4, 1)

        # layout.addWidget(QLabel('Solver'), 5, 0)

        index = 0
        for solver in self.electricalSolvers:
            # layout.addWidget(self.electricalSolvers[solver], 5 + index, 1)
            self.electricalSolver.addButton(self.electricalSolvers[solver], index)
            self.electricalSolvers[solver].setFocusPolicy(PyQt4.QtCore.Qt.NoFocus)
            index += 1

        self.electricalSolver.setExclusive(True)
        buttonLayout = QGridLayout()
        layout.addLayout(buttonLayout, 5 + index, 1)
        buttonLayout.addWidget(self.electricalSimulationCancel, 0, 0, Qt.Qt.AlignRight)
        buttonLayout.addWidget(self.electricalSimulationApply, 0, 1, Qt.Qt.AlignLeft)

        return widget
예제 #22
0
    def init(self, parent):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        # Initialize the facet handler to use:
        facet_handler = self.factory.facet_handler
        if facet_handler is None:
            facet_handler = self.object.base_facet(self.name).handler
        self._facet_handler = facet_handler

        # Create a scrolled window to hold all of the list item controls:
        self.control = QScrollArea(parent)
        self.control.setFrameShape(QFrame.NoFrame)

        # Create a widget with a grid layout as the container.
        self._list_pane = QWidget()
        layout = QGridLayout(self._list_pane)
        layout.setMargin(0)

        # Remember the editor to use for each individual list item:
        editor = self.factory.editor
        if editor is None:
            editor = facet_handler.item_facet.get_editor()

        self._editor = getattr(editor, self.kind)

        # Set up the additional 'list items changed' event handler needed for
        # a list based facet:
        self.context_object.on_facet_set(self.update_editor_item, self.extended_name + "_items?", dispatch="ui")
        self.set_tooltip()
예제 #23
0
 def __init__(self, modelRoot):
     super(NeuroKitVisualizer, self).__init__()
     layout = QGridLayout()
     self.toolbar = self.createToolbar()
     self.textEdit = self.createTextEdit()
     layout.addWidget(self.toolbar, 0, 0, 1, -1)
     layout.addWidget(self.textEdit, 1, 0, -1, -1)
예제 #24
0
    def _clicked(self, point, button):
        if self.iface.activeLayer() is None:
            self.raise_message("no_active_layer")
            return
        # Prüfe, ob Punkt innerhalb des Features
        for feature in self.iface.activeLayer().getFeatures():
            #Falls Punkt in Features
            if feature.geometry().contains(point):
                #hole gml_id
                try:
                    gml_id = feature.attribute('gml_id')
                except KeyError:
                    self.raise_message("no_gml_id_found")
                    return
                break

        # ids = tuple(str(feature.attribute('gml_id')) for feature in selected_features)
        result = self._get_fsn_from_gml_id(gml_id)
        html = self._build_html(result[0]['flsnr'])
        parent = QDialog()
        parent.setWindowTitle(u"Eigentümerinformationen")
        parent.setParent(self.iface.mainWindow())
        parent.setWindowFlags(QtCore.Qt.Window)

        textview = QTextEdit()
        textview.setReadOnly(True)
        textview.setText(html)
        layout = QGridLayout(parent)
        layout.addWidget(textview)
        parent.resize(500, 600)
        parent.show()
예제 #25
0
   def paint_mainWindow(self):
         
      # Define and use a "Grid Layout" for the main window.
      grid = QGridLayout()
      grid.addWidget(self.textArea, 1, 1)
      grid.addWidget(self.tabs,     2, 1)
      
      # Create central widget, add layout, and set
      central_widget = QWidget()
      central_widget.setLayout(grid)
      self.setCentralWidget(central_widget)      
      
      # Fun feature for users. If you are going to have a toolbar then you 
      # really need this status bar to show what the icons do.        
      self.statusbar = QStatusBar(self) 
      self.statusbar.setObjectName( "statusbar") 
      MainWindow.setStatusBar(self, self.statusbar) 
      self.statusbar.show()
      
      # Initial settings for the main window 
      #
      #    Set the Main Window Geometry
      top    =  100 # Main Window initial 'top' position (as pixels from top of screen)
      left   =  100 # Main Window initial 'left' position (as pixels from left side of screen)
      width  = 1000 # Main Window initial 'width' (as pixels)
      height =  700 # Main Window initial 'height' (as pixels)
      self.setGeometry(QRect(top, left, width, height))  
 
      # Create connection(s)
      #    If the contents of the text area are changed then call a function 
      #    to set the appropriate file menu state. This file menu state can 
      #    also be used to ensure clean exits. In english, keep track 
      #    of changes to the text editor. It affects the "state" of the
      #    application. See setState()
      self.connect(self.textArea, SIGNAL("textChanged()"), self.textChanged)
예제 #26
0
파일: gui.py 프로젝트: philipstahl/emotutor
 def get_init_emotion_widget(self):
     layout = QGridLayout()
     layout.addWidget(QLabel("Show emotion:"), 0, 0)
     layout.addWidget(self.init, 0, 1)
     widget = QWidget()
     widget.setLayout(layout)
     return widget
예제 #27
0
class SaveSessionDialog(QDialog):
    ''' Dialog window. Allows user to choose session info to save. '''
    def __init__(self, parent, sessionmgr):
        QDialog.__init__(self, parent)
        self.setWindowTitle("Save Session")

        self.cbContainer = []
        self.layout = QGridLayout()
        self.okButton = QPushButton("Ok", self)
        self.layout.addWidget(self.okButton, 0, 2)
        self.setLayout(self.layout)
        self.SessionManager = sessionmgr
        self.okButton.released.connect(self.__showSaveFileDialog)

    def addDialogItem(self, dialogItem):
        cb = QCheckBox(dialogItem, self)
        cb.setChecked(True)
        self.layout.addWidget(cb, len(self.cbContainer), 0)
        self.setLayout(self.layout)
        self.cbContainer.append(cb)

    def __showSaveFileDialog(self):
        filename = str(QFileDialog.getSaveFileName(None, "Save Session", "", "*.xml"))
        if (filename != ""):
            self.SessionManager.saveSession(filename, self.cbContainer)
        self.close()
예제 #28
0
    def initUI(self, lcd):
        self.setStyleSheet(
            """
            QWidget{ background-color: #FFFFFF; border:1px solid #000099; }
            QPushButton{background-color: #FFCC33; color: #000099; }
            QPushButton:pressed { background-color: #FFFF00; }
            """)
        self.setFixedSize(220, 220)

        grid = QGridLayout()
        self.setLayout(grid)

        arrow_up = QPushButton("▲")
        arrow_left = QPushButton("◄")
        arrow_right = QPushButton("►")
        arrow_down = QPushButton("▼")

        arrow_up.clicked.connect(self.clicked)
        arrow_left.clicked.connect(self.clicked)
        arrow_right.clicked.connect(self.clicked)
        arrow_down.clicked.connect(self.clicked)

        elementos = [None, arrow_up, None, arrow_left,
                     lcd, arrow_right, None, arrow_down, None]

        coords = [(i, j) for i in range(3) for j in range(3)]

        for coords, element in zip(coords, elementos):
            if not element:
                continue
            grid.addWidget(element, *coords)
예제 #29
0
파일: ui.py 프로젝트: Xifax/ransukan
    def create_ui_components(self):
        """
        Create layouts and qt controls.
        """
        self.layout = QGridLayout()

        self.kanjiGroup = QGroupBox()
        self.kanjiLayout = QGridLayout()

        # Kanji ui group
        self.day, self.week, self.month, self.year = \
        QLabel(KANJI), QLabel(KANJI), QLabel(KANJI), QLabel(KANJI)

        self.dayLabel, self.weekLabel, self.monthLabel, self.yearLabel = \
        QLabel('<b>Day</b>'), QLabel('<b>Week</b>'), \
        QLabel('<b>Month</b>'), QLabel('<b>Year</b>')

        # Main layout
        self.showAbout = QPushButton('A&bout')
        # DB controls (top)
        self.showDB, self.availableDB, self.changeDB = \
        QPushButton('&Change DB (active:)'), QComboBox(), QPushButton('&Remap')
        # General controls (bottom)
        self.getAll, self.showStats, self.quitApp, self.authGen, self.methodCombo = \
        QPushButton('&Get all'), QPushButton('&Stats'), QPushButton('&Quit'), \
        QPushButton('&Auth'), QComboBox()
        # Notifications
        self.progressBar = QProgressBar()
        self.statusMessage = QLabel()
        # About
        self.aboutBox = QMessageBox()
예제 #30
0
파일: lqi.py 프로젝트: Alwnikrotikz/lilykde
    def __init__(self, toolbox):
        super(Articulations, self).__init__(toolbox, 'articulation',
            i18n("Articulations"), symbol='articulation_prall',
            tooltip=i18n("Different kinds of articulations and other signs."))
            
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        
        # help text
        self.setWhatsThis("<p>{0}</p><p>{1}</p>".format(
            i18n("Click an articulation sign to add it to your document."),
            i18n("If you select some music first, the articulation will "
              "be added to all notes in the selection.")))
        
        self.shorthands = QCheckBox(i18n("Allow shorthands"))
        self.shorthands.setChecked(True)
        self.shorthands.setToolTip(i18n(
            "Use short notation for some articulations like staccato."))
        layout.addWidget(self.shorthands)

        self.titles = dict(ly.articulation.articulations(i18n))
        for title, group in ly.articulation.groups(i18n):
            box = QGroupBox(title)
            layout.addWidget(box)
            grid = QGridLayout()
            grid.setSpacing(0)
            box.setLayout(grid)
            for num, (sign, title) in enumerate(group):
                row, col = divmod(num, COLUMNS)
                b = ActionButton(self, sign, title, 'articulation_' + sign,
                    tooltip='<b>{0}</b> (\\{1})'.format(title, sign))
                grid.addWidget(b, row, col)
        layout.addStretch()
예제 #31
0
 def _create(self, base_frame):
     self.sliders = []
     self.spinboxes = []
     for i in range(len(self.dim_labels)):
         self.sliders.append(QSlider(QtCore.Qt.Horizontal))
         self.sliders[i].setRange(0, self.n_slider_steps[i])
         self.sliders[i].valueChanged.connect(partial(
             self._on_slide, i))
         spinbox = QDoubleSpinBox()
         spinbox.setRange(*self.limits[i])
         spinbox.setDecimals(3)
         spinbox.setSingleStep(0.001)
         self.spinboxes.append(spinbox)
         self.spinboxes[i].valueChanged.connect(
             partial(self._on_pos_edited, i))
     slider_group = QGridLayout()
     slider_group.addWidget(QLabel("Position"), 0, 0, 1, 3,
                            QtCore.Qt.AlignCenter)
     slider_group.addWidget(QLabel("Orientation (Euler angles)"), 0, 3,
                            1, 3, QtCore.Qt.AlignCenter)
     for i, slider in enumerate(self.sliders):
         slider_group.addWidget(QLabel(self.dim_labels[i]), 1, i)
         slider_group.addWidget(slider, 2, i)
         slider_group.addWidget(self.spinboxes[i], 3, i)
     slider_groupbox = QGroupBox("Transformation in frame '%s'" %
                                 base_frame)
     slider_groupbox.setLayout(slider_group)
     layout = QHBoxLayout()
     layout.addWidget(slider_groupbox)
     layout.addStretch(1)
     return layout
class GenericParameterWidget(QWidget, object):
    """Widget class for generic parameter."""
    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)

    def get_parameter(self):
        """Interface for returning parameter object.

        This must be implemented in child class.

        :raises: NotImplementedError

        """
        raise NotImplementedError('Must be implemented in child class')

    def show_hide_description(self):
        """Show and hide long description."""
        if self._hide_description:
            self._hide_description = False
            self._description_label.show()
            self._switch_button.setArrowType(2)
            self._switch_button.setToolTip('Click for hide detail description')
        else:
            self._hide_description = True
            self._description_label.hide()
            self._switch_button.setArrowType(4)
            self._switch_button.setToolTip('Click for detail description')
예제 #33
0
if __name__ == "__main__":

    ev = IPETEvaluation.fromXMLFile("test/testevaluate.xml")

    app = QApplication(sys.argv)
    mainwindow = QMainWindow()
    thewidget = QWidget(mainwindow)
    treeview = IpetTreeView(thewidget)

    layout = QHBoxLayout()
    layout.addWidget(treeview)

    editframe = QFrame(thewidget)
    layout.addWidget(editframe)

    layout2 = QGridLayout()

    editframe.setLayout(layout2)

    thewidget.setLayout(layout)
    mainwindow.setCentralWidget(thewidget)
    treeview.populateTree(ev)

    def redrawEditFrameContent():
        item = treeview.selectedItems()[0]

        for i in reversed(list(range(layout2.count()))):
            layout2.itemAt(i).widget().close()
        editframecontent = EditableForm(treeview.itemGetEditable(item),
                                        editframe)
        textlabel = QLabel(("Edit attributes for %s" %
예제 #34
0
	def create_main_frame(self):
        
		self.mainFrame = QWidget()
		
		gridLayout = QGridLayout()
                       
		self.dpi = 80
		self.xpos = 0
		self.ypos = 0
				
		self.titles = [r'I',r'Q',r'U',r'V']
		
		self.readData()
		
		self.resize(1500,500)
			
# Left window
		self.leftPlot = QWidget()
		#self.leftFig = Figure(((4*self.nFrames) / self.dpi,2*self.nx / self.dpi), dpi=self.dpi)
		self.leftFig = Figure(((4*self.nFrames) / self.dpi,8), dpi=self.dpi)
		self.leftCanvas = FigureCanvas(self.leftFig)
		self.leftCanvas.setParent(self.leftPlot)
					
		self.leftAxes = [None]*4
		self.drawnMap = [None]*4
		for i in range(4):
			self.leftAxes[i] = self.leftFig.add_subplot(2,2,i+1)
			self.drawnMap[i] = self.leftAxes[i].imshow(self.maps[i], aspect='equal')
			self.leftAxes[i].set_axis_off()
		self.leftCanvas.mpl_connect('motion_notify_event', self.onMouseMove)
		self.leftCanvas.mpl_connect('scroll_event', self.onScrollMove)		
		gridLayout.addWidget(self.leftPlot, 0, 0)
		gridLayout.setSpacing(10)
		
# Central window				
		self.centralPlot = QWidget()		
		#self.centralFig = Figure((self.nWavelength / self.dpi,2*self.nx / self.dpi), dpi=self.dpi)
		self.centralFig = Figure((10,8), dpi=self.dpi)
		self.centralCanvas = FigureCanvas(self.centralFig)
		self.centralCanvas.setParent(self.centralPlot)
				
		self.slitMaps = self.getMaps(0)
		
		self.centralAxes = [None]*4
		self.drawnSlitMap = [None]*4
		for i in range(4):
			self.centralAxes[i] = self.centralFig.add_subplot(4,1,i+1)
			self.drawnSlitMap[i] = self.centralAxes[i].imshow(self.slitMaps[i,:,:])
		#self.centralCanvas.draw()
			
		gridLayout.addWidget(self.centralPlot, 0, 1)

# Right window		
		self.rightPlot = QWidget()
		self.rightFig = Figure((8,8), dpi=self.dpi)
		self.rightCanvas = FigureCanvas(self.rightFig)
		self.rightCanvas.setParent(self.rightPlot)
							
		self.stokes = self.getProfiles(0,0)
		
# Draw the axes and the first profiles
		nCols = 2
		nRows = 2
		self.axes = [None] * 4
		self.obs = [None] * 4		
		loop = 0
		for j in range(2):
			for i in range(2):
				self.axes[loop] = self.rightFig.add_subplot(nCols, nRows, loop+1)
				self.obs[loop], = self.axes[loop].plot(self.stokes[loop,:])
				loop += 1
		gridLayout.addWidget(self.rightPlot, 0, 2)		
		
		
## Tight layout and redraw
		self.rightFig.tight_layout()
		
		self.rightCanvas.draw()
				
## We are using blit animation to do it fast, so we need to recover the axes modified by tight_layout
		self.newAxes = self.figRight.get_axes()
		
## Save the backgrounds
		loop = 0
		for j in range(6):
			for i in range(4):
				self.axes[loop] = self.newAxes[loop]
				self.background[loop] = self.canvasRight.copy_from_bbox(self.axes[loop].bbox)
				loop += 1
															
		
		
		
		plotLayout.addWidget(self.rightPlot)
		
		fullLayout.addLayout(gridLayout)
		
		self.mainFrame.setLayout(gridLayout)
		self.setCentralWidget(self.mainFrame)
예제 #35
0
    def __init__(self, page):
        super(SourceExport, self).__init__(page)

        layout = QGridLayout(spacing=1)
        self.setLayout(layout)

        self.numberLines = QCheckBox(toggled=self.changed)
        self.inlineStyleCopy = QCheckBox(toggled=self.changed)
        self.copyHtmlAsPlainText = QCheckBox(toggled=self.changed)
        self.inlineStyleExport = QCheckBox(toggled=self.changed)
        self.copyDocumentBodyOnly = QCheckBox(toggled=self.changed)
        self.wrapperTag = QLabel()
        self.wrapTagSelector = QComboBox()
        self.wrapTagSelector.currentIndexChanged.connect(page.changed)
        self.wrapperAttribute = QLabel()
        self.wrapAttribSelector = QComboBox()
        self.wrapAttribSelector.currentIndexChanged.connect(page.changed)
        self.wrapAttribNameLabel = QLabel()
        self.wrapAttribName = QLineEdit()
        self.wrapAttribName.textEdited.connect(page.changed)

        # left column
        layout.addWidget(self.copyHtmlAsPlainText, 0, 0)
        layout.addWidget(self.copyDocumentBodyOnly, 1, 0)
        layout.addWidget(self.inlineStyleCopy, 2, 0)
        layout.addWidget(self.inlineStyleExport, 3, 0)
        #right column
        layout.addWidget(self.numberLines, 0, 1, 1, 2)
        layout.addWidget(self.wrapperTag, 1, 1)
        layout.addWidget(self.wrapTagSelector, 1, 2)
        layout.addWidget(self.wrapperAttribute, 2, 1)
        layout.addWidget(self.wrapAttribSelector, 2, 2)
        layout.addWidget(self.wrapAttribNameLabel, 3, 1)
        layout.addWidget(self.wrapAttribName, 3, 2)

        app.translateUI(self)
예제 #36
0
    def __init__(self, page):
        super(Indenting, self).__init__(page)

        layout = QGridLayout(spacing=1)
        self.setLayout(layout)

        self.tabwidthBox = QSpinBox(minimum=1, maximum=99)
        self.tabwidthLabel = l = QLabel()
        l.setBuddy(self.tabwidthBox)

        self.nspacesBox = QSpinBox(minimum=0, maximum=99)
        self.nspacesLabel = l = QLabel()
        l.setBuddy(self.nspacesBox)

        self.dspacesBox = QSpinBox(minimum=0, maximum=99)
        self.dspacesLabel = l = QLabel()
        l.setBuddy(self.dspacesBox)

        layout.addWidget(self.tabwidthLabel, 0, 0)
        layout.addWidget(self.tabwidthBox, 0, 1)
        layout.addWidget(self.nspacesLabel, 1, 0)
        layout.addWidget(self.nspacesBox, 1, 1)
        layout.addWidget(self.dspacesLabel, 2, 0)
        layout.addWidget(self.dspacesBox, 2, 1)

        self.tabwidthBox.valueChanged.connect(page.changed)
        self.nspacesBox.valueChanged.connect(page.changed)
        self.dspacesBox.valueChanged.connect(page.changed)
        self.translateUI()
예제 #37
0
    def initUI(self):
        cw = QWidget()
        self.setCentralWidget(cw)
        grid = QGridLayout()
        grid.setSpacing(15)

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

        font_label = QFont()
        font_label.setBold(True)
        ################ dicom reader
        rstart = 0
        text_dcm = QLabel('DICOM reader')
        text_dcm.setFont(font_label)
        self.text_dcm_dir = QLabel('DICOM dir:')
        self.text_dcm_data = QLabel('DICOM data:')
        self.text_dcm_out = QLabel('output file:')
        grid.addWidget(text_dcm, rstart + 0, 1, 1, 4)
        grid.addWidget(self.text_dcm_dir, rstart + 1, 1, 1, 4)
        grid.addWidget(self.text_dcm_data, rstart + 2, 1, 1, 4)
        grid.addWidget(self.text_dcm_out, rstart + 3, 1, 1, 4)
        btn_dcmdir = QPushButton("Load DICOM", self)
        btn_dcmdir.clicked.connect(self.loadDcmDir)
        btn_dcmred = QPushButton("Organ Segmentation", self)
        btn_dcmred.clicked.connect(self.organSegmentation)
        btn_dcmcrop = QPushButton("Crop", self)
        btn_dcmcrop.clicked.connect(self.cropDcm)
        btn_dcmsave = QPushButton("Save DCM", self)
        btn_dcmsave.clicked.connect(self.saveDcm)
        grid.addWidget(btn_dcmdir, rstart + 4, 1)
        grid.addWidget(btn_dcmred, rstart + 4, 2)
        grid.addWidget(btn_dcmcrop, rstart + 4, 3)
        grid.addWidget(btn_dcmsave, rstart + 4, 4)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        grid.addWidget(hr, rstart + 5, 0, 1, 6)

        # quit
        btn_quit = QPushButton("Quit", self)
        btn_quit.clicked.connect(self.quit)
        grid.addWidget(btn_quit, 24, 2, 1, 2)

        cw.setLayout(grid)
        self.setWindowTitle('liver-surgery')
        self.show()
예제 #38
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)
예제 #39
0
    def __init__(self, layer, feature, mapCanvas, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.settings = MySettings()
        SettingDialog.__init__(self, self.settings, False, True)
        self.mapCanvas = mapCanvas
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.feature = feature
        self.initialGeometry = QgsGeometry(feature.geometry())
        self.layer = layer

        # close if no geom, hide "sketch current point" if not needed
        geomType = layer.geometryType()
        if not geomType in (QGis.Point, QGis.Line, QGis.Polygon):
            self.close()
            return
        if geomType == QGis.Point:
            self.pointRubberGroup.hide()

        # editors management
        self.editorLayout = QGridLayout(self.editorContainer)
        self.editor = GeomEditor(layer, feature.geometry())
        self.displayCombo.setCurrentIndex(0)
        self.displayCombo.currentIndexChanged.connect(self.setEditor)
        self.setEditor()

        # rubber bands
        self.featureRubber = QgsRubberBand(mapCanvas)
        self.currentPointRubber = QgsRubberBand(mapCanvas)
        self.settings.setting("featureRubberColor").valueChanged.connect(
            self.updateFeatureRubber)
        self.settings.setting("featureRubberSize").valueChanged.connect(
            self.updateFeatureRubber)
        self.settings.setting("currentPointRubberSize").valueChanged.connect(
            self.updateCurrentPointRubber)
        self.settings.setting("currentPointRubberColor").valueChanged.connect(
            self.updateCurrentPointRubber)
        self.settings.setting("currentPointRubberIcon").valueChanged.connect(
            self.updateCurrentPointRubber)
        self.updateFeatureRubber()
        self.updateCurrentPointRubber()
        self.geometryChanged()

        # GUI signals connection
        self.applyButton.clicked.connect(self.applyGeometry)
        self.resetButton.clicked.connect(self.resetGeometry)
        self.sketchGeometry.clicked.connect(self.geometryChanged)
        self.displayPointRubber.clicked.connect(self.currentPointRubber.reset)
        self.layerEditable()
        layer.editingStopped.connect(self.layerEditable)
        layer.editingStarted.connect(self.layerEditable)

        # set texts in UI
        self.layerLabel.setText(layer.name())
        try:
            featureTitle = unicode(feature[layer.displayField()])
        except KeyError:
            featureTitle = ""
        if featureTitle == "":
            featureTitle = str(feature.id())
        self.featureEdit.setText(featureTitle)
예제 #40
0
class GeomEditorDialog(QDialog, Ui_GeomEditor, SettingDialog):
    def __init__(self, layer, feature, mapCanvas, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.settings = MySettings()
        SettingDialog.__init__(self, self.settings, False, True)
        self.mapCanvas = mapCanvas
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.feature = feature
        self.initialGeometry = QgsGeometry(feature.geometry())
        self.layer = layer

        # close if no geom, hide "sketch current point" if not needed
        geomType = layer.geometryType()
        if not geomType in (QGis.Point, QGis.Line, QGis.Polygon):
            self.close()
            return
        if geomType == QGis.Point:
            self.pointRubberGroup.hide()

        # editors management
        self.editorLayout = QGridLayout(self.editorContainer)
        self.editor = GeomEditor(layer, feature.geometry())
        self.displayCombo.setCurrentIndex(0)
        self.displayCombo.currentIndexChanged.connect(self.setEditor)
        self.setEditor()

        # rubber bands
        self.featureRubber = QgsRubberBand(mapCanvas)
        self.currentPointRubber = QgsRubberBand(mapCanvas)
        self.settings.setting("featureRubberColor").valueChanged.connect(
            self.updateFeatureRubber)
        self.settings.setting("featureRubberSize").valueChanged.connect(
            self.updateFeatureRubber)
        self.settings.setting("currentPointRubberSize").valueChanged.connect(
            self.updateCurrentPointRubber)
        self.settings.setting("currentPointRubberColor").valueChanged.connect(
            self.updateCurrentPointRubber)
        self.settings.setting("currentPointRubberIcon").valueChanged.connect(
            self.updateCurrentPointRubber)
        self.updateFeatureRubber()
        self.updateCurrentPointRubber()
        self.geometryChanged()

        # GUI signals connection
        self.applyButton.clicked.connect(self.applyGeometry)
        self.resetButton.clicked.connect(self.resetGeometry)
        self.sketchGeometry.clicked.connect(self.geometryChanged)
        self.displayPointRubber.clicked.connect(self.currentPointRubber.reset)
        self.layerEditable()
        layer.editingStopped.connect(self.layerEditable)
        layer.editingStarted.connect(self.layerEditable)

        # set texts in UI
        self.layerLabel.setText(layer.name())
        try:
            featureTitle = unicode(feature[layer.displayField()])
        except KeyError:
            featureTitle = ""
        if featureTitle == "":
            featureTitle = str(feature.id())
        self.featureEdit.setText(featureTitle)

    def setEditor(self):
        self.editorLayout.removeWidget(self.editor)
        geom = self.editor.getGeom()
        idx = self.displayCombo.currentIndex()
        if idx == -99999:
            editor = CellEditor
        elif idx == 0:
            editor = WktEditor
        elif idx == 1:
            editor = WkbEditor
        else:
            self.editor = GeomEditor
            return
        self.editor = editor(self.layer, geom, self)
        self.editorLayout.addWidget(self.editor, 0, 0, 1, 1)

        self.editor.currentPointChanged.connect(self.drawCurrentPoint)
        self.editor.geometryChanged.connect(self.geometryChanged)

    def resetGeometry(self):
        self.editor.setGeom(self.initialGeometry)

    def closeEvent(self, e):
        self.featureRubber.reset()
        self.currentPointRubber.reset()
        self.layer.editingStarted.disconnect(self.layerEditable)
        self.layer.editingStopped.disconnect(self.layerEditable)
        self.editor.closeEditor()
        QDialog.closeEvent(self, e)

    def layerEditable(self):
        layerIsEditable = self.layer.isEditable()
        self.resetButton.setEnabled(layerIsEditable)
        self.applyButton.setEnabled(layerIsEditable)

    def geometryChanged(self):
        self.featureRubber.reset()
        self.currentPointRubber.reset()
        if self.editor.isGeomValid():
            self.displayCombo.setEnabled(True)
            self.applyButton.setEnabled(self.layer.isEditable())
            geomStatus = "Geometry is valid"
            if self.sketchGeometry.isChecked():
                self.featureRubber.setToGeometry(self.editor.getGeom(),
                                                 self.layer)
        else:
            self.applyButton.setEnabled(False)
            self.displayCombo.setEnabled(False)
            geomStatus = "Geometry is not valid"
        self.geomStatusLabel.setText(geomStatus)

    @pyqtSlot(QgsGeometry)
    def drawCurrentPoint(self, point):
        if self.displayPointRubber.isChecked():
            self.currentPointRubber.setToGeometry(point, None)
            self.mapCanvas.refresh()

    def applyGeometry(self):
        geometry = self.editor.getGeom()
        if geometry is not None:
            self.layer.changeGeometry(self.feature.id(), geometry)
            self.layer.updateExtents()
            self.layer.setCacheImage(None)
            self.layer.triggerRepaint()

    def updateFeatureRubber(self):
        self.featureRubber.setColor(self.settings.value("featureRubberColor"))
        self.featureRubber.setWidth(self.settings.value("featureRubberSize"))
        self.layer.triggerRepaint()

    def updateCurrentPointRubber(self):
        self.currentPointRubber.setIconSize(
            self.settings.value("currentPointRubberSize"))
        self.currentPointRubber.setColor(
            self.settings.value("currentPointRubberColor"))
        self.currentPointRubber.setIcon(
            self.settings.value("currentPointRubberIcon"))
        self.mapCanvas.refresh()
class GroupSelectParameterWidget(GenericParameterWidget):
    """Widget class for Group Select Parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

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

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                double_spin_box = QDoubleSpinBox()
                self.radio_button_layout.addWidget(double_spin_box, i, 1)
                double_spin_box.setValue(value.get('value', 0))
                double_spin_box.setMinimum(
                    value.get('constraint', {}).get('min', 0))
                double_spin_box.setMaximum(
                    value.get('constraint', {}).get('max', 1))
                double_spin_box.setSingleStep(
                    value.get('constraint', {}).get('step', 0.01))
                step = double_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                double_spin_box.setDecimals(precision)
                self.spin_boxes[key] = double_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    double_spin_box.setEnabled(True)
                else:
                    double_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value)), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                selected_fields = value.get('value', [])
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        self.setLayout(self.main_layout)

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

        # Update list widget
        self.update_list_widget()

        # Connect signal
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)

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

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in self._parameter.options.items():
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in xrange(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.selected = None
        else:
            self._parameter.selected = self._parameter.options.keys(
            )[radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = self._parameter.options.values(
            )[radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                        | Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in self.spin_boxes.values():
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = self._parameter.options.values(
            )[radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = self._parameter.options.keys(
                )[radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = self._parameter.options.keys().index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
예제 #42
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.matrix = None
        self.items = None
        self.linkmatrix = None
        self.root = None
        self._displayed_root = None
        self.cutoff_height = 0.0

        gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"),
                     self,
                     "linkage",
                     items=LINKAGE,
                     callback=self._invalidate_clustering)

        box = gui.widgetBox(self.controlArea, "Annotation")
        self.label_cb = gui.comboBox(box,
                                     self,
                                     "annotation_idx",
                                     callback=self._update_labels)

        self.label_cb.setModel(itemmodels.VariableListModel())
        self.label_cb.model()[:] = ["None", "Enumeration"]

        box = gui.radioButtons(self.controlArea,
                               self,
                               "pruning",
                               box="Pruning",
                               callback=self._invalidate_pruning)
        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(gui.appendRadioButton(box, "None", addToLayout=False),
                       0, 0)
        self.max_depth_spin = gui.spin(box,
                                       self,
                                       "max_depth",
                                       minv=1,
                                       maxv=100,
                                       callback=self._invalidate_pruning,
                                       keyboardTracking=False)

        grid.addWidget(
            gui.appendRadioButton(box, "Max depth", addToLayout=False), 1, 0)
        grid.addWidget(self.max_depth_spin, 1, 1)

        box = gui.radioButtons(self.controlArea,
                               self,
                               "selection_method",
                               box="Selection",
                               callback=self._selection_method_changed)

        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(gui.appendRadioButton(box, "Manual", addToLayout=False),
                       0, 0)
        grid.addWidget(
            gui.appendRadioButton(box, "Height ratio", addToLayout=False), 1,
            0)
        self.cut_ratio_spin = gui.spin(box,
                                       self,
                                       "cut_ratio",
                                       0,
                                       100,
                                       step=1e-1,
                                       spinType=float,
                                       callback=self._selection_method_changed)
        self.cut_ratio_spin.setSuffix("%")

        grid.addWidget(self.cut_ratio_spin, 1, 1)

        grid.addWidget(gui.appendRadioButton(box, "Top N", addToLayout=False),
                       2, 0)
        self.top_n_spin = gui.spin(box,
                                   self,
                                   "top_n",
                                   1,
                                   20,
                                   callback=self._selection_method_changed)
        grid.addWidget(self.top_n_spin, 2, 1)
        box.layout().addLayout(grid)

        self.controlArea.layout().addStretch()

        box = gui.widgetBox(self.controlArea, "Output")
        gui.checkBox(box,
                     self,
                     "append_clusters",
                     "Append cluster IDs",
                     callback=self._invalidate_output)

        ibox = gui.indentedBox(box)
        name_edit = gui.lineEdit(ibox, self, "cluster_name")
        name_edit.editingFinished.connect(self._invalidate_output)

        cb = gui.comboBox(
            ibox,
            self,
            "cluster_role",
            callback=self._invalidate_output,
            items=["Attribute", "Class variable", "Meta variable"])
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow,
                           labelAlignment=Qt.AlignLeft,
                           spacing=8)
        form.addRow("Name", name_edit)
        form.addRow("Place", cb)

        ibox.layout().addSpacing(5)
        ibox.layout().addLayout(form)
        ibox.layout().addSpacing(5)

        gui.auto_commit(box,
                        self,
                        "autocommit",
                        "Send data",
                        "Auto send is on",
                        box=False)

        self.scene = QGraphicsScene()
        self.view = QGraphicsView(
            self.scene,
            horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
            alignment=Qt.AlignLeft | Qt.AlignVCenter)

        def axis_view(orientation):
            ax = pg.AxisItem(orientation=orientation, maxTickLength=7)
            scene = QGraphicsScene()
            scene.addItem(ax)
            view = QGraphicsView(
                scene,
                horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                alignment=Qt.AlignLeft | Qt.AlignVCenter)
            view.setFixedHeight(ax.size().height())
            ax.line = SliderLine(orientation=Qt.Horizontal,
                                 length=ax.size().height())
            scene.addItem(ax.line)
            return view, ax

        self.top_axis_view, self.top_axis = axis_view("top")
        self.mainArea.layout().setSpacing(1)
        self.mainArea.layout().addWidget(self.top_axis_view)
        self.mainArea.layout().addWidget(self.view)
        self.bottom_axis_view, self.bottom_axis = axis_view("bottom")
        self.mainArea.layout().addWidget(self.bottom_axis_view)

        self._main_graphics = QGraphicsWidget()
        self._main_layout = QGraphicsLinearLayout(Qt.Horizontal)
        self._main_layout.setSpacing(1)

        self._main_graphics.setLayout(self._main_layout)
        self.scene.addItem(self._main_graphics)

        self.dendrogram = DendrogramWidget()
        self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding,
                                      QSizePolicy.MinimumExpanding)
        self.dendrogram.selectionChanged.connect(self._invalidate_output)
        self.dendrogram.selectionEdited.connect(self._selection_edited)

        fm = self.fontMetrics()
        self.dendrogram.setContentsMargins(5,
                                           fm.lineSpacing() / 2, 5,
                                           fm.lineSpacing() / 2)
        self.labels = GraphicsSimpleTextList()
        self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.labels.setAlignment(Qt.AlignLeft)
        self.labels.setMaximumWidth(200)
        self.labels.layout().setSpacing(0)

        self._main_layout.addItem(self.dendrogram)
        self._main_layout.addItem(self.labels)

        self._main_layout.setAlignment(self.dendrogram,
                                       Qt.AlignLeft | Qt.AlignVCenter)
        self._main_layout.setAlignment(self.labels,
                                       Qt.AlignLeft | Qt.AlignVCenter)

        self.view.viewport().installEventFilter(self)
        self.top_axis_view.viewport().installEventFilter(self)
        self.bottom_axis_view.viewport().installEventFilter(self)
        self._main_graphics.installEventFilter(self)

        self.cut_line = SliderLine(self.dendrogram, orientation=Qt.Horizontal)
        self.cut_line.valueChanged.connect(self._dendrogram_slider_changed)
        self.cut_line.hide()

        self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.top_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed)
        self._set_cut_line_visible(self.selection_method == 1)
예제 #43
0
    def __init__(self):
        QWizardPage.__init__(self)
        self.setTitle('New Project Data')
        self.setSubTitle(
            'Complete the following fields to create the Project Structure')

        g_box = QGridLayout(self)
        #Names of the blanks to complete
        self.lbl_Name = QLabel('New Project Name:')
        self.lbl_Place = QLabel('Project Location:')
        self.lbl_Folder = QLabel('Projet Folder:')
        self.lbl_Description = QLabel('Project Description:')
        self.lbl_License = QLabel('Project License:')
        g_box.addWidget(self.lbl_Name, 0, 0, Qt.AlignRight)
        g_box.addWidget(self.lbl_Place, 1, 0, Qt.AlignRight)
        g_box.addWidget(self.lbl_Folder, 2, 0, Qt.AlignRight)
        g_box.addWidget(self.lbl_Description, 3, 0, Qt.AlignTop)
        g_box.addWidget(self.lbl_License, 4, 0, Qt.AlignRight)

        #Blanks on de right of the grid
        self.txtName = QLineEdit()
        self.registerField('projectName*', self.txtName)
        #Here comes a LineEdit and a PushButton in a HBoxLayout
        h_Place = QHBoxLayout()
        self.txtPlace = QLineEdit()
        self.txtPlace.setReadOnly(True)
        self.registerField('place*', self.txtPlace)
        self.btnExamine = QPushButton('Examine...')
        h_Place.addWidget(self.txtPlace)
        h_Place.addWidget(self.btnExamine)
        #Now lets continue with the rest
        self.txtFolder = QLineEdit()
        self.txtDescription = QPlainTextEdit()
        self.cboLicense = QComboBox()
        self.cboLicense.setFixedWidth(250)
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        g_box.addWidget(self.txtName, 0, 1)
        g_box.addLayout(h_Place, 1, 1)
        g_box.addWidget(self.txtFolder, 2, 1)
        g_box.addWidget(self.txtDescription, 3, 1)
        g_box.addWidget(self.cboLicense, 4, 1)

        #Signal
        self.connect(self.btnExamine, SIGNAL('clicked()'), self.load_folder)
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

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

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                double_spin_box = QDoubleSpinBox()
                self.radio_button_layout.addWidget(double_spin_box, i, 1)
                double_spin_box.setValue(value.get('value', 0))
                double_spin_box.setMinimum(
                    value.get('constraint', {}).get('min', 0))
                double_spin_box.setMaximum(
                    value.get('constraint', {}).get('max', 1))
                double_spin_box.setSingleStep(
                    value.get('constraint', {}).get('step', 0.01))
                step = double_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                double_spin_box.setDecimals(precision)
                self.spin_boxes[key] = double_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    double_spin_box.setEnabled(True)
                else:
                    double_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value)), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                selected_fields = value.get('value', [])
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        self.setLayout(self.main_layout)

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

        # Update list widget
        self.update_list_widget()

        # Connect signal
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)
예제 #45
0
class SecondAndHalfStepWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        self.deviceOrderWidgets = list()
        self.tDeviceManager = TangoDeviceManager()
        self.currentWidgetIndex = -1

        self.setMinimumHeight(667)
        self.setMinimumWidth(942)

        self.setupButtons()

    def setupButtons(self):
        previousStepButton = QPushButton(self)
        previousStepButton.setText("Previous step")
        previousStepButton.setStyleSheet("background-color:red;color:white;")
        previousStepButton.setFixedWidth(600)
        self.layout.addWidget(previousStepButton, 0, 0, QtCore.Qt.AlignHCenter)
        self.connect(previousStepButton, QtCore.SIGNAL("clicked()"), QtCore.SIGNAL("previousStep()"))

        nextStepButton = QPushButton(self)
        nextStepButton.setText("Next step")
        nextStepButton.setStyleSheet("background-color:green;color:white;")
        nextStepButton.setFixedWidth(500)
        self.layout.addWidget(nextStepButton, 0, 1, QtCore.Qt.AlignHCenter)
        self.connect(nextStepButton, QtCore.SIGNAL("clicked()"), self.saveSettingsBeforeNextStep)

        self.sectionLabel = QLabel(self)
        self.sectionLabel.setText("")
        self.sectionLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.layout.addWidget(self.sectionLabel, 1, 0, 1, -1, QtCore.Qt.AlignTop | QtCore.Qt.AlignHCenter)

        previousSectionButton = QPushButton(self)
        previousSectionButton.setText("Previous section")
        self.layout.addWidget(previousSectionButton, 2, 0)
        self.connect(previousSectionButton, QtCore.SIGNAL("clicked()"), self.previousSection)

        nextSectionButton = QPushButton(self)
        nextSectionButton.setText("Next section")
        self.layout.addWidget(nextSectionButton, 2, 1)
        self.connect(nextSectionButton, QtCore.SIGNAL("clicked()"), self.nextSection)

    def previousSection(self):
        if self.currentWidgetIndex > 0:
            self.changeWidget(-1)

    def nextSection(self):
        if self.currentWidgetIndex+1 < len(self.deviceOrderWidgets):
            self.changeWidget(1)

    def changeWidget(self, diff):
        self.layout.removeWidget(self.deviceOrderWidgets[self.currentWidgetIndex])
        self.deviceOrderWidgets[self.currentWidgetIndex].setVisible(False)
        self.currentWidgetIndex += diff
        self.layout.addWidget(self.deviceOrderWidgets[self.currentWidgetIndex], 3, 0, 1, -1, QtCore.Qt.AlignHCenter)
        self.deviceOrderWidgets[self.currentWidgetIndex].setVisible(True)
        self.showSectionName()

    def showSectionName(self):
        sectionWidget = self.deviceOrderWidgets[self.currentWidgetIndex]
        sectionName = sectionWidget.section.longName
        labelString = "Section "
        labelString += sectionName
        self.sectionLabel.setText(labelString)

    def setSectionsData(self, linacData, ringData):
        self.svgDrawer = SvgDrawer()
        sectionsProcessor = SectionsDataProcesssor(self.svgDrawer)
        sectionsProcessor.processLinacSections(linacData)
        sectionsProcessor.processRingSections(ringData)
        self.sections = self.svgDrawer.getAllSections()

    def createDeviceWidgets(self):
        self.clearWidgets()
        devices = self.tDeviceManager.getDevicesWithoutParameters()
        self.svgDrawer.addDeviceToAccelerator(devices)
        for section in self.sections:
            widget =  DeviceOrderWidget()
            widget.setSection(section)
            widget.setVisible(False)
            self.deviceOrderWidgets.append(widget)
        if len(self.deviceOrderWidgets) > 0:
            self.currentWidgetIndex = 0
            self.deviceOrderWidgets[0].setVisible(True)
            self.layout.addWidget(self.deviceOrderWidgets[0], 3, 0, 1, -1, QtCore.Qt.AlignHCenter)
            self.showSectionName()

    def clearWidgets(self):
        for widget in self.deviceOrderWidgets:
            widget.setVisible(False)
            self.layout.removeWidget(widget)
            del widget
        del self.deviceOrderWidgets[:]

    def saveSettingsBeforeNextStep(self):
        linacSectionNumber = 1
        ringSectionNumber = 1
        for sectionOrderWidget in self.deviceOrderWidgets:
            if isinstance(sectionOrderWidget.section, LinacSection):
                self.processLinacSection(sectionOrderWidget, linacSectionNumber)
                linacSectionNumber += 1
            else:
                self.processRingSection(sectionOrderWidget, ringSectionNumber)
                ringSectionNumber += 1
        self.emit(QtCore.SIGNAL("nextStep()"))

    def processLinacSection(self, sectionOrderWidget, number):
        sortedDevices = sectionOrderWidget.getSortedDevices()
        yCoord = 0
        baseXCoord = number * 100
        deviceNumber = 1
        for device in sortedDevices:
            xCoord = baseXCoord + deviceNumber
            device.realCoordinates = [float(xCoord), float(yCoord)]
            self.tDeviceManager.putDeviceParametersIntoDb(device)
            deviceNumber += 1

    def processRingSection(self, sectionOrderWidget, number):
        sortedDevices = sectionOrderWidget.getSortedDevices()
        deviceNumber = 0
        baseAngle = (360.0 / len(self.deviceOrderWidgets)) * number
        for device in sortedDevices:
            angle = baseAngle + deviceNumber
            [xCoord, yCoord] = ArcDrawingTools.polarToCartesian(0, 0, 1, angle)
            device.realCoordinates = [float(xCoord), float(yCoord)]
            self.tDeviceManager.putDeviceParametersIntoDb(device)
            deviceNumber -= 1
예제 #46
0
    def __createLayout(self):
        " Creates the dialog layout "
        self.resize(640, 480)
        self.setSizeGripEnabled(True)

        vboxLayout = QVBoxLayout(self)

        hLayout = QHBoxLayout()
        self.__propsView = QTreeWidget()
        self.__propsView.setAlternatingRowColors(True)
        self.__propsView.setRootIsDecorated(False)
        self.__propsView.setItemsExpandable(False)
        self.__propsView.setSortingEnabled(True)
        self.__propsView.setItemDelegate(NoOutlineHeightDelegate(4))
        self.__propsView.itemSelectionChanged.connect(
            self.__propsSelectionChanged)

        propsViewHeader = QTreeWidgetItem(["Property Name", "Property Value"])
        self.__propsView.setHeaderItem(propsViewHeader)
        self.__propsView.header().setSortIndicator(0, Qt.DescendingOrder)
        hLayout.addWidget(self.__propsView)

        self.__delButton = QToolButton()
        self.__delButton.setText("Delete")
        self.__delButton.setFocusPolicy(Qt.NoFocus)
        self.__delButton.setEnabled(False)
        self.__delButton.clicked.connect(self.__onDel)
        hLayout.addWidget(self.__delButton, 0, Qt.AlignBottom)
        vboxLayout.addLayout(hLayout)

        # Set property part
        setGroupbox = QGroupBox(self)
        setGroupbox.setTitle("Set Property")

        setLayout = QGridLayout(setGroupbox)
        setLayout.addWidget(QLabel("Name"), 0, 0, Qt.AlignTop | Qt.AlignRight)
        setLayout.addWidget(QLabel("Value"), 1, 0, Qt.AlignTop | Qt.AlignRight)

        self.__nameEdit = QLineEdit()
        self.__nameEdit.textChanged.connect(self.__nameChanged)
        setLayout.addWidget(self.__nameEdit, 0, 1)

        self.__valueEdit = QTextEdit()
        self.__valueEdit.setAcceptRichText(False)
        self.__valueEdit.textChanged.connect(self.__valueChanged)
        metrics = QFontMetrics(self.__valueEdit.font())
        rect = metrics.boundingRect("X")
        self.__valueEdit.setFixedHeight(rect.height() * 4 + 5)
        setLayout.addWidget(self.__valueEdit, 1, 1)

        self.__setButton = QToolButton()
        self.__setButton.setText("Set")
        self.__setButton.setFocusPolicy(Qt.NoFocus)
        self.__setButton.setEnabled(False)
        self.__setButton.clicked.connect(self.__onSet)
        setLayout.addWidget(self.__setButton, 1, 2,
                            Qt.AlignBottom | Qt.AlignHCenter)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            setGroupbox.sizePolicy().hasHeightForWidth())
        setGroupbox.setSizePolicy(sizePolicy)
        vboxLayout.addWidget(setGroupbox)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
        buttonBox.accepted.connect(self.close)
        vboxLayout.addWidget(buttonBox)
        return
예제 #47
0
    def set_up_resource_parameters(self):
        """Set up the resource parameter for the add/edit view.
        """
        name_parameter = StringParameter('UUID-1')
        name_parameter.name = self.resource_parameters['Resource name']
        name_parameter.help_text = tr(
            'Name of the resource that will be provided '
            'as part of minimum needs. '
            'e.g. Rice, Water etc.')
        name_parameter.description = tr(
            'A <b>resource</b> is something that you provide to displaced '
            'persons in the event of a disaster. The resource will be made '
            'available at IDP camps and may need to be stockpiled by '
            'contingency planners in their preparations for a disaster.')
        name_parameter.is_required = True
        name_parameter.value = ''

        description_parameter = StringParameter('UUID-2')
        description_parameter.name = self.resource_parameters[
            'Resource description']
        description_parameter.help_text = tr(
            'Description of the resource that will be provided as part of '
            'minimum needs.')
        description_parameter.description = tr(
            'This gives a detailed description of what the resource is and ')
        description_parameter.is_required = True
        description_parameter.value = ''

        unit_parameter = StringParameter('UUID-3')
        unit_parameter.name = self.resource_parameters['Unit']
        unit_parameter.help_text = tr(
            'Single unit for the resources spelled out. e.g. litre, '
            'kilogram etc.')
        unit_parameter.description = tr(
            'A <b>unit</b> is the basic measurement unit used for computing '
            'the allowance per individual. For example when planning water '
            'rations the unit would be single litre.')
        unit_parameter.is_required = True
        unit_parameter.value = ''

        units_parameter = StringParameter('UUID-4')
        units_parameter.name = self.resource_parameters['Units']
        units_parameter.help_text = tr(
            'Multiple units for the resources spelled out. e.g. litres, '
            'kilogram etc.')
        units_parameter.description = tr(
            '<b>Units</b> are the basic measurement used for computing the '
            'allowance per individual. For example when planning water '
            'rations the units would be litres.')
        units_parameter.is_required = True
        units_parameter.value = ''

        unit_abbreviation_parameter = StringParameter('UUID-5')
        unit_abbreviation_parameter.name = \
            self.resource_parameters['Unit abbreviation']
        unit_abbreviation_parameter.help_text = tr(
            'Abbreviations of unit for the resources. e.g. l, kg etc.')
        unit_abbreviation_parameter.description = tr(
            "A <b>unit abbreviation</b> is the basic measurement unit's "
            "shortened. For example when planning water rations "
            "the units would be l.")
        unit_abbreviation_parameter.is_required = True
        unit_abbreviation_parameter.value = ''

        minimum_parameter = FloatParameter('UUID-6')
        minimum_parameter.name = self.resource_parameters['Minimum allowed']
        minimum_parameter.is_required = True
        minimum_parameter.precision = 2
        minimum_parameter.minimum_allowed_value = -99999.0
        minimum_parameter.maximum_allowed_value = 99999.0
        minimum_parameter.help_text = tr(
            'The minimum allowable quantity per person. ')
        minimum_parameter.description = tr(
            'The <b>minimum</b> is the minimum allowed quantity of the '
            'resource per person. For example you may dictate that the water '
            'ration per person per day should never be allowed to be less '
            'than 0.5l. This is enforced when tweaking a minimum needs set '
            'before an impact evaluation')
        minimum_parameter.value = 0.00

        maximum_parameter = FloatParameter('UUID-7')
        maximum_parameter.name = self.resource_parameters['Maximum allowed']
        maximum_parameter.is_required = True
        maximum_parameter.precision = 2
        maximum_parameter.minimum_allowed_value = -99999.0
        maximum_parameter.maximum_allowed_value = 99999.0
        maximum_parameter.help_text = tr(
            'The maximum allowable quantity per person. ')
        maximum_parameter.description = tr(
            'The <b>maximum</b> is the maximum allowed quantity of the '
            'resource per person. For example you may dictate that the water '
            'ration per person per day should never be allowed to be more '
            'than 67l. This is enforced when tweaking a maximum needs set '
            'before an impact evaluation.')
        maximum_parameter.value = 100.0

        default_parameter = FloatParameter('UUID-8')
        default_parameter.name = self.resource_parameters['Default']
        default_parameter.is_required = True
        default_parameter.precision = 2
        default_parameter.minimum_allowed_value = -99999.0
        default_parameter.maximum_allowed_value = 99999.0
        default_parameter.help_text = tr(
            'The default allowable quantity per person. ')
        default_parameter.description = tr(
            "The <b>default</b> is the default allowed quantity of the "
            "resource per person. For example you may indicate that the water "
            "ration per person weekly should be 67l.")
        default_parameter.value = 10.0

        frequency_parameter = StringParameter('UUID-9')
        frequency_parameter.name = self.resource_parameters['Frequency']
        frequency_parameter.help_text = tr(
            "The frequency that this resource needs to be provided to a "
            "displaced person. e.g. weekly, daily, once etc.")
        frequency_parameter.description = tr(
            "The <b>frequency</b> informs the aid worker how regularly this "
            "resource needs to be provided to the displaced person.")
        frequency_parameter.is_required = True
        frequency_parameter.value = tr('weekly')

        sentence_parameter = TextParameter('UUID-10')
        sentence_parameter.name = self.resource_parameters['Readable sentence']
        sentence_parameter.help_text = tr(
            'A readable presentation of the resource.')
        sentence_parameter.description = tr(
            "A <b>readable sentence</b> is a presentation of the resource "
            "that displays all pertinent information. If you are unsure then "
            "use the default. Properties should be included using double "
            "curly brackets '{{' '}}'. Including the resource name would be "
            "achieved by including e.g. {{ Resource name }}")
        sentence_parameter.is_required = True
        sentence_parameter.value = tr(
            'A displaced person should be provided with '
            '%(default value)s %(unit)s/%(units)s/%(unit abbreviation)s of '
            '%(resource name)s. Though no less than %(minimum allowed)s '
            'and no more than %(maximum allowed)s. This should be provided '
            '%(frequency)s.' % {
                'default value': '{{ Default }}',
                'unit': '{{ Unit }}',
                'units': '{{ Units }}',
                'unit abbreviation': '{{ Unit abbreviation }}',
                'resource name': '{{ Resource name }}',
                'minimum allowed': '{{ Minimum allowed }}',
                'maximum allowed': '{{ Maximum allowed }}',
                'frequency': '{{ Frequency }}'
            })

        parameters = [
            name_parameter, description_parameter, unit_parameter,
            units_parameter, unit_abbreviation_parameter, default_parameter,
            minimum_parameter, maximum_parameter, frequency_parameter,
            sentence_parameter
        ]
        parameter_container = ParameterContainer(parameters)
        parameter_container.setup_ui()

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(parameter_container)
        self.parameters_scrollarea.setLayout(layout)
예제 #48
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)
예제 #49
0
    def __init__(self, pvname, savedValue, liveValue=None, parent=None):
        super(ShowArrayValueDlg, self).__init__(parent)
        self.setWindowTitle('waveform data')

        self.savedValue = savedValue
        self.liveValue = liveValue
        # create table
        tableview = self.createTable()

        # add label
        pvnameLabel = QLabel()
        label = 'Saved value (%d data points)' % (len(savedValue))
        if liveValue != None:
            label += ' and live value (%d data points)' % (len(liveValue))

        label += ' for\n' + pvname
        pvnameLabel.setText(label)

        #add Close button
        self.quit = QPushButton('Close Widget', self)
        self.quit.resize(self.quit.sizeHint())
        self.connect(self.quit, SIGNAL('clicked()'), self.close)

        #add plot figure
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        #plot the waveform data
        self.plotWfData()

        # layout
        #layout = QVBoxLayout(self)
        layout = QGridLayout(self)
        # add pvname label
        layout.addWidget(pvnameLabel)
        #add table view
        layout.addWidget(tableview)
        #add plot stuff and push button
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.quit)
        self.setLayout(layout)
예제 #50
0
class widget_ctrl_run(QWidget):

    #-----------------------------------------------------------------------
    # DEFINE THE INITIALIZATION FUNCTION.
    #-----------------------------------------------------------------------

    def __init__(self, core):

        # Inherit all attributes of an instance of "QWidget".

        super(widget_ctrl_run, self).__init__()

        # Store the Janus core.

        self.core = core

        # Prepare to respond to signals received from the Janus core.

        self.connect(self.core, SIGNAL('janus_chng_spc'), self.resp_chng_spc)
        self.connect(self.core, SIGNAL('janus_done_auto_run'),
                     self.resp_done_auto_run)

        # Give this widget a grid layout, "self.grd".

        self.grd = QGridLayout()

        self.setLayout(self.grd)

        # Initialize the primary buttons.

        self.btn_mom = event_PushButton(self, 'mom', 'Moments')
        self.btn_nln = event_PushButton(self, 'nln', 'Non-Linear')
        self.btn_opt = event_PushButton(self, 'opt', 'Options')
        self.btn_auto = event_PushButton(self, 'auto', 'Auto-Run')

        # Initialize and configure the stop button.

        self.btn_stop = event_PushButton(self, 'stop', 'Stop')

        self.btn_stop.setStyleSheet('QPushButton {color:red}')

        self.btn_stop.setVisible(False)

        # Add the buttons to this widget's grid.

        self.grd.addWidget(self.btn_stop, 1, 1, 1, 1)

        self.grd.addWidget(self.btn_mom, 0, 0, 1, 1)
        self.grd.addWidget(self.btn_nln, 0, 1, 1, 1)
        self.grd.addWidget(self.btn_opt, 1, 0, 1, 1)
        self.grd.addWidget(self.btn_auto, 1, 1, 1, 1)

        # Intialize the variables that will store the user's last
        # requested settings for the automatic analysis.

        self.req_auto_strt = ''
        self.req_auto_stop = ''
        self.req_auto_next = False
        self.req_auto_halt = True

        # Initialize the variable that will hold the progress-bar dialog
        # (if an when one is created).

        self.dia_prog = None

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO A USER-INITIATED EVENT.
    #-----------------------------------------------------------------------

    def user_event(self, event, fnc):

        # If the stop button has been pressed, inform the core to abort
        # the automatic analysis.

        if (fnc == 'stop'):

            # Set the core's indicator of a premature-stop request
            # to "True".

            self.core.stop_auto_run = True

            # Return.

            return

        # If a "thread_*" computation thread is running, abort.

        if (n_thread() != 0):
            return

        # If the "Moments" or "Non-Linear" button has been pressed,
        # execute the requested analysis and return.

        if (fnc == 'mom'):
            if (n_thread() == 0):
                Thread(target=thread_anls_mom, args=(self.core, )).start()
            return

        if (fnc == 'nln'):
            if (n_thread() == 0):
                Thread(target=thread_anls_nln, args=(self.core, )).start()
            return

        # If the "Options" button has been pressed, launch a dialog box
        # that will allow the user to alter various settings.

        if (fnc == 'opt'):

            # WARNING!  THIS FEATURE IS INCOMPLETE.  DURING
            #           DEVELOPMENT, IT IS ONLY AVAILABLE IN
            #           DEBUGGING MODE.

            # If debugging mode is not active, alert the user and
            # abort.

            if (not self.core.debug):
                dialog_missing().alert()
                return

            # Return.

            return

        # If the "Auto" button has been pressed, launch the auto-run
        # dialog box.  If the user-input is valid, start a thread to run
        # the reqested analyses on the specified spectra, enable the
        # "stop" button, and return.

        if (fnc == 'auto'):

            # WARNING!  THIS FEATURE IS INCOMPLETE.  DURING
            #           DEVELOPMENT, IT IS ONLY AVAILABLE IN
            #           DEBUGGING MODE.

            # If debugging mode is not active, alert the user and
            # abort.

            if (not self.core.debug):
                dialog_missing().alert()
                return

            # Attempt to find suggested settings for the automated
            # analysis based on the current spectrum loaded (if any)
            # and the previous requests of the user.

            self.req_auto_strt = self.core.time_txt

            if (self.req_auto_strt == ''):
                self.req_auto_stop = ''
                self.req_auto_next = False
            else:
                self.req_auto_next = True
                if (self.req_auto_stop != ''):
                    epc_strt = calc_time_epc(self.req_auto_strt)
                    epc_stop = calc_time_epc(self.req_auto_stop)
                    if ((epc_strt is None) or (epc_stop is None)):
                        self.req_auto_stop = ''
                    elif (epc_strt >= epc_stop):
                        self.req_auto_stop = ''

            # Launch a dialog box to request a range of times from
            # the user.

            time_rang = dialog_auto_ctrl(
                time_strt=self.req_auto_strt,
                time_stop=self.req_auto_stop,
                get_next=self.req_auto_next).get_time_rang()

            # If the range of times is invalid (which can happen if
            # the user cancels the dialog), return.

            if (time_rang is None):
                return

            # Store the new requested times from the user.

            self.req_auto_strt = time_rang[0]
            self.req_auto_stop = time_rang[1]
            self.req_auto_next = time_rang[2]
            self.req_auto_halt = time_rang[3]

            # Assuming that there still aren't any janus threads
            # running, start a new thread for the automatic analysis
            # and make the "stop" button available for the user to
            # abort that analysis (if so desired).

            if (n_thread() == 0):

                # Start a new thread that automatically loads
                # and processes each spectrum in the time range
                # specified by the user.

                Thread(target=thread_auto_run,
                       args=(self.core, self.req_auto_strt, self.req_auto_stop,
                             self.req_auto_next, self.req_auto_halt,
                             1)).start()

                # Hide the "auto" button and make the "stop"
                # button visible (so that the user can abort the
                # automatic analyis).

                self.btn_auto.setVisible(False)
                self.btn_stop.setVisible(True)

                self.dia_prog = dialog_auto_prog(self.req_auto_strt,
                                                 self.req_auto_stop)

            # Return.

            return

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO LOADING OF A NEW SPECTRUM.
    #-----------------------------------------------------------------------

    def resp_chng_spc(self):

        # If a progress-bar dialog exists, request that it update based
        # on the timestamp of the new spectrum.

        if ((self.dia_prog is not None) and (self.core.time_val is not None)):
            self.dia_prog.updt_bar(self.core.time_val)

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO THE COMPLETION OF AN AUTO-RUN.
    #-----------------------------------------------------------------------

    def resp_done_auto_run(self):

        # Hide the "stop" button and make the "auto" button visible.

        self.btn_stop.setVisible(False)
        self.btn_auto.setVisible(True)

        # Close the progress-bar dialog (if one exists).

        if (self.dia_prog is not None):
            self.dia_prog.close()
예제 #51
0
class LayerItemWidget(QWidget):
    @property
    def layer(self):
        return self._layer

    @layer.setter
    def layer(self, layer):
        if self._layer:
            self._layer.changed.disconnect(self._updateState)
        self._layer = layer
        self._updateState()
        self._layer.changed.connect(self._updateState)

    def __init__(self, parent=None):
        super(LayerItemWidget, self).__init__(parent=parent)
        self._layer = None

        self._font = QFont(QFont().defaultFamily(), 9)
        self._fm = QFontMetrics(self._font)
        self.bar = FractionSelectionBar(initial_fraction=0.)
        self.bar.setFixedHeight(10)
        self.nameLabel = QLabel(parent=self)
        self.nameLabel.setFont(self._font)
        self.nameLabel.setText("None")
        self.opacityLabel = QLabel(parent=self)
        self.opacityLabel.setAlignment(Qt.AlignRight)
        self.opacityLabel.setFont(self._font)
        self.opacityLabel.setText(u"\u03B1=%0.1f%%" % (100.0 *
                                                       (self.bar.fraction())))
        self.toggleEye = ToggleEye(parent=self)
        self.toggleEye.setActive(False)
        self.toggleEye.setFixedWidth(35)
        self.toggleEye.setToolTip("Visibility")
        self.channelSelector = QSpinBox(parent=self)
        self.channelSelector.setFrame(False)
        self.channelSelector.setFont(self._font)
        self.channelSelector.setMaximumWidth(35)
        self.channelSelector.setAlignment(Qt.AlignRight)
        self.channelSelector.setToolTip("Channel")
        self.channelSelector.setVisible(False)

        self._layout = QGridLayout(self)
        self._layout.addWidget(self.toggleEye, 0, 0)
        self._layout.addWidget(self.nameLabel, 0, 1)
        self._layout.addWidget(self.opacityLabel, 0, 2)
        self._layout.addWidget(self.channelSelector, 1, 0)
        self._layout.addWidget(self.bar, 1, 1, 1, 2)

        self._layout.setColumnMinimumWidth(0, 35)
        self._layout.setSpacing(0)
        self._layout.setContentsMargins(5, 2, 5, 2)

        self.setLayout(self._layout)

        self.bar.fractionChanged.connect(self._onFractionChanged)
        self.toggleEye.activeChanged.connect(self._onEyeToggle)
        self.channelSelector.valueChanged.connect(self._onChannelChanged)

    def mousePressEvent(self, ev):
        super(LayerItemWidget, self).mousePressEvent(ev)

    def _onFractionChanged(self, fraction):
        if self._layer and (fraction != self._layer.opacity):
            self._layer.opacity = fraction

    def _onEyeToggle(self, active):
        if self._layer and (active != self._layer.visible):

            if self._layer._allowToggleVisible:
                self._layer.visible = active
            else:
                self.toggleEye.setActive(True)

    def _onChannelChanged(self, channel):
        if self._layer and (channel != self._layer.channel):
            self._layer.channel = channel

    def _updateState(self):
        if self._layer:
            self.toggleEye.setActive(self._layer.visible)
            self.bar.setFraction(self._layer.opacity)
            self.opacityLabel.setText(u"\u03B1=%0.1f%%" %
                                      (100.0 * (self.bar.fraction())))
            self.nameLabel.setText(self._layer.name)

            if self._layer.numberOfChannels > 1:
                self.channelSelector.setVisible(True)
                self.channelSelector.setMaximum(self._layer.numberOfChannels -
                                                1)
                self.channelSelector.setValue(self._layer.channel)
            else:
                self.channelSelector.setVisible(False)
                self.channelSelector.setMaximum(self._layer.numberOfChannels -
                                                1)
                self.channelSelector.setValue(self._layer.channel)
            self.update()
예제 #52
0
    def __init__(self):
        QWizardPage.__init__(self)
        self.setTitle(self.tr("New Project Data"))
        self.setSubTitle(self.tr(
            "Complete the following fields to create the Project Structure"))

        gbox = QGridLayout(self)
        #Names of the fields to complete
        self.lblName = QLabel(self.tr("New Project Name (*):"))
        self.lblPlace = QLabel(self.tr("Create in (*):"))
        self.lblDescription = QLabel(self.tr("Project Description:"))
        self.lblLicense = QLabel(self.tr("Project License:"))
        self.lblVenvFolder = QLabel(self.tr("Virtualenv Folder:"))
        gbox.addWidget(self.lblName, 0, 0, Qt.AlignRight)
        gbox.addWidget(self.lblPlace, 1, 0, Qt.AlignRight)
        gbox.addWidget(self.lblDescription, 2, 0, Qt.AlignTop)
        gbox.addWidget(self.lblLicense, 3, 0, Qt.AlignRight)
        gbox.addWidget(self.lblVenvFolder, 4, 0, Qt.AlignRight)

        #Fields on de right of the grid
        #Name
        self.txtName = QLineEdit()
        #Location
        hPlace = QHBoxLayout()
        self.txtPlace = QLineEdit()
        self.txtPlace.setReadOnly(True)
        self.btnExamine = QPushButton(self.tr("Browse..."))
        hPlace.addWidget(self.txtPlace)
        hPlace.addWidget(self.btnExamine)
        #Virtualenv
        vPlace = QHBoxLayout()
        self.vtxtPlace = QLineEdit()
        self._dir_completer = QCompleter()
        self._dir_completer.setModel(QDirModel(self._dir_completer))
        self.vtxtPlace.setCompleter(self._dir_completer)
        self.vbtnExamine = QPushButton(self.tr("Browse..."))
        vPlace.addWidget(self.vtxtPlace)
        vPlace.addWidget(self.vbtnExamine)
        #Project Description
        self.txtDescription = QPlainTextEdit()
        #Project License
        self.cboLicense = QComboBox()
        self.cboLicense.setFixedWidth(250)
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('Mozilla Public License 2.0')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        #Add to Grid
        gbox.addWidget(self.txtName, 0, 1)
        gbox.addLayout(hPlace, 1, 1)
        gbox.addWidget(self.txtDescription, 2, 1)
        gbox.addWidget(self.cboLicense, 3, 1)
        gbox.addLayout(vPlace, 4, 1)
        #Signal
        self.connect(self.btnExamine, SIGNAL('clicked()'), self.load_folder)
        self.connect(self.vbtnExamine, SIGNAL('clicked()'),
            self.load_folder_venv)
        self.connect(self.txtName, SIGNAL('textChanged(const QString&)'),
            lambda: self.emit(SIGNAL("completeChanged()")))
예제 #53
0
 def __init__(self, parent=None):
     super(QWizardPage, self).__init__(parent)
     self.setTitle("Export Options")
     self.gridLayout = QGridLayout(self)
     self.plugin = None
예제 #54
0
class ImusWidget(QWidget):
    def __init__(self, parent=None):
        super(ImusWidget, self).__init__(parent)

        self.create_ui()
        self.compose_ui()

        self.init_composition()
        self.init_contents()
        self.init_actions()

        self.on_start()

    def create_ui(self):
        self.layout = QGridLayout()

        self.directory = QLineEdit()
        self.search = QLineEdit()
        self.info = QLabel('Nothing to info about')
        self.bench = QLabel('0.0')

        self.results = QTableWidget()

        self.scan = QPushButton('&Scan')
        self.leave = QPushButton('&Quit')

    def compose_ui(self):
        self.layout.addWidget(self.directory, 0, 0, 1, 2)
        self.layout.addWidget(self.search, 1, 0, 1, 2)
        self.layout.addWidget(self.info, 2, 0, 1, 2)
        self.layout.addWidget(self.scan, 3, 0)
        self.layout.addWidget(self.leave, 3, 1)
        self.layout.addWidget(self.bench, 4, 0, 1, 2)

        self.setLayout(self.layout)

    def init_composition(self):
        #self.setWindowTitle(NAME + ' ' + __version__)
        desktop = QApplication.desktop()
        WIDTH = 800
        HEIGHT = 600
        self.setGeometry((desktop.width() - WIDTH) / 2,
                         (desktop.height() - HEIGHT) / 2, WIDTH, HEIGHT)
        self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint)

    def init_contents(self):
        self.directory.setPlaceholderText('Folder to scan')
        self.search.setPlaceholderText('Key to search')
        self.info.setMaximumWidth(640)
        self.info.setMaximumHeight(480)
        self.info.setAlignment(Qt.AlignCenter)

    def init_actions(self):
        self.scan.clicked.connect(self.update_lib)
        self.leave.clicked.connect(self.close)
        self.search.textChanged.connect(self.lookup_variants)

    def on_start(self):
        """
        Post-launch initialization.
        """
        self.r = Redis()
        self.crawler = Crawler(self.r)
        self.mpost = QPoint()
        self.lookup_task = None

    ##### actions #####

    def update_lib(self):
        if not self.directory.text().isEmpty():
            self.crawler.crawl(unicode(self.directory.text()))
        self.info.setText('Redis keys: %d' % len(self.r.lookup('*')))

    def lookup_variants(self):
        ##TODO: should not lookup queries under 2 symbols (in case those aren't kanji/hanzi)
        # Temporarily! May not work properly in many-many cases
        if not self.search.text().isEmpty():
            #if len(self.search.text()) > 1:
            # If lookut thread already initialized
            if self.lookup_task is not None:
                # If not finished yet - stop
                if not self.lookup_task.isFinished():
                    #print 'not finished!'
                    self.lookup_task.quit()
                # Update search query and restart
                self.lookup_task.update(self.search.text())
                self.lookup_task.start()
            # If not - let's create it and bind signals
            else:
                self.lookup_task = Lookup(self.r, self.search.text())
                self.lookup_task.done.connect(self.lookup_results)
                self.lookup_task.benchmark.connect(self.lookup_time)
                self.lookup_task.start()

        ##TODO: should not lookup queries under 2 symbols (in case those aren't kanji/hanzi)
        #if not self.search.text().isEmpty():
        ##TODO: implement option to search case-independent (e.g., convert to small case)
        #found = self.r.lookup(self.search.text())
        #if found:
        #self.info.setText(unicode('<hr/>'.join(found), 'utf-8'))
        #else:
        #self.info.setText('Nothing matches')
        ##self.adjustSize()
        #self.adjustSize()

    def lookup_results(self, found):
        if found:
            print Track.structure(self.r.retrieve(found))
            text = ''
            for track in self.r.retrieve(found):
                text += track.info()
                text += '<hr/>'

            try:
                self.info.setText(unicode(text, 'utf-8'))
            except TypeError:
                self.info.setText(text)
            # TEST: getting from Redis
            #self.info.setText(unicode('<hr/>'.join(found), 'utf-8'))
        else:
            self.info.setText('Nothing matches')
        self.adjustSize()

    def lookup_time(self, measured):
        #print measured
        self.bench.setText(str(measured))

    ##### events #####

    def onResizeEvent(self, event):
        pass

    def mousePressEvent(self, event):
        self.mpos = event.pos()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            diff = QPoint(event.pos() - self.mpos)
            newpos = QPoint(self.pos() + diff)

            self.move(newpos)

    def close(self, event):
        # TODO: implement 'minimize to tray' and all that stuff
        sys.exit()
예제 #55
0
    def initUI(self):
        self.setGeometry(200, 200, 260, 150)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setWindowTitle(u'添加基站')
        # 用grid布局
        grid1 = QGridLayout()
        grid1.setSpacing(10)
        grid2 = QGridLayout()
        grid2.setSpacing(10)
        grid3 = QGridLayout()
        grid3.setSpacing(10)
        grid4 = QGridLayout()
        grid4.setSpacing(10)

        lonlat_hobx = QHBoxLayout()
        lonlat_hobx.setSpacing(10)
        site_label = QLabel(u"<b>基站信息:  <\b>")
        grid1.addWidget(site_label, 1, 0)
        SiteId_label = QLabel(u"基站ID:")
        grid1.addWidget(SiteId_label, 2, 0)
        self.site_id = QLineEdit()
        site_id_validator = QIntValidator(0, 999999999,
                                          self)  # SiteId只能为最多9位的纯数字
        self.site_id.setValidator(site_id_validator)
        self.site_id.setPlaceholderText(u'必填(只能为最多9位的纯数字)')
        grid1.addWidget(self.site_id, 2, 1)
        SiteNmae_label = QLabel(u"基站名字:")
        grid1.addWidget(SiteNmae_label, 3, 0)
        self.site_name = QLineEdit()
        self.site_name.setPlaceholderText(u'必填')
        grid1.addWidget(self.site_name, 3, 1)
        RNCBSC_label = QLabel(u"RNC-BSC:")
        grid1.addWidget(RNCBSC_label, 4, 0)
        self.rnc_bsc = QLineEdit()
        self.rnc_bsc.setPlaceholderText(u'若不填则为随机数')
        grid1.addWidget(self.rnc_bsc, 4, 1)

        lon_label = QLabel(u"经度:")
        lonlat_hobx.addWidget(lon_label)
        self.lon = QLineEdit()
        lonlat_hobx.addWidget(self.lon)
        lat_label = QLabel(u"纬度:")
        lonlat_hobx.addWidget(lat_label)
        self.lat = QLineEdit()
        lonlat_hobx.addWidget(self.lat)

        operator_label = QLabel(u'运营商:')
        grid2.addWidget(operator_label, 1, 0)
        self.operator = QComboBox(self)  # 运营商选择下拉框
        self.operator.addItems([u"移动", u"联通", u"电信", u"铁塔"])
        grid2.addWidget(self.operator, 1, 1)
        region_label = QLabel(u'区域类型:')
        grid2.addWidget(region_label, 1, 2)
        self.region = QComboBox(self)  # 区域类型选择下拉框
        self.region.addItems([u"普通市区", u"密集市区", u"郊区乡镇", u"农村"])
        grid2.addWidget(self.region, 1, 3)
        system_label = QLabel(u"网络制式:")
        grid2.addWidget(system_label, 2, 0)
        self.system = QComboBox(self)  # 网络制式选择下拉框
        self.system.addItems([
            u"900", u"1800", u"CDMA", u"WCDMA", u"TD-LTE", u"FDD-LTE",
            u"TDSCDMA"
        ])
        grid2.addWidget(self.system, 2, 1)
        frequency_label = QLabel(u"频段:")
        grid2.addWidget(frequency_label, 2, 2)
        self.frequency = QComboBox(self)  # 频段选择下拉框
        self.frequency.addItems([
            u"700M", u"800M", u"900M", u"1800M", u"1900M", u"2100M", u"2300M",
            u"2600M"
        ])
        grid2.addWidget(self.frequency, 2, 3)

        # cell_label = QtGui.QLabel(u"<b>小区信息:  <\b>(若不需要添加小区请自行把下列的角度信息删除)")
        self.add_cell_checkbox = QCheckBox(u"添加小区")
        self.add_cell_checkbox.setChecked(False)
        grid3.addWidget(self.add_cell_checkbox, 1, 0)
        QObject.connect(self.add_cell_checkbox, SIGNAL("clicked()"),
                        self.add_cell_checkChange)

        azimuth_1_label = QLabel(u'Azimuth 1:')
        grid4.addWidget(azimuth_1_label, 1, 0)
        azimuth_validator = QIntValidator(0, 360, self)
        self.azimuth_1 = QLineEdit()
        self.azimuth_1.setEnabled(False)
        self.azimuth_1.setValidator(azimuth_validator)
        grid4.addWidget(self.azimuth_1, 1, 1)
        titl_1_label = QLabel(u'TILT')
        grid4.addWidget(titl_1_label, 2, 0)
        self.tilt_1 = QLineEdit()
        self.tilt_1.setEnabled(False)
        grid4.addWidget(self.tilt_1, 2, 1)
        etilt_1_label = QLabel(u'ETILT')
        grid4.addWidget(etilt_1_label, 2, 2)
        self.etilt_1 = QLineEdit()
        self.etilt_1.setEnabled(False)
        grid4.addWidget(self.etilt_1, 2, 3)
        mtilt_1_label = QLabel(u"MTILT")
        grid4.addWidget(mtilt_1_label, 2, 4)
        self.mtilt_1 = QLineEdit()
        self.mtilt_1.setEnabled(False)
        grid4.addWidget(self.mtilt_1, 2, 5)

        azimuth_2_label = QLabel(u'Azimuth 2:')
        grid4.addWidget(azimuth_2_label, 3, 0)
        self.azimuth_2 = QLineEdit()
        self.azimuth_2.setEnabled(False)
        self.azimuth_2.setValidator(azimuth_validator)
        grid4.addWidget(self.azimuth_2, 3, 1)
        titl_2_label = QLabel(u'TILT')
        grid4.addWidget(titl_2_label, 4, 0)
        self.tilt_2 = QLineEdit()
        self.tilt_2.setEnabled(False)
        grid4.addWidget(self.tilt_2, 4, 1)
        etitl_2_label = QLabel(u'ETILT')
        grid4.addWidget(etitl_2_label, 4, 2)
        self.etilt_2 = QLineEdit()
        self.etilt_2.setEnabled(False)
        grid4.addWidget(self.etilt_2, 4, 3)
        mtilt_2_label = QLabel(u'MTILT')
        grid4.addWidget(mtilt_2_label, 4, 4)
        self.mtilt_2 = QLineEdit()
        self.mtilt_2.setEnabled(False)
        grid4.addWidget(self.mtilt_2, 4, 5)

        azimuth_3_label = QLabel(u'Azimuth 3:')
        grid4.addWidget(azimuth_3_label, 5, 0)
        self.azimuth_3 = QLineEdit()
        self.azimuth_3.setEnabled(False)
        self.azimuth_3.setValidator(azimuth_validator)
        grid4.addWidget(self.azimuth_3, 5, 1)
        titl_3_label = QLabel(u'TILT')
        grid4.addWidget(titl_3_label, 6, 0)
        self.tilt_3 = QLineEdit()
        self.tilt_3.setEnabled(False)
        grid4.addWidget(self.tilt_3, 6, 1)
        etitl_3_label = QLabel(u'ETILT')
        grid4.addWidget(etitl_3_label, 6, 2)
        self.etilt_3 = QLineEdit()
        self.etilt_3.setEnabled(False)
        grid4.addWidget(self.etilt_3, 6, 3)
        mtilt_3_label = QLabel(u'MTILT')
        grid4.addWidget(mtilt_3_label, 6, 4)
        self.mtilt_3 = QLineEdit()
        self.mtilt_3.setEnabled(False)
        grid4.addWidget(self.mtilt_3, 6, 5)

        azimuth_4_label = QLabel(u'Azimuth 4:')
        grid4.addWidget(azimuth_4_label, 7, 0)
        self.azimuth_4 = QLineEdit()
        self.azimuth_4.setEnabled(False)
        self.azimuth_4.setValidator(azimuth_validator)
        grid4.addWidget(self.azimuth_4, 7, 1)
        titl_4_label = QLabel(u'TILT')
        grid4.addWidget(titl_4_label, 8, 0)
        self.tilt_4 = QLineEdit()
        self.tilt_4.setEnabled(False)
        grid4.addWidget(self.tilt_4, 8, 1)
        etitl_4_label = QLabel(u'ETILT')
        grid4.addWidget(etitl_4_label, 8, 2)
        self.etilt_4 = QLineEdit()
        self.etilt_4.setEnabled(False)
        grid4.addWidget(self.etilt_4, 8, 3)
        mtilt_4_label = QLabel(u'MTILT')
        grid4.addWidget(mtilt_4_label, 8, 4)
        self.mtilt_4 = QLineEdit()
        self.mtilt_4.setEnabled(False)
        grid4.addWidget(self.mtilt_4, 8, 5)

        btn_hbox = QHBoxLayout()
        ok = QPushButton(u"添加")
        self.connect(ok, SIGNAL('clicked()'), self.add)
        cancel = QPushButton(u"取消")
        self.connect(cancel, SIGNAL('clicked()'), self.accept)
        btn_hbox.addStretch(1)
        btn_hbox.addWidget(ok)
        btn_hbox.addWidget(cancel)
        btn_hbox.addStretch(1)

        vbox = QVBoxLayout()
        vbox.addLayout(grid1)
        vbox.addLayout(lonlat_hobx)
        vbox.addLayout(grid2)
        vbox.addLayout(grid3)
        vbox.addLayout(grid4)
        vbox.addStretch(1)
        vbox.addLayout(btn_hbox)
        self.setLayout(vbox)
        self.resize(500, 510)
예제 #56
0
class ExportDataWidget(QWizardPage):
    """
	Wraps up whatever UI the plugin provides in a container QWidget (throwing away the old widget as required).
	There is no nextId() provided for widgets wrapped in this container - its the end of the road here.
	"""
    def __init__(self, parent=None):
        super(QWizardPage, self).__init__(parent)
        self.setTitle("Export Options")
        self.gridLayout = QGridLayout(self)
        self.plugin = None

    def nextId(self):
        # if no more pages, then return -1
        return -1

    def isComplete(self):
        if self.plugin is None:
            return False
        return self.plugin.ui.isComplete()

    def __createExportUI(self, document, parent):
        if self.plugin is None:
            raise Exception(
                "self.plugin isn't set when __createExportUI was called")
        self.plugin.ui = self.plugin.createExportUI(parent)
        self.plugin.ui.initializePageWithDocument(document)
        return self.plugin.ui

    def changed(self):
        self.completeChanged.emit()

    def initializePage(self):
        """
		Find and load the persistent document, create the export UI and insert it into the 'container'.  This
		method assumes that the wizard has a documentName set.
		"""

        self.container = QWidget(self)

        if self.plugin is not None:
            self.plugin.ui.setParent(None)
            self.gridLayout.removeWidget(self.plugin.ui)
            self.plugin.ui = None
            self.plugin = None

        name_of_file = self.wizard().documentName()
        document = PersistentScanningState(
            DocumentStorage.documentFullPath(name_of_file))

        self.plugin = self.__createPluginNamed(
            self.field("exportType").toString())
        ui = self.__createExportUI(document, self.container)
        self.gridLayout.addWidget(ui)

        self.changed()

    def __createPluginNamed(self, plugin_name):
        if ExporterPlugin.isValidPluginModule(plugin_name):
            plugin = ExporterPlugin(plugin_name)
            return plugin
        return None
예제 #57
0
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
예제 #58
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
예제 #59
0
    def __init__(self, page):
        super(TypographicalQuotes, self).__init__(page)

        layout = QGridLayout(spacing=1)
        self.setLayout(layout)
        l = self.languageLabel = QLabel()
        c = self.languageCombo = QComboBox(currentIndexChanged=self.languageChanged)
        l.setBuddy(c)

        self.primaryLabel = QLabel()
        self.secondaryLabel = QLabel()
        self.primaryLeft = QLineEdit(textEdited=self.changed)
        self.primaryRight = QLineEdit(textEdited=self.changed)
        self.secondaryLeft = QLineEdit(textEdited=self.changed)
        self.secondaryRight = QLineEdit(textEdited=self.changed)

        self._langs = ["current", "custom"]
        self._langs.extend(lang for lang in lasptyqu.available() if lang != "C")
        c.addItems(['' for i in self._langs])

        layout.addWidget(self.languageLabel, 0, 0)
        layout.addWidget(self.primaryLabel, 1, 0)
        layout.addWidget(self.secondaryLabel, 2, 0)
        layout.addWidget(self.languageCombo, 0, 1, 1, 2)
        layout.addWidget(self.primaryLeft, 1, 1)
        layout.addWidget(self.primaryRight, 1, 2)
        layout.addWidget(self.secondaryLeft, 2, 1)
        layout.addWidget(self.secondaryRight, 2, 2)

        app.translateUI(self)
예제 #60
0
class MoralityWidget(QWidget):
    """
	@brief Dieses Widget stellt die Moral-Tabelle dar.

	Diese Tabelle zeigt die aktuelle Moralstufe an und bietet Platz für das Eintragen von Geistesstörungen.
	"""

    valueChanged = Signal(int)

    def __init__(self, template, character, parent=None):
        super(MoralityWidget, self).__init__(parent)

        self.__character = character
        self.__storage = template

        self.__value = 0

        self.__layout = QVBoxLayout()
        self.setLayout(self.__layout)

        self.__layoutHeading = QHBoxLayout()
        self.__layout.addLayout(self.__layoutHeading)

        self.__labelHeading = QLabel("Test")
        self.__labelHeading.setAlignment(Qt.AlignHCenter)

        self.__layoutHeading.addStretch()
        self.__layoutHeading.addWidget(self.__labelHeading)
        self.__layoutHeading.addStretch()

        self.__layoutTab = QGridLayout()
        # Nur die Spalte mit den Geistesstörungen soll sich strecken dürfen.
        self.__layoutTab.setColumnStretch(1, 1)
        self.__layout.addLayout(self.__layoutTab)

        self.__dotList = {}
        self.__derangementBoxList = {}

        for i in range(Config.TRAIT_MORALITY_VALUE_MAX):
            label = QLabel("{}".format(Config.TRAIT_MORALITY_VALUE_MAX - i))
            label.setAlignment(Qt.AlignRight)
            self.__layoutTab.addWidget(label, i, 0)

            dot = Dot()
            # Den Punkt zu einer Liste hinzufügen, um später zu sehen, welcher Punkt den Wert änderte.
            self.__dotList[Config.TRAIT_MORALITY_VALUE_MAX - i] = dot
            self.__layoutTab.addWidget(dot, i, 2)

            if i >= Config.TRAIT_MORALITY_VALUE_MAX - Config.TRAIT_MORALITY_DERANGEMENT_VALUE_MAX:
                box = DerangementComboBox()
                self.__derangementBoxList[Config.TRAIT_MORALITY_VALUE_MAX -
                                          i] = box
                self.__layoutTab.addWidget(box, i, 1)

                box.currentIndexChanged[str].connect(self.uniqifyDerangements)
                box.derangementChanged.connect(self.checkSevereDerangement)

            dot.clicked.connect(self.__calcValue)

        self.__character.speciesChanged.connect(self.setMoralityName)
        self.__character.moralityChanged.connect(self.setValue)
        self.valueChanged.connect(self.__character.setMorality)
        self.__character.speciesChanged.connect(self.fillDerangementBoxes)
        self.valueChanged.connect(self.enableDerangementBox)
        self.__character.derangementChanged.connect(
            self.updateDerangementBoxes)

    def __getValue(self):
        return self.__value

    def setValue(self, value):
        if (self.__value != value):
            self.__value = value
            self.__drawValue(value)
            #Debug.debug(value)
            self.valueChanged.emit(value)

    value = property(__getValue, setValue)

    def __calcValue(self, value):
        """
		Berechnet aus dem angeklickten Punkt, welchen Wert die Moral jetzt hat.
		"""

        #Debug.debug(self.__dotList)
        # Ist der Wert True, suche ich nach dem höchsten wahren Punkt und mache alle kleineren auch wahr.
        # Ist der Wert False, suche ich nach dem niedrigesten False punkt, und mache die höheren alle False.
        if value:
            dotsTrue = []
            for i in range(1, self.__layoutTab.rowCount() + 1):
                if self.__dotList[i].value:
                    dotsTrue.append(i)
            maxValue = max(dotsTrue)
            #Debug.debug(dotsTrue)
            for i in range(1, maxValue):
                self.__dotList[i].value = True
                #Debug.debug("{}: {} (Maximalwert {})".format(i, self.__dotList[i].value, maxValue))
            self.value = maxValue
        else:
            dotsFalse = []
            for i in range(1, self.__layoutTab.rowCount() + 1):
                if not self.__dotList[i].value:
                    dotsFalse.append(i)
            minValue = min(dotsFalse)
            if minValue == self.value and minValue != 1:
                self.__dotList[minValue].value = True
            else:
                for i in range(minValue + 1, self.__layoutTab.rowCount() + 1):
                    self.__dotList[i].value = False
                    #Debug.debug("{}: {} (Maximalwert {})".format(i, self.__dotList[i].value, minValue))
                # Intuitiverweise will man die Moral auf den Wert setzen, auf den man klickt. Aber das gilt nicht, wenn man auf den untersten Punkt klickt.
                if minValue == 1:
                    self.__dotList[minValue].value = False
                    self.value = 0
                else:
                    self.value = minValue

    def __drawValue(self, value):
        """
		Ändert sich der Wert des Widgets, wird hierüber die passende Anzahl an Punkten schwarz ausgemalt.
		"""

        if value > 0:
            for i in range(value, len(self.__dotList) + 1):
                self.__dotList[i].value = False
            for i in range(1, value + 1):
                self.__dotList[i].value = True
        else:
            for i in range(1, len(self.__dotList) + 1):
                self.__dotList[i].value = False

    def setMoralityName(self, species):
        """
		Setzt die Überschrift dieses Widgets auf einen neuen Namen. Der name hängt von der Spezies ab.
		"""

        self.__labelHeading.setText("<b>{}</b>".format(
            self.__storage.moralityName(species)))

    def fillDerangementBoxes(self, species):
        """
		Sorgt dafür, daß die Comboboxen alle für diese Spezies verfügbaren Geistesstörungen enthalten.
		"""

        ## Milde Geistesstörungen.
        mild = self.__storage.derangementList(species)
        ## Ernste Geistesstörungen.
        severe = []
        for item in mild:
            severe.extend(self.__storage.derangementList(species, item))
        severe.sort()
        ## An den Anfang kommt ein leerer String
        mild.insert(0, "")
        #Debug.debug(mild)
        #Debug.debug(severe)
        lostDerangements = []
        for i in range(1,
                       Config.TRAIT_MORALITY_DERANGEMENT_VALUE_MAX + 1)[::-1]:
            ## Speichern der alten Auswahl.
            oldSelection = self.__derangementBoxList[i].currentText()
            ## Erst löschen
            self.__derangementBoxList[i].clear()
            ## Dann wieder füllen
            self.__derangementBoxList[i].addItems(mild)
            self.__derangementBoxList[i].addItems(severe, severe=True)
            ## Und wenn möglich, alte Auswahl wiederherstellen.
            oldIndex = self.__derangementBoxList[i].findText(oldSelection)
            if oldIndex < 0:
                lostDerangements.append(oldSelection)
            else:
                self.__derangementBoxList[i].setCurrentIndex(oldIndex)

        #Debug.debug(self.__character.isLoading)
        if lostDerangements and not self.__character.isLoading:
            derangements = ""
            infoText = ""
            if len(lostDerangements) > 1:
                derangements = ", ".join(lostDerangements[:-1])
                derangements = "{} and {}".format(derangements,
                                                  lostDerangements[-1])
                infoText = self.tr(
                    "The derangements \"{derangements}\" are not available for a {species}. The character lost these deragnements."
                    .format(derangements=derangements, species=species))
            else:
                derangements = "".join(lostDerangements)
                infoText = self.tr(
                    "The derangement \"{derangements}\" is not available for a {species}. The character lost this deragnement."
                    .format(derangements=derangements, species=species))
            QMessageBox.information(self, self.tr("Lost Derangement"),
                                    infoText)

    def enableDerangementBox(self, value):
        """
		Sorgt dafür, daß die Combobox für die Geistesstörung neben einem leeren Moralpunkt aktiviert und mit den verfügbaren Geistesstörungen gefüllt wird.

		Alle Boxen zeigen alle Geistesstörungen an, aber wenn eine Gewählt wird, die schon anderorts gewählt wurde, wird sie dort abgewählt.
		"""

        #Debug.debug(value)

        for i in range(value + 1,
                       Config.TRAIT_MORALITY_DERANGEMENT_VALUE_MAX + 1)[::-1]:
            self.__derangementBoxList[i].setEnabled(True)
        for i in range(1, value + 1):
            self.__derangementBoxList[i].setCurrentIndex(0)
            self.__derangementBoxList[i].setEnabled(False)

    def uniqifyDerangements(self, text):
        """
		Eine Geistesstörung darf immer nur in einer ComboBox auftauchen.

		Es werd die oberen doppelt vorkommende Geistesstörung gelöscht.
		"""

        #Debug.debug(text)
        firstOccuranceHappened = False
        for i in range(1, Config.TRAIT_MORALITY_DERANGEMENT_VALUE_MAX + 1):
            if self.__derangementBoxList[i].currentIndex != 0:
                if self.__derangementBoxList[i].currentText(
                ) == text and firstOccuranceHappened:
                    self.__derangementBoxList[i].setCurrentIndex(0)
                elif self.__derangementBoxList[i].currentText() == text:
                    firstOccuranceHappened = True

    def checkSevereDerangement(self, derangement, isSevere, sender):
        """
		Wird eine schwere Geistesstörung gewählt und ihre Milde version ist nicht gewählt, muß gewarnt werden.
		"""

        if isSevere:
            mildParent = ""
            for item in self.__storage.derangementList(
                    self.__character.species):
                if derangement in self.__storage.derangementList(
                        self.__character.species, item):
                    mildParent = item
                    break
            mildExists = False
            for i in range(1, Config.TRAIT_MORALITY_DERANGEMENT_VALUE_MAX + 1):
                if self.__derangementBoxList[i].currentText() == mildParent:
                    mildExists = True
                    break
            if not mildExists:
                #Debug.debug("Milde Verfsion exisitert nicht!")
                QMessageBox.warning(
                    self, self.tr("Warning"),
                    self.
                    tr("{severe} can only be taken, if its mild version {mild} was selected at a higher morality level. Instead of {severe}, {mild} will be selected for this morality level."
                       .format(mild=mildParent, severe=derangement)))
                #Debug.debug(sender)
                sender.setCurrentIndex(sender.findText(mildParent))
                derangement = mildParent

        ## Nach der Kontrolle, kann die Geistesstörung gespeichert werden.
        for item in self.__derangementBoxList.items():
            if sender == item[1]:
                #Debug.debug(item[0], derangement)
                self.saveDerangements(moralityValue=item[0],
                                      derangement=derangement)
                break

    def saveDerangements(self, moralityValue, derangement):
        """
		Speichert die gewählte Geistesstörung im Charakter.
		"""

        self.__character.setDerangement(moralityValue=moralityValue,
                                        derangement=derangement)

    def updateDerangementBoxes(self, moralityValue, derangement):
        """
		Wählt in den derangementBoxen die jeweils übergebenen Geistesstörungen aus.
		"""

        #Debug.debug(derangement, moralityValue)

        self.__derangementBoxList[moralityValue].setCurrentIndex(
            self.__derangementBoxList[moralityValue].findText(derangement))