Пример #1
0
    def initializePage(self):
        super(PanelPage, self).initializePage()

        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        row0 = QHBoxLayout()
        lable0 = QLabel('  依赖库:')
        lable0.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items0 = QStringList()
        for moudel in app.g_configurations.libs:
            items0.append(moudel['name'])
        self.lw_files.addItems(items0)
        row0.addWidget(lable0)
        row0.addWidget(self.lw_files)

        row1 = QHBoxLayout()
        lable1 = QLabel('工程文件:')
        lable1.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items1 = QStringList()
        for file in app.g_configurations.config['files']:
            items1.append(file['target'])
        self.lw_files.addItems(items1)
        row1.addWidget(lable1)
        row1.addWidget(self.lw_files)

        rootLayout.addLayout(row0)
        rootLayout.addLayout(row1)
        self.setLayout(rootLayout)
Пример #2
0
 def __init__(self, colour_scheme, parent = None):
     super(DBColourPicker, self).__init__(parent)
     self.setupUi(self)
     self._originalScheme = copy.deepcopy(colour_scheme)
     self._currentScheme = copy.deepcopy(colour_scheme)
     reset = self.buttonBox.button(self.buttonBox.Reset)
     reset.clicked.connect(self.reset)
     restore = self.buttonBox.button(self.buttonBox.RestoreDefaults)
     restore.clicked.connect(self.restoreDefaults)
     self._colourSelectors = []
     self._lineSelectors = []
     for row, colour in enumerate(self._currentScheme.iterTextColours()):
         colourAttr = colour.colourAttrs
         label = QLabel(self.frame)
         label.setText(colourAttr.longName)
         label.setAlignment(QtCore.Qt.AlignRight)
         self.textGrid.addWidget(label, row + 1, 0, 1, 1)
         textButton = self._makeLineButton(colourAttr)
         self.textGrid.addWidget(textButton, row + 1, 1, 1, 1)
     for row, colour in enumerate(self._currentScheme.iterAreaColours()):
         colourAttr = colour.colourAttrs
         label = QLabel(self.frame_2)
         label.setText(colourAttr.longName)
         label.setAlignment(QtCore.Qt.AlignRight)
         self.areaGrid.addWidget(label, row + 1, 0, 1, 1)
         if colourAttr.background:
             backgroundButton = self._makeBackgroundButton(colourAttr)
             self.areaGrid.addWidget(backgroundButton, row + 1, 1, 1, 1)
         if colourAttr.border:
             combo = self._makeLineCombo(colourAttr)
             self.areaGrid.addWidget(combo, row + 1, 2, 1, 1)
             lineButton = self._makeLineButton(colourAttr)
             self.areaGrid.addWidget(lineButton, row + 1, 3, 1, 1)
     self._setColourValues()
Пример #3
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.parent = parent
        sizer = QVBoxLayout()
        global LOGO
        LOGO = path2(LOGO)
        logo = QLabel(self)
        logo.setPixmap(QPixmap(LOGO))

        sizer.addWidget(logo, 0, Qt.AlignCenter)

        date = "/".join(str(n) for n in reversed(param.date_version))
        textes = [u"<b>%s version %s</b>" % (NOMPROG, param.version)]
        textes.append(u"<i>Version publiée le " + date + "</i>")
        textes.append("")
        textes.append(u"« Le couteau suisse du prof de maths »")
        textes.append("")
        textes.append(
            "<img src='%s'> <b>%s est un \
                    <a href='http://fr.wikipedia.org/wiki/Logiciel_libre'> \
                    logiciel libre</a></b>"
            % (path2("%/wxgeometrie/images/copyleft.png"), NOMPROG)
        )
        textes.append(u"Vous pouvez l'utiliser et le modifier selon les termes de la GNU Public License v2.")
        textes.append(u"<i>Copyleft 2005-%s Nicolas Pourcelot ([email protected])</i>" % ANNEE)
        textes.append("")
        label = QLabel("<br>".join(textes))
        label.setAlignment(Qt.AlignCenter)
        label.setOpenExternalLinks(True)

        sizer.addWidget(label, 0, Qt.AlignCenter)
        self.setLayout(sizer)
class LoadingWidget(QWidget):

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


        self.message = QLabel(self)
        self.message.setAlignment(Qt.AlignCenter)

        self._createLayout()

    def setMessage(self, msg):
        self.message.setText('<b>%s</b>' % msg)

    def _createLayout(self):

        l = QVBoxLayout()

        l.addStretch(1)
        l.addWidget(self.message)

        l.addSpacing(10)
        spinner = BusySpinnerWidget(self)

        l.addWidget(spinner)
        l.addStretch(1)

        self.setLayout(l)
Пример #5
0
class InputWidget(ControlMapper):
    def __init__(self, device=1, parent=None):
        ControlMapper.__init__(self, device, parent)

        self.midiLabel = QLabel('midi', self)
        self.midiLabel.setAlignment(Qt.AlignCenter)
        self.midiLED = pk.widgets.LED(self)
        self.midiLED.setFixedSize(20, 10)
        
        self.kbLabel = QLabel('kb', self)
        self.kbLabel.setAlignment(Qt.AlignCenter)
        self.kbLED = pk.widgets.LED(self)
        self.kbLED.setFixedSize(20, 10)

        Layout = QGridLayout(self)
        Layout.setRowStretch(0, 1)
        Layout.addWidget(self.kbLabel, 2, 0)
        Layout.addWidget(self.kbLED, 1, 0)
        Layout.addWidget(self.midiLabel, 2, 1)
        Layout.addWidget(self.midiLED, 1, 1)
        Layout.setRowStretch(3, 1)
        
    def midiEvent(self, msg):
        self.midiLED.blink()
        ControlMapper.midiEvent(self, msg)

    def keyPressEvent(self, e):
        self.kbLED.blink()
        ControlMapper.keyPressEvent(self, e)
Пример #6
0
    def __init__(self, show_title, value_range,  default_value, slider_type, adjust_function):
        # The parent widget
        widget = QWidget();
        # Create a slider using based on the type provided
        slider = create_slider(slider_type, value_range, default_value)
        # Create the labels that will hold the title and the current value
        title  = QLabel(str(show_title));
        value  = QLabel(str(default_value))

        # Center the text of the title label
        title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        title.setWordWrap(True)

        # Center the text of the value label
        value.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        # Create and set a new Vertical BoxLayout
        widget.setLayout(QBoxLayout(QBoxLayout.TopToBottom))

        # Inserts the widget into the layout
        widget.layout().addWidget(title , 1)
        widget.layout().addWidget(slider, 2)
        widget.layout().addWidget(value , 1)

        # Remove the vertical spacing
        widget.layout().setSpacing(0)

        # A function that will clip the value to the range
        def clip(v):
            v = max(v, value_range[0])
            v = min(v, value_range[1])
            return v

        # No adjust_function is given, uses only the clip
        if adjust_function is None:
            adjust_func = clip
        # If adjust_func is given, use it and the clip
        else:
            def adjust_func(v):
                v = adjust_function(v)
                v = clip(v)
                return v
        # This function will receive the sliderMoved signal from the slider.
        # It should pass it to the adjust_func and show the returned value to
        # the user through the `value` label, so the value that user sees is
        # always correct. It also changes the _value member to the value return'
        def slider_moved(v):
            self._value = int(adjust_func(v))
            value.setText(str(self._value))

        slider.sliderMoved.connect(slider_moved)

        self._widget  = widget
        self._slider  = slider
        self._title   = title
        self._range   = value_range
        self._default = int(default_value)
        self._value   = int(default_value)
        self._adjust  = adjust_func
        self._native_title = show_title
Пример #7
0
 def addMenuLine(self, parent, text, box, header = False):
     aLabel = QLabel(text, parent)
     if header:
         aLabel.setAlignment(Qt.AlignCenter)
         oldFont = aLabel.font()
         aLabel.setFont(QFont(oldFont.family(), 13, QFont.Bold))
     box.addWidget(aLabel, 0, Qt.AlignBottom)
Пример #8
0
    def _mostrar_dialogo(self):
        self.frame_snake.pause()
        self.dialogo = QDialog()
        self.dialogo.setWindowTitle(self.tr("Pyborita"))
        box = QVBoxLayout(self.dialogo)
        # Acerca de
        logo_pyborita = QLabel()
        logo_pyborita.setPixmap(QPixmap(":image/pyborita"))
        logo_pyborita.setAlignment(Qt.AlignCenter)
        box.addWidget(logo_pyborita)

        description = QLabel(self.tr("<b>Pyborita</b> es un clon de Snake "
                            "desarrollado por<br>Gabriel Acosta en Python"
                            " usando PyQt para la GUI.<br><br>Copyright (C) "
                            "<2015> Gabriel Acosta - Gabo<br>"
                            "License: GPLv3"))
        box.addWidget(description)
        # Botones
        hbox = QHBoxLayout()
        btn_nuevo_juego = QPushButton(self.tr("Nuevo Juego"))
        hbox.addWidget(btn_nuevo_juego)
        btn_salir = QPushButton(self.tr("Salir"))
        hbox.addWidget(btn_salir)
        box.addLayout(hbox)

        # Conexiones de botones
        btn_nuevo_juego.clicked.connect(self._nuevo_juego)
        btn_salir.clicked.connect(self._close)

        self.dialogo.exec_()
        self.frame_snake.reanude()
        self.frame_snake.setFocus()
class PluginWidget(QWidget):
    def __init__( self, parent, plugin ):
        super(PluginWidget, self).__init__(parent)
        
        self._icon = QLabel(self)
        self._icon.setPixmap(QPixmap(plugin.iconFile()))
        self._icon.setMinimumWidth(48)
        self._icon.setMinimumHeight(48)
        self._icon.setAlignment(Qt.AlignCenter)
        
        self._title = QLabel(plugin.title(), self)
        self._title.setAlignment(Qt.AlignCenter)
        
        font = self.font()
        font.setPointSize(7)
        
        self._title.setFont(font)
        
        vbox = QVBoxLayout()
        vbox.addStretch()
        vbox.addWidget(self._icon)
        vbox.addWidget(self._title)
        vbox.addStretch()
        
        self.setLayout(vbox)
        
        self._plugin = plugin
    
    def plugin( self ):
        """
        Returns the plugin instance linked to this widget.
        
        :return     <XWizardPlugin>
        """
        return self._plugin
Пример #10
0
    def __init__(self):
        QDialog.__init__(self, None, Qt.Dialog)
        self.setModal(True)
        self.setWindowTitle('About NINJA-IDE')
        self.setMaximumSize(QSize(0,0))
        v_box = QVBoxLayout(self)
        
        pixmap = QPixmap(resources.images['icon'])
        labIcon = QLabel('')
        labIcon.setPixmap(pixmap)
        hbox = QHBoxLayout()
        hbox.addWidget(labIcon)
        lblTitle = QLabel('<h1>NINJA-IDE</h1>\n<i>Ninja Is Not Just Another IDE<i>')
        lblTitle.setTextFormat(Qt.RichText)
        lblTitle.setAlignment(Qt.AlignLeft)
        hbox.addWidget(lblTitle)
        v_box.addLayout(hbox)
        v_box.addWidget(QLabel("""NINJA is an IDE specialy Designed for Python applications development.
In the Version 1.0, also called Kunai, will be included the next features:
    Autocompleting Code, Code Checking, Projects Management,
    Wizard Interfaces for creating new files and also new projects,
    an interactive Python console,
    an easter egg (essencial in any application),
    and much more!."""))
        v_box.addWidget(QLabel('Version: UNDER DEVELOPMENT'))
        v_box.addWidget(QLabel('Website: http://ninja-ide.googlecode.com'))
    def __init__(self, parent, available):
        QWidget.__init__(self)
        self._parent = parent
        self._available = available
        vbox = QVBoxLayout(self)
        self._table = QTableWidget(1, 3)
        self._table.removeRow(0)
        vbox.addWidget(self._table)
        set_data(available, self._table)
        btnInstall = QPushButton("Install")
        btnInstall.setMaximumWidth(100)
        vbox.addWidget(btnInstall)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Add an external Plugin. URL Zip File:"))
        self.link = QLineEdit()
        hbox.addWidget(self.link)
        btnAdd = QPushButton("Add")
        hbox.addWidget(btnAdd)
        vbox.addLayout(hbox)
        lblExternalPlugin = QLabel('(Write the URL of the Plugin and press "Add")')
        lblExternalPlugin.setAlignment(Qt.AlignRight)
        vbox.addWidget(lblExternalPlugin)

        self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins)
        self.connect(btnAdd, SIGNAL("clicked()"), self._install_external)
Пример #12
0
class MuteButtonLabel(QWidget):

    def __init__(self, parent=None): 
        QWidget.__init__(self, parent) 
        #self.setFixedSize(CustomSize)
        self.movie_screen = QLabel()
        self.movie_screen.setFixedSize(CustomSize)
        self.movie_screen.setAlignment(Qt.AlignLeft)
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.movie_screen)
        self.setLayout(main_layout)
        self.muted = False

        #self.unmute() # this is for testpurpose only

        
    def unmute(self):
        """start animation"""
        self.movie = QMovie(":/unmute.gif", QByteArray(), self)
        self.movie.setScaledSize(CustomSize*0.7)
        self.movie.setCacheMode(QMovie.CacheAll)
        self.movie.setSpeed(100)
        self.movie_screen.setMovie(self.movie)
        self.muted = False
        #print("Emitted 'sig_unmute'")
        self.emit(SIGNAL("sig_unmute"))
        self.movie.start()

    def show_unmute(self):
        self.movie = QMovie(":/unmute.gif", QByteArray(), self)
        self.movie.setScaledSize(CustomSize*0.7)
        self.movie.setCacheMode(QMovie.CacheAll)
        self.movie.setSpeed(100)
        self.movie_screen.setMovie(self.movie)
        self.muted = False
        self.movie.start()

    def mute(self):
        """stop the animation"""
        self.movie = QMovie(":/mute.gif", QByteArray(), self)
        self.movie.setScaledSize(CustomSize*0.7)
        self.movie.setCacheMode(QMovie.CacheAll)
        self.movie.setSpeed(100)
        self.movie_screen.setMovie(self.movie)
        self.muted = True
        #print("Emitted 'sig_mute'")
        self.emit(SIGNAL("sig_mute"))
        self.movie.start()

    def toggleMute(self):
        if self.muted:
            self.unmute()
        else:
            self.mute()

    def mousePressEvent(self, QMouseEvent):

        self.toggleMute()

        QMouseEvent.accept()
Пример #13
0
    def setup_welcome_widget(self):

        """Load the welcome widget at startup."""

        widget = QWidget()
        layout = QVBoxLayout()

        welcome = QLabel(parent=self)
        pix = QPixmap(KStandardDirs.locate("appdata","logo.png"))

        welcome.setPixmap(pix)
        welcome.setAlignment(Qt.AlignCenter)

        self.first_fetch_widget = connectwidget.ConnectWidget(
        self.preferences.boards_list, self)

        self.statusbar.addPermanentWidget(self.first_fetch_widget, 300)

        self.first_fetch_widget.connectionEstablished.connect(
            self.handle_connection)
        self.first_fetch_widget.rejected.connect(
            self.first_fetch_widget.hide)

        self.first_fetch_widget.hide()

        self.first_fetch_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)

        layout.addWidget(self.first_fetch_widget)
        layout.addWidget(welcome)
        widget.setLayout(layout)

        self.setCentralWidget(widget)
Пример #14
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setModal(True)
        self.setWindowTitle(self.tr("About NINJA-IDE"))
        self.setMaximumSize(QSize(0, 0))

        vbox = QVBoxLayout(self)

        #Create an icon for the Dialog
        pixmap = QPixmap(resources.IMAGES['icon'])
        lblIcon = QLabel()
        lblIcon.setPixmap(pixmap)

        hbox = QHBoxLayout()
        hbox.addWidget(lblIcon)

        lblTitle = QLabel(
                '<h1>NINJA-IDE</h1>\n<i>Ninja-IDE Is Not Just Another IDE<i>')
        lblTitle.setTextFormat(Qt.RichText)
        lblTitle.setAlignment(Qt.AlignLeft)
        hbox.addWidget(lblTitle)
        vbox.addLayout(hbox)
        #Add description
        vbox.addWidget(QLabel(
self.tr("""NINJA-IDE (from: "Ninja Is Not Just Another IDE"), is a
cross-platform integrated development environment specially design
to build Python Applications.
NINJA-IDE provides tools to simplify the Python-software development
and handles all kinds of situations thanks to its rich extensibility.""")))
        vbox.addWidget(QLabel(self.tr("Version: %1").arg(
                ninja_ide.__version__)))
        vbox.addWidget(QLabel(
            self.tr("Website: %1").arg(ninja_ide.__url__)))
        vbox.addWidget(QLabel(
            self.tr("Source Code: %1").arg(ninja_ide.__source__)))
Пример #15
0
class EditorTab(object):
    def __init__(self, mainwindow, filePath):
        self.mainwindow = mainwindow

        self.tabIcon = QIcon(":/Images/Images/cog.png")
        self.tabLabel = "Editor Dyn Tab"

        self.tab = QWidget(self.mainwindow)

        self.widgetLayout = QVBoxLayout(self.tab)
        self.widgetLayout.setAlignment(Qt.AlignTop)
        self.editorStatusLabel = QLabel(self.tab)
        self.editorStatusLabel.setAlignment(Qt.AlignCenter)
        self.editorStatusLabel.setObjectName("editorStatusLabel")
        self.editorStatusLabel.setText(QString("No files currently loaded..."))
        self.widgetLayout.addWidget(self.editorStatusLabel)
        self.editorStuff = EditorBase(self.mainwindow)
        self.widgetLayout.addWidget(self.editorStuff)
        try:
            f = open(filePath,'r')
        except:
            return
        for l in f.readlines():
            self.editorStuff.append(l)
        f.close()
        self.editorStatusLabel.setText(QString(filePath))

        self.mainwindow.tabWidget.insertTab(0,self.tab,self.tabIcon,self.tabLabel)
        self.mainwindow.tabWidget.setCurrentIndex(0)
 def initUI(self):
     # title
     title = QLabel(self)
     title.setText("User Instruction")
     title.setAlignment(Qt.AlignCenter)
     # user instruction
     groupBox = QGroupBox()
     text = QLabel(self)
     text.setText("Create image montages and histograms from the interface:\nChoose option No. 1 to 5 on main interface.\nClick Enter to select the paths for input and output locations.\nEnjoy using the interface!")
     self.setStyleSheet("QLabel { color: #8B4513; font-size: 16px;font-family: cursive, sans-serif;}")    
     title.setStyleSheet("QLabel { color: #8B4513; font-weight: 600;}")
     # set layout
     sbox = QVBoxLayout(self)
     sbox.addWidget(text)
     groupBox.setLayout(sbox) 
     vBoxLayout = QVBoxLayout()
     vBoxLayout.addSpacing(15)
     vBoxLayout.addWidget(title)
     vBoxLayout.addWidget(groupBox)
     vBoxLayout.addSpacing(15)
     self.setLayout(vBoxLayout)
     # set background as transparent
     palette	= QPalette()
     palette.setBrush(QPalette.Background,QBrush(QPixmap()))
     self.setPalette(palette)
Пример #17
0
 def _drawButtons(self, logoFnam):
     gbox = QGroupBox()
     spol = QSizePolicy()
     spol.horizontalPolicy = QSizePolicy.Maximum
     gbox.setSizePolicy(spol)
     vbox = QVBoxLayout()
     
     if os.path.isfile(logoFnam):
         img = QPixmap(logoFnam)    #.scaled(64, 64)
         lblLogo = QLabel()
         lblLogo.setPixmap(img)
         lblLogo.setAlignment(Qt.AlignTop | Qt.AlignRight)
         vbox.addWidget(lblLogo)
         #vbox.addSpacing(3) 
     
     self.butSave = self._drawButton(vbox, "M&odify", 'closeSave')
     font = QFont()
     font.setBold(True)
     self.butSave.setFont(font)
     self.butCancel = self._drawButton(vbox, "Cancel", 'closeCancel', True)
     vbox.addSpacing(36)
     self.butAddRule = self._drawButton(vbox, "Add Rule", 'addRule', True)
     self.butCopyRule = self._drawButton(vbox, "Copy Rule", 'copyRule')
     self.butDelRule = self._drawButton(vbox, "Delete Rule", 'delRule')
     self.butMoveRuleUp = self._drawButton(vbox, "Move Rule Up", 'moveRuleUp')
     self.butMoveRuleDn = self._drawButton(vbox, "Move Rule Down", 'moveRuleDown')
     vbox.addSpacing(24)
     self.butAddCond = self._drawButton(vbox, "Add Condition", 'addCond')
     self.butDelCond = self._drawButton(vbox, "Delete Condition", 'delCond')
     vbox.addSpacing(15)
     self.butAddAction = self._drawButton(vbox, "Add Action", 'addAction')
     self.butDelAction = self._drawButton(vbox, "Delete Action", 'delAction')
     
     gbox.setLayout(vbox)
     self.mainHSplit.addWidget(gbox) 
Пример #18
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("About Bii-IDE"))
        vbox = QVBoxLayout(self)

        pixmap = QPixmap(GUI_ICON_128)
        self.lblIcon = QLabel()
        self.lblIcon.setPixmap(pixmap)

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

        lblTitle = QLabel(
                '<h1>Bii-IDE</h1>\n<i>Arduino IDE<i>')
        lblTitle.setTextFormat(Qt.RichText)
        lblTitle.setAlignment(Qt.AlignLeft)
        hbox.addWidget(lblTitle)
        vbox.addLayout(hbox)
        vbox.addWidget(QLabel(self.tr("""Bii-IDE: Arduino IDE with support for biicode""")))
        vbox.addWidget(QLabel(self.tr("Version: %s" % __version__)))
        link_biigui = QLabel(
            self.tr('Website: <a href="https://github.com/biicode/bii-ide"><span style=" '
                'text-decoration: underline; color:#ff9e21;">'
                'https://github.com/biicode/bii-ide</span></a>'))
        vbox.addWidget(link_biigui)
        link_source = QLabel(
            self.tr('Source Code: <a href="https://github.com/biicode/bii-ide"><span style=" '
        'text-decoration: underline; color:#ff9e21;">https://github.com/biicode/bii-ide</span></a>'))
        vbox.addWidget(link_source)

        self.connect(link_biigui, SIGNAL("linkActivated(QString)"),
            self.link_activated)
        self.connect(link_source, SIGNAL("linkActivated(QString)"),
            self.link_activated)
Пример #19
0
class ImagePlayer(QWidget):
    def __init__(self, filename, title, parent=None):
        QWidget.__init__(self, parent)

        # Load the file into a QMovie
        self.movie = QMovie(filename, QByteArray(), self)

        size = self.movie.scaledSize()
        self.setGeometry(200, 200, size.width(), size.height())
        self.setWindowTitle(title)

        self.movie_screen = QLabel()
        # Make label fit the gif
        self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.movie_screen.setAlignment(Qt.AlignCenter)

        # Create the layout
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.movie_screen)

        self.setLayout(main_layout)

        # Add the QMovie object to the label
        self.movie.setCacheMode(QMovie.CacheAll)
        self.movie.setSpeed(100)
        self.movie_screen.setMovie(self.movie)
        self.movie.start()
Пример #20
0
    def add_parameter(self, name, parameter_data, parameter_change):
        layout = self.frm_parameters.layout()
        qtitle = QLabel(parameter_data[3])
        qslider = QSlider(Qt.Horizontal)
        qmin = QLabel(str(parameter_data[0]))
        qmax = QLabel(str(parameter_data[1]))
        qvalue = QLabel(str(parameter_data[2]))
        qslider.setRange(parameter_data[0], parameter_data[1])
        qslider.setValue(parameter_data[2])
        qtitle.setAlignment(Qt.AlignHCenter)
        qvalue.setAlignment(Qt.AlignHCenter)
        pos = layout.rowCount()
        layout.addWidget(qtitle, pos, 0, 1, 3)
        layout.addWidget(qmin, pos + 1, 0, 1, 1)
        layout.addWidget(qslider, pos + 1, 1, 1, 1)
        layout.addWidget(qmax, pos + 1, 2, 1, 1)
        layout.addWidget(qvalue, pos + 2, 0, 1, 3)

        def value_changed(value):
            v = parameter_change(name, value)
            qvalue.setNum(v)

        qslider.valueChanged.connect(value_changed)
        qslider.setTracking(True)

        self.parameters[name] = qslider
Пример #21
0
class IconWidget(QWidget):

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

        self.message = QLabel(self)

        self.message.setAlignment(Qt.AlignCenter)

        self.icon = QLabel(self)
        self.icon.setAlignment(Qt.AlignCenter)

        self._createLayout()


    def setIcon(self, path):
        pix = QPixmap(path)
        pix = pix.scaledToHeight(200, Qt.SmoothTransformation)
        self.icon.setPixmap(pix)


    def setMessage(self, msg):
        self.message.setText('<b>%s</b>' % msg)


    def _createLayout(self):

        l = QVBoxLayout()
        l.addStretch(1)
        l.addWidget(self.message)
        l.addSpacing(10)
        l.addWidget(self.icon)
        l.addStretch(1)

        self.setLayout(l)
Пример #22
0
    def __init__(self, title = "Title", description = "Description", parent=None):
        QDialog.__init__(self, parent)

        self.__option_list = []
        """ :type: list of HelpedWidget """

        self.setModal(True)
        self.setWindowTitle(title)
        # self.setMinimumWidth(250)
        # self.setMinimumHeight(150)

        self.layout = QFormLayout()
        self.layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        self.layout.setSizeConstraint(QLayout.SetFixedSize)

        label = QLabel(description)
        label.setAlignment(Qt.AlignHCenter)
        
        self.layout.addRow(self.createSpace(5))
        self.layout.addRow(label)
        self.layout.addRow(self.createSpace(10))

        self.ok_button = None


        self.setLayout(self.layout)
Пример #23
0
    def __init__(self, parent=None):
        super(aboutWidget, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle('LoL Server Status - About')
        self.setMinimumWidth(parent.width())
        self.move(parent.pos())
        self.setFocus(False)

        #label_title
        label_title = QLabel('LoL Server Status')
        label_title.setObjectName('label_title')
        label_title.setAlignment(Qt.AlignCenter)

        #label_source
        label_source = QLabel(
            'Source: <a style="color:#0073de" href="%s">Github repository</a>' %
            __source__)
        label_source.setToolTip('Github repository')
        label_source.setOpenExternalLinks(True)

        #btn_about_qt
        btn_about_qt = QPushButton('About Qt')

        #General layout
        vbox = QVBoxLayout(self)
        vbox.addWidget(label_title)
        vbox.addWidget(QLabel('Version: %s' % __version__))
        vbox.addWidget(QLabel('Author: %s' % __author__))
        vbox.addWidget(QLabel('License: %s' % __license__))
        vbox.addWidget(label_source)
        vbox.addWidget(btn_about_qt)

        #CONNECT SGNALS
        self.connect(btn_about_qt, SIGNAL('clicked()'), self.open_about_qt)
Пример #24
0
    def initUi(self):
        self.setWindowTitle('BLABLABLA')
        self.setMouseTracking(True)
        # self.setGeometry(50, 50, 1024, 768)
        # self.setMaximumSize(1024, 768)
        # self.setMinimumSize(800, 600)
        self.setLayout(self.hbox)
        self.hbox.addStretch(1)
        self.hbox.addLayout(self.vbox)
        self.hbox.addStretch(1)
        self.hbox.addWidget(self.grid)
        self.grid.show()
        self.vbox.addStretch(1)
        font = QFont()
        font.setBold(True)
        font.setPixelSize(30*variables.SCALE)
        label = QLabel("PUNTAJE")
        label.setFont(font)
        label.setAlignment(Qt.AlignCenter)
        self.vbox.addWidget(label)
        font2 = QFont()
        font2.setPixelSize(30*variables.SCALE)
        self.label_puntaje.setFont(font2)
        self.label_puntaje.setAlignment(Qt.AlignCenter)
        self.vbox.addWidget(self.label_puntaje)
        self.vbox.addWidget(self.button)
        self.vbox.addWidget(self.orientation)
        self.orientation.setAlignment(Qt.AlignCenter)
        self.orientation.setPixmap(self.__clockwise_pm)
        self.vbox.addStretch(1)
        self.button.clicked.connect(self.invertirPressed)

        self.grid.initUI()
Пример #25
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("About SIDE-C"))
        self.setMaximumSize(QSize(0, 0))
        

        vbox = QVBoxLayout(self)

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

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

        lblTitle = QLabel(
                '<h1>SIDE - C</h1>\n<i>Simple Integrated Development Environment for C<i>')
        lblTitle.setTextFormat(Qt.RichText)
        lblTitle.setAlignment(Qt.AlignLeft)
        hbox.addWidget(lblTitle)
        vbox.addLayout(hbox)
        #Add description
        vbox.addWidget(QLabel(
self.tr("""ALGO ACA""")))
        vbox.addWidget(QLabel("Hola"))
        link_ninja = QLabel(
            self.tr('Website: '))
        vbox.addWidget(link_ninja)
        link_source = QLabel(
            self.tr('Source Code'))
        vbox.addWidget(link_source)
Пример #26
0
class _StatusBar(QStatusBar):
    """Extended status bar. Supports HTML messages
    """
    def __init__(self, *args):
        QStatusBar.__init__(self, *args)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setSizeGripEnabled(False)
        self.setStyleSheet("QStatusBar {border: 0} QStatusBar::item {border: 0}")
        self._label = QLabel(self)
        self._label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self._label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self._label.setStyleSheet("color: red")
        self.addWidget(self._label)
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        self._timer.timeout.connect(self.clearMessage)
    
    def showMessage(self, text, timeout=0):
        """QStatusBar.showMessage()
        """
        self._label.setText(text)
        self._timer.stop()
        if timeout > 0:
            self._timer.start(timeout)
    
    def clearMessage(self):
        """QStatusBar.clearMessage()
        """
        self._label.clear()
Пример #27
0
class Option(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        Layout = QHBoxLayout(self)
        Layout.setMargin(0)
        
        self.button = Button(self)
        palette = QPalette(self.button.palette())
        palette.setColor(QPalette.Button, QColor('grey').dark(150))
        self.button.setPalette(palette)
        QObject.connect(self.button, SIGNAL('clicked()'), self.clicked)
        Layout.addWidget(self.button)
        
        self.label = QLabel(self)
        self.label.setFrameShape(QLabel.Panel)
        self.label.setFixedHeight(self.button.height())
        self.label.setAutoFillBackground(True)
        self.label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        palette = QPalette(self.label.palette())
        palette.setColor(QPalette.Window, QColor(151, 169, 0))
        self.label.setPalette(palette)
        Layout.addWidget(self.label)

    def clicked(self):
        self.emit(SIGNAL('selected(QString &)'), self.label.text())
    def __init__(self, parent, app):
        super(QWidget, self).__init__()

        layout1 = QHBoxLayout()
        layout2 = QVBoxLayout()
        
        layout1.addStretch()
        layout1.addLayout(layout2)
        layout1.addStretch()

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

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

        self.lcdwidget = LCDWidget(self, app)

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

        self.setLayout(layout1)

        self.qtcb_update_illuminance.connect(self.update_illuminance_data_slot)
        self.qtcb_update_air_pressure.connect(self.update_air_pressure_data_slot)
        self.qtcb_update_temperature.connect(self.update_temperature_data_slot)
        self.qtcb_update_humidity.connect(self.update_humidity_data_slot)
        self.qtcb_button_pressed.connect(self.button_pressed_slot)
Пример #29
0
    def starsRefresh(self):

        self.starsTableWidget.clearContents()

        try:
            starred = self.github.get_user().get_starred()
            self.starsTableWidget.setRowCount(self.github.get_user().public_repos)
        except (GithubException, AttributeError):
            return
        for row, repo in enumerate(starred):
            imageLabel = QLabel()
            if repo.fork:
                imageLabel.setPixmap(self.repo_fork_pixmap)
            else:
                imageLabel.setPixmap(self.repo_pixmap)
            imageLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            imageLabel.setMargin(5)

            self.starsTableWidget.setCellWidget(row, 0, imageLabel)
            label = QLabel(u'<b>{}/{}</b><br />{}'.format(
                unicode(repo.owner.login), unicode(repo.name), unicode(repo.description)))
            label.setAlignment(Qt.AlignVCenter)
            label.setMargin(5)
            label.setWordWrap(True)
            self.starsTableWidget.setCellWidget(row, 1, label)
            self.starsTableWidget.setItem(row, 2, 
                    QTableWidgetItem(QIcon(self.star_pixmap), '0'))
            self.starsTableWidget.setItem(row, 3, 
                    QTableWidgetItem(QIcon(self.eye_pixmap), str(repo.watchers_count)))
            self.starsTableWidget.setItem(row, 4, 
                    QTableWidgetItem(QIcon(self.fork_pixmap), str(repo.forks_count)))

        self.starsTableWidget.resizeRowsToContents()
Пример #30
0
    def __init__(self):
        super(AboutTab, self).__init__()
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        lbl_version = QLabel(self.tr("Versión: %s") % ui.__version__)
        label_descripcion = QLabel(self.tr(
            "a simple cross-platform IDE for C"))
        lbl_link = QLabel("Web: <a href='%s'><span style='color: #dedede;'>"
                          "%s</span></a>" % (ui.__web__, ui.__web__))
        lbl_sc = QLabel(self.tr("Código fuente: <a href='%s'><span style="
                        "'color: #dedede;'>%s</span></a>" %
                                (ui.__codigo_fuente__, ui.__codigo_fuente__)))
        logo = QPixmap(paths.ICONOS['icon'])
        label_logo = QLabel()
        label_logo.setAlignment(Qt.AlignCenter)
        label_logo.setPixmap(logo)
        box.addWidget(label_descripcion)
        box.addWidget(lbl_version)
        box.addWidget(lbl_link)
        box.addWidget(lbl_sc)
        box.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding,
                    QSizePolicy.Expanding))

        lbl_link.linkActivated.connect(lambda link: webbrowser.open(link))
        lbl_sc.linkActivated.connect(lambda link: webbrowser.open(link))
Пример #31
0
    def loading(self):
        if self.child:
            self.clear_layout(self)

        image = self.base.load_image('turpial-196.png', True)
        logo = QLabel()
        logo.setPixmap(image)
        logo.setAlignment(Qt.AlignCenter)
        logo.setContentsMargins(0, 80, 0, 0)

        appname = QLabel('Turpial 3')
        if detect_os() == OS_MAC:
            font = QFont('Maven Pro Light', 28, 0, False)
            font2 = QFont('Ubuntu', 16, 0, False)
        else:
            font = QFont('Maven Pro Light', 18, QFont.Light, False)
            font2 = QFont('Ubuntu', 12, QFont.Normal, False)
        appname.setFont(font)

        welcome = QLabel()
        welcome.setText(i18n.get('hi_there'))
        welcome.setAlignment(Qt.AlignCenter)
        welcome.setFont(font)

        message = QLabel()
        message.setText(i18n.get('give_me_a_minute'))
        message.setAlignment(Qt.AlignCenter)
        message.setWordWrap(True)
        message.setFont(font2)

        loader = BarLoadIndicator()

        self.child = QVBoxLayout()
        self.child.addWidget(logo)
        self.child.addWidget(welcome)
        self.child.addSpacing(10)
        self.child.addWidget(message)
        #self.child.setSpacing(10)
        self.child.addStretch(1)
        self.child.addWidget(loader)
        self.child.setContentsMargins(30, 0, 30, 30)

        self.insertLayout(0, self.child)
        self.is_empty = True
Пример #32
0
    def error(self):
        if self.child:
            self.clear_layout(self)

        image = self.base.load_image('turpial-196.png', True)
        logo = QLabel()
        logo.setPixmap(image)
        logo.setAlignment(Qt.AlignCenter)
        logo.setContentsMargins(0, 80, 0, 0)

        appname = QLabel('Turpial 3')
        if detect_os() == OS_MAC:
            font = QFont('Maven Pro Light', 28, 0, False)
            font2 = QFont('Ubuntu', 16, 0, False)
        else:
            font = QFont('Maven Pro Light', 18, QFont.Light, False)
            font2 = QFont('Ubuntu', 12, QFont.Normal, False)
        appname.setFont(font)

        welcome = QLabel()
        welcome.setText(i18n.get('oh_oh'))
        welcome.setAlignment(Qt.AlignCenter)
        welcome.setFont(font)

        message = QLabel()
        text = "%s. <a href='cmd:restart'>%s</a>" % (
            i18n.get('something_terrible_happened'), i18n.get('try_again'))
        message.setText(text)
        message.linkActivated.connect(self.__link_clicked)
        message.setAlignment(Qt.AlignCenter)
        message.setWordWrap(True)
        message.setFont(font2)

        self.child = QVBoxLayout()
        self.child.addWidget(logo)
        self.child.addWidget(welcome)
        self.child.addSpacing(10)
        self.child.addWidget(message)
        #self.child.setSpacing(10)
        self.child.addStretch(1)
        self.child.setContentsMargins(30, 0, 30, 30)

        self.insertLayout(0, self.child)
        self.is_empty = True
Пример #33
0
    def __init__(self):
        QDialog.__init__(self)
        vlayout = QVBoxLayout()
        self.setLayout(vlayout)
        self.explorer = ExplorerWidget(self)
        vlayout.addWidget(self.explorer)

        hlayout1 = QHBoxLayout()
        vlayout.addLayout(hlayout1)
        label = QLabel("<b>Open file:</b>")
        label.setAlignment(Qt.AlignRight)
        hlayout1.addWidget(label)
        self.label1 = QLabel()
        hlayout1.addWidget(self.label1)
        self.connect(self.explorer, SIGNAL("open_file(QString)"),
                     self.label1.setText)

        hlayout2 = QHBoxLayout()
        vlayout.addLayout(hlayout2)
        label = QLabel("<b>Open dir:</b>")
        label.setAlignment(Qt.AlignRight)
        hlayout2.addWidget(label)
        self.label2 = QLabel()
        hlayout2.addWidget(self.label2)
        self.connect(self.explorer, SIGNAL("open_dir(QString)"),
                     self.label2.setText)
        self.connect(self.explorer, SIGNAL("open_dir(QString)"),
                     lambda path: os.chdir(unicode(path)))

        hlayout3 = QHBoxLayout()
        vlayout.addLayout(hlayout3)
        label = QLabel("<b>Option changed:</b>")
        label.setAlignment(Qt.AlignRight)
        hlayout3.addWidget(label)
        self.label3 = QLabel()
        hlayout3.addWidget(self.label3)
        self.connect(
            self.explorer, SIGNAL("option_changed"),
            lambda x, y: self.label3.setText('option_changed: %r, %r' %
                                             (x, y)))

        self.connect(self.explorer, SIGNAL("open_parent_dir()"),
                     lambda: self.explorer.listwidget.refresh('..'))
Пример #34
0
class LogoDialog(QDialog):

    def __init__(self, parent=None):
        super(LogoDialog, self).__init__(parent)
        self.pagetitle = 'School Data' 
        stylesheet = Valid().background() + Valid().font()
        self.setStyleSheet(stylesheet)
        
        data = Db().selectn('datas', '', 1, {'pubID':'datas', 'name':'logo'})
        d = ''
        if data:
            d = data['description']
        else:
            d = ''
        
        self.pic1 = QLabel()
        self.pic1.setAlignment(Qt.AlignCenter)
        if os.path.isfile('./pic_main/logo.png'):
            image1 = Image.open('pic_main/logo.png')
        else:
            image1 = Image.open('img/stdpic.png')
        
        self.mainLink = ''
        imageQ1 = ImageQt(image1)
        imagep1 = QPixmap(QPixmap.fromImage(QImage(imageQ1).scaled(250, 300, Qt.IgnoreAspectRatio)))
        self.pic1.resize(250, 300)
        self.pic1.setPixmap(imagep1)
        self.pic1.setMaximumHeight(250)
        #self.pic1.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn1 = QPushButton('Select Image')
        self.picBtn1.clicked.connect(lambda:self.getFilez())
        self.colorLbl = QLabel('Please use only only images in png format prferablly with transperent background')
        self.colorLbl1 = QLabel('Image should be a perfect square')
        
        Gbo = QGridLayout()
        Gbo.addWidget(self.colorLbl, 0, 0)
        Gbo.addWidget(self.colorLbl1, 1, 0)
        Gbo.addWidget(self.pic1, 2, 0)
        Gbo.addWidget(self.picBtn1, 3, 0)
        
        groupBox1 = QGroupBox('Upload School Logo')
        groupBox1.setLayout(Gbo)
        
        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Save")
        
        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Close")
        
        hbo = QHBoxLayout()
        hbo.addWidget(self.pb1)
        hbo.addStretch()
        hbo.addWidget(self.pb)
        
        groupBox2 = QGroupBox('')
        groupBox2.setLayout(hbo)
            
        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 1, 0)
        
        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self))
        self.setWindowTitle(self.pagetitle)

    
    def getFilez(self):
         fname = QFileDialog.getOpenFileName(self, 'Select Image', 'c:\\', '*.png')
         image1 = Image.open(fname)
         imageQ1 = ImageQt(image1)
         imagep1 = QPixmap(QPixmap.fromImage(QImage(imageQ1).scaled(300, 300, Qt.IgnoreAspectRatio)))
         self.pic1.resize(300, 300)
         self.pic1.setPixmap(imagep1)
         self.mainLink = image1
        
    
    def setCurrentPix(self):
        file1 = "pic_main/"
        img = ''
        img = str(file1)+'logo.png'
             
        image1 = Image.open(img)
        imageQ1 = ImageQt(image1)
        imagep1 = QPixmap(QPixmap.fromImage(QImage(imageQ1).scaled(250, 250, Qt.IgnoreAspectRatio)))
        self.pic1.resize(250, 250)
        self.pic1.setPixmap(imagep1)
      
    
    def button_close(self, a):
        a.close()
      
    def button_click(self):
        fname = self.mainLink
        im1 = fname
        file1 = 'pic_thumb/'
        file2 = 'pic_main/'
        lnk = "logo.png"
      
        im1.thumbnail((128, 128))
        im1.save(file1 + lnk, "PNG" )
        
        im1.thumbnail((300, 300))
        im1.save(file2 + lnk, "PNG")
    
        g = Db()
        sel = g.selectn('datas', '', 1, {'pubID':'datas', 'name':'logo'})
        if sel and sel['id'] > 0:
            pass
        else:
            g.insert('datas', {'pubID':'datas', 'name':'logo', 'description': lnk})
            
        self.setCurrentPix()  
        self.button_close(self)
Пример #35
0
class LoginForm(QMainWindow):
    def __init__(self, parent=None):
        super(LoginForm, self).__init__(parent)
        self.width, self.height = 800, 650
        self.crear_interfaz(self.width, self.height)
        self.checkbox_rememberme.clicked.connect(self.remember_me)
        self.button_login.clicked.connect(self.logging)
        # self.div_create.setVisible(False)
        self.database = Database()
        """self.label_rememberme.mousePressEvent = self.do_remember

	def do_remember(self, event):
		# TDE FIXME: Create another remember_me method for remember me label 
		self.remember_me(event)
		"""

    def loading(self):
        print "loading..."

    def logging(self):
        self.valid_fields()

    def valid_fields(self):
        username = self.username.text()
        password = self.password.text()

        if username == '':
            self.username.setFocus(True)
        elif password == '':
            self.password.setFocus(True)
        else:
            self.loading()
            self.username.setEnabled(False)
            self.password.setEnabled(False)
            print "Logging validation username"
            if self.database.login(username, password):
                print "Bienvenido %s" % username
            else:
                print "Datos incorrectos!"

        # return True in end of statement

    def anim_left(self):
        animation = QPropertyAnimation(self.label_icon, "geometry")
        animation.setDuration(250)
        animation.setStartValue(QRect(0, 0, 20, 20))
        animation.setEndValue(QRect(20, 0, 20, 20))
        animation.start()
        self.animation = animation

    def anim_right(self):
        animation = QPropertyAnimation(self.label_icon, "geometry")
        animation.setDuration(250)
        animation.setStartValue(QRect(20, 0, 20, 20))
        animation.setEndValue(QRect(0, 0, 20, 20))
        animation.start()
        self.animation = animation

    def remember_me(self):
        if self.checkbox_rememberme.isChecked():
            self.anim_left()
            self.label_icon.setGeometry(20, 0, 20, 20)
        else:
            self.anim_right()
            self.label_icon.setGeometry(0, 0, 20, 20)

    def crear_interfaz(self, width, height):
        self.setMinimumSize(width, height)
        self.setMaximumSize(width, height)
        self.setWindowTitle('I n i c i a  s e s i ó n | SN')
        self.setObjectName('login_form_window')

        self.container = QWidget(self)
        self.container.setMinimumSize(width, height)
        self.container.setMaximumSize(width, height)
        self.container.setObjectName('login_container')

        self.title = QLabel(self)
        self.title.setText('I N I C I A   S E S I Ó N   G R Á T I S')
        self.title.setGeometry(210, 130, 400, 40)
        self.title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.title.setObjectName('login_title')

        self.username = QLineEdit(self)
        self.username.setPlaceholderText('N O M B R E  D E  U S U A R I O')
        self.username.setGeometry(260, 230, 300, 40)
        self.username.setObjectName('login_username')
        self.username.setAcceptDrops(False)

        self.password = QLineEdit(self)
        self.password.setPlaceholderText('C O N T R A S E Ñ A')
        self.password.setGeometry(260, 290, 300, 40)
        self.password.setObjectName('login_password')
        self.password.setEchoMode(QLineEdit.Password)

        self.checkbox_rememberme = QCheckBox(self)
        self.checkbox_rememberme.setLayoutDirection(Qt.RightToLeft)
        self.checkbox_rememberme.setGeometry(260, 360, 40, 20)
        self.checkbox_rememberme.setObjectName("login_rememberme")
        self.checkbox_rememberme.setCursor(QCursor(Qt.PointingHandCursor))

        self.label_icon = QLabel(self.checkbox_rememberme)
        self.label_icon.setGeometry(0, 0, 20, 20)
        self.label_icon.setObjectName("label_icon")

        self.label_rememberme = QLabel(self)
        self.label_rememberme.setText("R E C U É R D A M E")
        self.label_rememberme.setGeometry(310, 360, 165, 20)
        self.label_rememberme.setObjectName("label_rememberme")

        self.button_login = QPushButton(self)
        self.button_login.setGeometry(315, 420, 200, 40)
        self.button_login.setText("I N I C I A R  S E S I Ó N")
        self.button_login.setObjectName("button_login")

        self.layout = QGridLayout(self.container)
Пример #36
0
class YPipeWidget(QWidget):
    def __init__(self, leftFlow=0, rightFlow=0, maxFlow=100, parent=None):
        super(YPipeWidget, self).__init__(parent)

        self.leftSpinBox = QSpinBox(self)
        self.leftSpinBox.setRange(0, maxFlow)
        self.leftSpinBox.setValue(leftFlow)
        self.leftSpinBox.setSuffix(" l/s")
        self.leftSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.connect(self.leftSpinBox, SIGNAL("valueChanged(int)"),
                     self.valueChanged)

        self.rightSpinBox = QSpinBox(self)
        self.rightSpinBox.setRange(0, maxFlow)
        self.rightSpinBox.setValue(rightFlow)
        self.rightSpinBox.setSuffix(" l/s")
        self.rightSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.connect(self.rightSpinBox, SIGNAL("valueChanged(int)"),
                     self.valueChanged)

        self.label = QLabel(self)
        self.label.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.label.setAlignment(Qt.AlignCenter)
        fm = QFontMetricsF(self.font())
        self.label.setMinimumWidth(fm.width(" 999 l/s "))

        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setMinimumSize(self.minimumSizeHint())
        self.valueChanged()

    def valueChanged(self):
        a = self.leftSpinBox.value()
        b = self.rightSpinBox.value()
        self.label.setText("{0} l/s".format(a + b))
        self.emit(SIGNAL("valueChanged"), a, b)
        self.update()

    def values(self):
        return self.leftSpinBox.value(), self.rightSpinBox.value()

    def minimumSizeHint(self):
        return QSize(self.leftSpinBox.width() * 3,
                     self.leftSpinBox.height() * 5)

    def resizeEvent(self, event=None):
        fm = QFontMetricsF(self.font())
        x = (self.width() - self.label.width()) / 2
        y = self.height() - (fm.height() * 1.5)
        self.label.move(x, y)
        y = self.height() / 60.0
        x = (self.width() / 4.0) - self.leftSpinBox.width()
        self.leftSpinBox.move(x, y)
        x = self.width() - (self.width() / 4.0)
        self.rightSpinBox.move(x, y)

    def paintEvent(self, event=None):
        LogicalSize = 100.0

        def logicalFromPhysical(length, side):
            return (length / side) * LogicalSize

        fm = QFontMetricsF(self.font())
        ymargin = (
            (LogicalSize / 30.0) +
            logicalFromPhysical(self.leftSpinBox.height(), self.height()))
        ymax = (LogicalSize -
                logicalFromPhysical(fm.height() * 2, self.height()))
        width = LogicalSize / 4.0
        cx, cy = LogicalSize / 2.0, LogicalSize / 3.0
        ax, ay = cx - (2 * width), ymargin
        bx, by = cx - width, ay
        dx, dy = cx + width, ay
        ex, ey = cx + (2 * width), ymargin
        fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0)
        gx, gy = fx, ymax
        hx, hy = cx - (width / 2), ymax
        ix, iy = hx, fy

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        side = min(self.width(), self.height())
        painter.setViewport((self.width() - side) / 2,
                            (self.height() - side) / 2, side, side)
        painter.setWindow(0, 0, LogicalSize, LogicalSize)

        painter.setPen(Qt.NoPen)

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        a = self.leftSpinBox.value()
        gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([ax, ay, bx, by, cx, cy, ix, iy]))

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        b = self.rightSpinBox.value()
        gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([cx, cy, dx, dy, ex, ey, fx, fy]))

        if (a + b) == 0:
            color = QColor(Qt.white)
        else:
            ashare = (a / (a + b)) * 255.0
            bshare = 255.0 - ashare
            color = QColor(ashare, 0, bshare)
        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        gradient.setColorAt(1, color)
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([cx, cy, fx, fy, gx, gy, hx, hy, ix, iy]))

        painter.setPen(Qt.black)
        painter.drawPolyline(QPolygon([ax, ay, ix, iy, hx, hy]))
        painter.drawPolyline(QPolygon([gx, gy, fx, fy, ex, ey]))
        painter.drawPolyline(QPolygon([bx, by, cx, cy, dx, dy]))
Пример #37
0
class _QueuedMessageWidget(QWidget):
    
    cleared = pyqtSignal()
    finished = pyqtSignal()
    shown = pyqtSignal()
    closed = pyqtSignal()
    linkActivated = pyqtSignal(unicode)
    linkHovered= pyqtSignal(unicode)
    buttonClicked = pyqtSignal(QAbstractButton)
    
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self._messages = []
        self._defaultTimeout = 0
        self._defaultPixmap = QPixmap(":/enkiicons/infos.png" )
        self._defaultBackground = QBrush( QColor( 250, 230, 147 ) )
        self._defaultForeground = QBrush( QColor( 0, 0, 0 ) )
        
        # pixmap
        self.lPixmap = QLabel( self )
        self.lPixmap.setAlignment( Qt.AlignCenter )
        self.lPixmap.setSizePolicy( QSizePolicy( QSizePolicy.Maximum, QSizePolicy.Preferred ) )
        
        # message
        self.lMessage = QLabel( self )
        self.lMessage.setAlignment( Qt.AlignVCenter | Qt.AlignLeft )
        self.lMessage.setSizePolicy( QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) )
        self.lMessage.setWordWrap( True )
        self.lMessage.setOpenExternalLinks( True )
        self.lMessage.setTextInteractionFlags( Qt.TextBrowserInteraction )
        
        # button
        self.dbbButtons = QDialogButtonBox( self )
        
        # if false - buttons don't have neither text nor icons
        self.dbbButtons.setStyleSheet("dialogbuttonbox-buttons-have-icons: true;")

        self.dbbButtons.setSizePolicy( QSizePolicy( QSizePolicy.Maximum, QSizePolicy.Preferred ) )
        
        self.setSizePolicy( QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Maximum ) )
        
        # layout
        self.hbl = QHBoxLayout( self )
        self.hbl.setMargin( 0 )
        self.hbl.addWidget( self.lPixmap, 0, Qt.AlignCenter )
        self.hbl.addWidget( self.lMessage )
        self.hbl.addWidget( self.dbbButtons, 0, Qt.AlignCenter )
        
        # connections
        self.lMessage.linkActivated.connect(self.linkActivated)
        self.lMessage.linkHovered.connect(self.linkHovered)
        self.dbbButtons.clicked.connect(self.buttonClicked)

    def sizeHint(self):
        return QWidget.minimumSizeHint(self)

    def openExternalLinks(self):
        return self.lMessage.openExternalLinks()

    def defaultTimeout(self):
        return self._defaultTimeout

    def defaultPixmap(self):
        return self._defaultPixmap

    def defaultBackground(self):
        return self._defaultBackground

    def defaultForeground(self):
        return self._defaultForeground

    def currentMessageInformations(self):
        return self.currentMessagePixmap(), self.currentMessageBackground(), self.currentMessageForeground()

    def pendingMessageCount(self):
        return len(self._messages)

    def currentMessage(self):
        return self._messages[0]

    def append(self, message, milliSeconds ):
        msg = _QueuedMessage()
        msg.message = message
        if milliSeconds == -1:
            msg.milliSeconds = self._defaultTimeout
        else:
           msg.milliSeconds = milliSeconds
        msg.pixmap = self._defaultPixmap
        msg.background = self._defaultBackground
        msg.foreground = self._defaultForeground
        
        self._messages.append(msg)
            
        if  len(self._messages) == 1 :
            QTimer.singleShot( 0, self.showMessage)

    def setOpenExternalLinks(self, open ):
        self.lMessage.setOpenExternalLinks( open )

    def setDefaultTimeout(self, timeout ):
        self._defaultTimeout = timeout

    def setDefaultPixmap(self, pixmap ):
        self._defaultPixmap = pixmap

    def setDefaultBackground(self, brush ):
        self._defaultBackground = brush

    def setDefaultForeground(self, brush ):
        self._defaultForeground = brush

    def remove(self, message ):
        raise NotImplemented()  # incorrect port from cpp fresh
        if not self._messages or self._messages.first() == message:
            return

        self._messages.removeOne( message )

    def clear(self):
        self._messages.clear()
        self.lPixmap.clear()
        self.lMessage.clear()
        self.dbbButtons.clear()
        self.cleared.emit()

    def currentMessagePixmap(self):
        msg = self.currentMessage()
        if msg.pixmap.isNull():
            return self._defaultPixmap
        else:
            return msg.pixmap

    def currentMessageBackground(self):
        msg = self.currentMessage()
        if msg.background == QBrush( Qt.NoBrush ):
            return self._defaultBackground
        else:
            return msg.background

    def currentMessageForeground(self):
        msg = self.currentMessage()
        if msg.foreground == QBrush( Qt.NoBrush ):
            return self._defaultForeground
        else:
            return msg.foreground

    def paintEvent(self, event ):
        if  self.pendingMessageCount() == 0 :
            QWidget.paintEvent(self, event )
            return
        
        painter = QPainter( self )
        painter.setPen( Qt.NoPen )
        painter.setBrush( self.currentMessageBackground() )
        painter.drawRect( self.contentsRect() )

    def buttonClicked(self, button ):
        msg = self.currentMessage()
        standardButton = self.dbbButtons.standardButton( button )
        
        if msg.slot is not None:
            msg.slot(standardButton, msg)
        
        self.closeMessage()

    def showMessage(self):
        # get message
        msg = self.currentMessage()
        
        # update palette
        pal = self.lMessage.palette()
        pal.setBrush( self.lMessage.foregroundRole(), self.currentMessageForeground() )
        self.lMessage.setPalette( pal )
        
        # format widget
        self.lPixmap.setPixmap( self.currentMessagePixmap() )
        self.lMessage.setText( msg.message )
        self.lMessage.setToolTip( msg.message )
        self.lMessage.setWhatsThis( msg.message )
        
        # set buttons
        if not msg.buttons:
            msg.buttons[ QDialogButtonBox.Close ] = None

        self.dbbButtons.clear()
        
        for button in msg.buttons.keys():
            pb = self.dbbButtons.addButton( button )
            
            if button in msg.buttons:
                pb.setText( msg.buttons[ button ] )
        
        # auto close if needed
        if msg.milliSeconds == -1:
            timeout = self._defaultTimeout
        else:
            timeout =  msg.milliSeconds
        
        if  timeout > 0:
            QTimer.singleShot( timeout, self.closeMessage )
        
        # signal.emit
        self.shown.emit()

    def closeMessage(self):
        # message.emit
        self.closed.emit()
        
        # remove remove current message from hash
        self._messages = self._messages[1:]
        
        # process next if possible, clear gui
        if self._messages:
            QTimer.singleShot( 0, self.showMessage)
        else:
            QTimer.singleShot( 0, self.clearMessage)
        
        # finished.emit message if needed
        if not self._messages:
            self.finished.emit()

    def clearMessage(self):
        self.lPixmap.clear()
        self.lMessage.clear()
        self.dbbButtons.clear()
Пример #38
0
class CImprovedButton(QToolButton):
    def __init__(self, parent=None):
        QToolButton.__init__(self, parent)

        #TESTO ALTERNATIVO
        #Spesso se il pulsante ha icona troppo grossa e quando per ragioni di spazio o altro non si può spostare
        #o ridimensionare il pulsante stesso, la label ha posizioni assurde e schifose. Aggiungerne una "+ controllabile"
        #è l'unico modo..
        self.__fixed_label = QLabel("alternative label", self)
        self.__fixed_label.move(0, self.geometry().height() - 35)
        self.__fixed_label.resize(self.geometry().width(),
                                  self.__fixed_label.geometry().height())
        self.__fixed_label.setAlignment(QtCore.Qt.AlignHCenter
                                        | QtCore.Qt.AlignVCenter)
        self.__font = QtGui.QFont("Arial", 10)
        self.__fixed_label.setFont(self.__font)
        self.__fixed_label.show()

        #INDICATORE STILE iOS
        self.__indicator = QLabel("0", self)
        self.__indicator.setStyleSheet(
            "border-image: url(':/images/backgrounds/indicator.png'); padding-right:1px; color: white;"
        )
        self.__indicator.geometry().setWidth(25)
        self.__indicator.geometry().setHeight(20)
        self.__indicator.setAlignment(QtCore.Qt.AlignHCenter
                                      | QtCore.Qt.AlignVCenter)
        self.__indicator.setVisible(False)
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(),
                                    0))  #default top-right corner
        #Quando il pulsante viene ridimensionato (designer o meno) devo anche sistemare la label di conseguenza
        self.resizeEvent = self.__onResize
        self.__indicator.resizeEvent = self.__on_indicator_Resize

        self.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)

        self.clicked.connect(self.stopAllAnimations)

        #BLINK
        self.__blink_timer = QTimer(parent)
        self.__blink_timer.timeout.connect(self.__on_blink_timer)
        self.__blink_timer_interval = 1000

        #FADING
        self.__opacity_effect = QGraphicsOpacityEffect()
        self.__fading_timer = QTimer(parent)
        self.__fading_timer.timeout.connect(self.__on_fading_timer)
        self.__FADE_TYPE = Enum("IN", "OUT")
        self.__fade_time = 20
        self.__opacity = 1.0
        self.__opacity_fading_coefficient = 0.02
        self.__selected_fade_type = self.__FADE_TYPE.IN

        # ANIMAZIONI GROW
        self.__animationGrow = QPropertyAnimation(self, "iconSize", self)
        self.__animationGrow.setDuration(1000)
        self.__animationGrow.setEasingCurve(QEasingCurve.Linear)
        self.__animationGrow.finished.connect(self.__on_growed)

        self.__animationShrink = QPropertyAnimation(self, "iconSize", self)
        self.__animationShrink.setDuration(1000)
        self.__animationShrink.setEasingCurve(QEasingCurve.Linear)
        self.__animationShrink.finished.connect(self.__on_shrinked)

        self.__defaultIconDimension = 60
        self.__iconGrowsBy = 40
        self.__growing = False

        # ANIMAZIONI BOUNCE
        self.__animationUp = QPropertyAnimation(self, "pos", self)
        self.__animationUp.setDuration(200)
        self.__animationUp.setEasingCurve(QEasingCurve.Linear)
        self.__animationUp.finished.connect(self.__on_top_reached)

        self.__animationBounce = QPropertyAnimation(self, "pos", self)
        self.__animationBounce.setDuration(1000)
        self.__animationBounce.setEasingCurve(QEasingCurve.OutBounce)
        self.__animationBounce.finished.connect(self.__on_bounce_finished)

        self.__bouncing = False
        self.__startPos = QPoint(self.pos().x(), self.pos().y())

        #PIXMAP & MASCHERA
        self.__pmap = QPixmap(self.size())
        self.__pmap_fname = ""
        self.__show_mask_preview = False

    def setDefaultIconSize(self, value):
        """ Sets default icon size when growing stops.
        @param value: size (both width and height)
        @type value: int
        """
        self.__defaultIconDimension = value

    def getDefaultIconSize(self):
        return self.__defaultIconDimension

    defaultIconSize = QtCore.pyqtProperty("int", getDefaultIconSize,
                                          setDefaultIconSize)

    def setFixetTextVisibility(self, bool):
        """ Sets if fixed text is visible or not.
        @param bool: visible or not
        @type bool: bool
        """
        self.__fixed_label.setVisible(bool)

    def getFixetTextVisibility(self):
        return self.__fixed_label.isVisible()

    fixetTextVisibility = QtCore.pyqtProperty("bool",
                                              fget=getFixetTextVisibility,
                                              fset=setFixetTextVisibility)

    def setFixedText(self, txt):
        """ Sets text on the button.
        @param txt: text
        @type txt: string
        """
        self.__fixed_label.setText(txt)

    def getFixedText(self):
        return self.__fixed_label.text()

    fixedText = QtCore.pyqtProperty("QString", getFixedText, setFixedText)

    def setFixedTextPos(self, qpoint):
        """ Sets text position in the button.
        @param qpoint: Position RELATIVE. 0,0 is top left corner of the button.
        @type qpoint: QPoint
        """
        self.__fixed_label.move(qpoint)

    def getFixedTextPos(self):
        return self.__fixed_label.pos()

    fixedTextPos = QtCore.pyqtProperty("QPoint", getFixedTextPos,
                                       setFixedTextPos)

    def setFixedTextFont(self, font):
        """ Sets text font.
        @param font: Font for fixed text.
        @type font: QFont
        """
        self.__font = font
        self.__fixed_label.setFont(self.__font)

    def getFixedTextFont(self):
        return self.__font

    fixedTextFont = QtCore.pyqtProperty("QFont", getFixedTextFont,
                                        setFixedTextFont)

    #FUNZIONI INDICATORE
    def setIndicatorVisibility(self, bool):
        """ Sets if indicator is visible or not.
        @param bool: visible or not
        @type bool: bool
        """
        self.__indicator.setVisible(bool)

    def getIndicatorVisibility(self):
        return self.__indicator.isVisible()

    indicatorVisibility = QtCore.pyqtProperty("bool",
                                              fget=getIndicatorVisibility,
                                              fset=setIndicatorVisibility)

    def setIndicatorPos(self, qpoint):
        """ Sets indicator position in the button.
        @param qpoint: Position RELATIVE. 0,0 is top left corner of the button.
        @type qpoint: QPoint
        """
        self.__indicator.move(qpoint)

    def getIndicatorPos(self):
        return self.__indicator.pos()

    indicatorPos = QtCore.pyqtProperty("QPoint", getIndicatorPos,
                                       setIndicatorPos)

    def setIndicatorSize(self, size):
        """ Sets indicator size.
        @param size: Size
        @type size: QSize
        """
        self.__indicator.resize(size)

    def getIndicatorSize(self):
        return self.__indicator.size()

    indicatorSize = QtCore.pyqtProperty("QSize", getIndicatorSize,
                                        setIndicatorSize)

    def setIndicatorFont(self, font):
        """ Sets indicator text font.
        @param font: Font for indicator text.
        @type font: QFont
        """
        self.__indicator.setFont(font)

    def getIndicatorFont(self):
        return self.__indicator.font()

    indicatorFont = QtCore.pyqtProperty("QFont", getIndicatorFont,
                                        setIndicatorFont)

    ## FUNZIONI PER BLINK
    def __on_blink_timer(self):
        self.setVisible(not (self.isVisible()))

    def setBlinking(self, blink):
        """ Sets if the button have to blink or not.
        @param blink: blinking or not
        @type blink: bool
        """
        if blink:
            self.__blink_timer.setInterval(self.__blink_timer_interval)
            self.__blink_timer.start()
        else:
            self.__blink_timer.stop()
            self.setVisible(True)

    def setBlinkInterval(self, value):
        """ Sets blink interval.
        @param blink: blink interval (msec)
        @type blink: int
        """
        self.__blink_timer_interval = value

    def getBlinkInterval(self):
        return self.__blink_timer_interval

    blinkInterval = QtCore.pyqtProperty("int", getBlinkInterval,
                                        setBlinkInterval)

    ##FUNZIONI PER FADING
    def fadeIn(self):
        """
         Button fades in from completely invisible to completely visible.
        """
        self.__opacity = 0.0
        self.__selected_fade_type = self.__FADE_TYPE.IN
        self.__fading_timer.start(self.__fade_time)

    def fadeOut(self):
        """
         Button fades out from completely visible to completely invisible.
        """
        self.__selected_fade_type = self.__FADE_TYPE.OUT
        self.__fading_timer.start(self.__fade_time)

    def setFadeTime(self, value):
        """ Sets fading time. Everytime interval is reached, alpha is increased (or decreased) by __opacity_fading_coefficient.
        @param value: fade time (msec)
        @type value: int
        """
        self.__fade_time = value

    def getFadeTime(self):
        return self.__fade_time

    fadeInterval = QtCore.pyqtProperty("int", getFadeTime, setFadeTime)

    def setFadeCoefficient(self, value):
        """ Sets fading coefficient. Alpha is increased (or decreased) by this value.
        @param value: coefficient (min 0.0 - max 1.0)
        @type value: float
        """
        self.__opacity_fading_coefficient = value

    def getFadeCoefficient(self):
        return self.__opacity_fading_coefficient

    fadeCoefficient = QtCore.pyqtProperty("double", getFadeCoefficient,
                                          setFadeCoefficient)

    def __on_fading_timer(self):
        if self.__selected_fade_type == self.__FADE_TYPE.OUT:
            if self.__opacity > 0:
                self.__opacity -= self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

        if self.__selected_fade_type == self.__FADE_TYPE.IN:
            if self.__opacity <= 1.0:
                self.__opacity += self.__opacity_fading_coefficient
                self.__opacity_effect.setOpacity(self.__opacity)
                self.setGraphicsEffect(self.__opacity_effect)
            else:
                self.__fading_timer.stop()

    # FUNZIONI PER GROW\SHRINK
    def __on_growed(self):
        self.__animationShrink.setStartValue(
            QSize(self.iconSize().width(),
                  self.iconSize().height()))
        self.__animationShrink.setEndValue(
            QSize(self.iconSize().width() - self.__iconGrowsBy,
                  self.iconSize().height() - self.__iconGrowsBy))
        self.__animationShrink.start()

    def __on_shrinked(self):
        self.__animationGrow.setStartValue(
            QSize(self.iconSize().width(),
                  self.iconSize().height()))
        self.__animationGrow.setEndValue(
            QSize(self.iconSize().width() + self.__iconGrowsBy,
                  self.iconSize().height() + self.__iconGrowsBy))
        self.__animationGrow.start()

    def startGrow(self):
        """
         Button ICON starts to grow and shrink to standard value when maximum size (configured) is reached
        """
        if self.__growing:
            return
        self.__animationGrow.setStartValue(
            QSize(self.iconSize().width(),
                  self.iconSize().height()))
        self.__animationGrow.setEndValue(
            QSize(self.iconSize().width() + self.__iconGrowsBy,
                  self.iconSize().height() + self.__iconGrowsBy))
        self.__animationGrow.start()
        self.__growing = True

    def stopGrow(self):
        if self.__animationGrow.startValue().toSize() != QSize(
                0,
                0) and self.__animationShrink.startValue().toSize() != QPoint(
                    0, 0):
            self.__animationGrow.stop()
            self.__animationShrink.stop()
            self.setIconSize(
                QSize(self.__defaultIconDimension,
                      self.__defaultIconDimension))
            self.__growing = False

    #FUNZIONI PER BOUNCE
    def startBounce(self):
        """
         Button starts to bounce requiring attention.
        """
        if self.__bouncing:
            return
        self.__startPos = QPoint(self.pos().x(), self.pos().y())
        self.__animationUp.setStartValue(
            QPoint(self.__startPos.x(), self.__startPos.y()))
        self.__animationUp.setEndValue(
            QPoint(self.__startPos.x(),
                   self.__startPos.y() - self.geometry().height()))
        self.__animationUp.start()
        self.__bouncing = True

    def stopBounce(self):
        if self.__animationUp.startValue().toPoint() != QPoint(
                0,
                0) and self.__animationBounce.startValue().toPoint() != QPoint(
                    0, 0):
            self.__animationBounce.stop()
            self.__animationUp.stop()
            self.setGeometry(self.__startPos.x(), self.__startPos.y(),
                             self.geometry().width(),
                             self.geometry().height())
            self.__bouncing = False

    def __on_top_reached(self):
        self.__animationBounce.setStartValue(
            QPoint(self.pos().x(),
                   self.pos().y()))
        self.__animationBounce.setEndValue(
            QPoint(self.__startPos.x(), self.__startPos.y()))
        self.__animationBounce.start()

    def __on_bounce_finished(self):
        self.__animationUp.start()

    def stopAllAnimations(self):
        self.stopBounce()
        self.stopGrow()

    #FUNZIONI PER PIXMAP & MASCHERA
    def setPixmapFile(self, image_file):
        self.__pmap = image_file
        self.__pmap.scaled(self.size())
        #NB: Il pixmap deve essere BIANCO e NERO. Con heuristicMask il primo pixel in alto a sinistra (0,0) viene
        #usato per decidere il colore trasparente, tutto il resto è visibile.

    def getPixmapFile(self):
        return self.__pmap

    pixmapFile = QtCore.pyqtProperty("QPixmap", getPixmapFile, setPixmapFile)

    def applyMask(self, bool):
        self.__show_mask_preview = bool
        if bool:
            self.setMask(
                QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))
        else:
            self.setMask(QBitmap())

    def getMask(self):
        return self.__show_mask_preview

    appliedMask = QtCore.pyqtProperty("bool", fget=getMask, fset=applyMask)

    def __onResize(self, event):
        self.__fixed_label.move(0, self.geometry().height() - 35)
        self.__fixed_label.resize(self.geometry().width(),
                                  self.__fixed_label.geometry().height())
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(),
                                    0))
        self.__pmap.scaled(self.size())
        if self.__show_mask_preview:
            self.setMask(
                QBitmap(self.__pmap.createHeuristicMask().scaled(self.size())))

    def __on_indicator_Resize(self, event):
        self.setIndicatorPos(QPoint(self.width() - self.__indicator.width(),
                                    0))
Пример #39
0
class PlotScalesWidget(QWidget):
    plotScaleChanged = pyqtSignal()

    def __init__(self, type_key, title, select_min_time_value=False):
        QWidget.__init__(self)

        self.__type_key = type_key
        self.__type = None

        self.__double_spinner = self.createDoubleSpinner(minimum=-999999999.0,
                                                         maximum=999999999.0)
        self.__integer_spinner = self.createIntegerSpinner(minimum=0,
                                                           maximum=999999999)

        self.__time_map = ReportStepsModel().getList()
        self.__time_index_map = {}
        for index in range(len(self.__time_map)):
            time = self.__time_map[index]
            self.__time_index_map[time] = index

        self.__time_spinner = self.createTimeSpinner(
            select_minimum_value=select_min_time_value)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.__label = QLabel(title)
        self.__label.setAlignment(Qt.AlignHCenter)

        self.__stack = QStackedWidget()
        self.__stack.setSizePolicy(QSizePolicy(QSizePolicy.Preferred))
        self.__stack.addWidget(self.__integer_spinner)
        self.__stack.addWidget(self.__double_spinner)
        self.__stack.addWidget(self.__time_spinner)

        layout.addWidget(self.__stack)
        layout.addWidget(self.__label)

        self.setLayout(layout)

    def createDoubleSpinner(self, minimum, maximum):
        spinner = QDoubleSpinBox()
        spinner.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        spinner.setMinimumWidth(105)
        spinner.setRange(minimum, maximum)
        spinner.setKeyboardTracking(False)
        spinner.setDecimals(8)

        spinner.editingFinished.connect(self.plotScaleChanged)
        spinner.valueChanged.connect(self.plotScaleChanged)

        return spinner

    def createIntegerSpinner(self, minimum, maximum):
        spinner = QSpinBox()
        spinner.setMinimumWidth(75)
        spinner.setRange(minimum, maximum)
        spinner.setKeyboardTracking(False)

        spinner.editingFinished.connect(self.plotScaleChanged)
        spinner.valueChanged.connect(self.plotScaleChanged)

        return spinner

    def createTimeSpinner(self, select_minimum_value):
        def converter(item):
            return "%s" % (str(item.date()))

        spinner = ListSpinBox(self.__time_map)
        spinner.setMinimumWidth(75)

        if select_minimum_value:
            spinner.setValue(0)

        spinner.valueChanged[int].connect(self.plotScaleChanged)
        spinner.editingFinished.connect(self.plotScaleChanged)
        spinner.setStringConverter(converter)

        return spinner

    def getValue(self):
        if self.__type is int:
            return self.__integer_spinner.value()
        elif self.__type is float:
            return self.__double_spinner.value()
        elif self.__type is CTime:
            index = self.__time_spinner.value()
            return self.__time_map[index]
        else:
            raise TypeError("Unsupported spinner type: %s" % self.__type)

    def setValue(self, value):
        if value is not None:
            if self.__type is int:
                self.__integer_spinner.setValue(int(value))
            elif self.__type is float:
                self.__double_spinner.setValue(value)
            elif self.__type is CTime:
                index = self.__time_index_map[value]
                self.__time_spinner.setValue(index)
            else:
                raise TypeError("Unsupported spinner type: %s" % self.__type)

    def setFontSize(self, size):
        font = self.__double_spinner.font()
        font.setPointSize(size)
        self.__double_spinner.setFont(font)

        font = self.__integer_spinner.font()
        font.setPointSize(size)
        self.__integer_spinner.setFont(font)

        font = self.__time_spinner.font()
        font.setPointSize(size)
        self.__time_spinner.setFont(font)

        font = self.__label.font()
        font.setPointSize(size)
        self.__label.setFont(font)

    def setType(self, spinner_type):
        self.__type = spinner_type
        if spinner_type is int:
            self.__stack.setCurrentWidget(self.__integer_spinner)
        elif spinner_type is float:
            self.__stack.setCurrentWidget(self.__double_spinner)
        elif spinner_type is CTime:
            self.__stack.setCurrentWidget(self.__time_spinner)
        else:
            raise TypeError("Unsupported spinner type: %s" % spinner_type)

    def getType(self):
        return self.__type
Пример #40
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(700, 300)
        self.setSizeGripEnabled(True)

        layout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Columns
        colsLabel = QLabel("Columns")
        self.__colsEdit = QLineEdit()
        self.__colsEdit.setText(str(self.__settings.settings["COL_LIMIT"]))
        self.__colsEdit.setToolTip(self.__settings.getDescription("COL_LIMIT"))
        self.__colsEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(colsLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.__colsEdit, 0, 1, 1, 1)
        font = self.__colsEdit.font()
        font.setFamily(GlobalData().skin.baseMonoFontFace)
        self.__colsEdit.setFont(font)

        # Assignment
        assignmentLabel = QLabel("Assignment")
        self.__assignmentEdit = QLineEdit()
        self.__assignmentEdit.setText(self.__settings.settings["ASSIGNMENT"])
        self.__assignmentEdit.setToolTip(
            self.__settings.getDescription("ASSIGNMENT"))
        self.__assignmentEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(assignmentLabel, 0, 3, 1, 1)
        gridLayout.addWidget(self.__assignmentEdit, 0, 4, 1, 1)
        self.__assignmentEdit.setFont(font)

        # Function parameters assignment
        funcAssignLabel = QLabel("Function params\nassignment")
        self.__funcAssignEdit = QLineEdit()
        self.__funcAssignEdit.setText(
            self.__settings.settings["FUNCTION_PARAM_ASSIGNMENT"])
        self.__funcAssignEdit.setToolTip(
            self.__settings.getDescription("FUNCTION_PARAM_ASSIGNMENT"))
        self.__funcAssignEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(funcAssignLabel, 1, 0, 1, 1)
        gridLayout.addWidget(self.__funcAssignEdit, 1, 1, 1, 1)
        self.__funcAssignEdit.setFont(font)

        # Dictionary separator
        dictSepLabel = QLabel("Dictionary separator")
        self.__dictSepEdit = QLineEdit()
        self.__dictSepEdit.setText(self.__settings.settings["DICT_COLON"])
        self.__dictSepEdit.setToolTip(
            self.__settings.getDescription("DICT_COLON"))
        self.__dictSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(dictSepLabel, 1, 3, 1, 1)
        gridLayout.addWidget(self.__dictSepEdit, 1, 4, 1, 1)
        self.__dictSepEdit.setFont(font)

        # Slice separator
        sliceSepLabel = QLabel("Slice separator")
        self.__sliceSepEdit = QLineEdit()
        self.__sliceSepEdit.setText(self.__settings.settings["SLICE_COLON"])
        self.__sliceSepEdit.setToolTip(
            self.__settings.getDescription("SLICE_COLON"))
        self.__sliceSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(sliceSepLabel, 2, 0, 1, 1)
        gridLayout.addWidget(self.__sliceSepEdit, 2, 1, 1, 1)
        self.__sliceSepEdit.setFont(font)

        # Interpreter
        inLabel = QLabel("Interpreter")
        self.__inEdit = QLineEdit()
        self.__inEdit.setText(self.__settings.settings["SHEBANG"])
        self.__inEdit.setToolTip(self.__settings.getDescription("SHEBANG"))
        self.__inEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(inLabel, 2, 3, 1, 1)
        gridLayout.addWidget(self.__inEdit, 2, 4, 1, 1)
        self.__inEdit.setFont(font)

        # Coding spec
        codingLabel = QLabel("Output encoding")
        self.__outCodingEdit = QLineEdit()
        self.__outCodingEdit.setText(self.__settings.settings["CODING"])
        self.__outCodingEdit.setToolTip(
            self.__settings.getDescription("CODING"))
        self.__outCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(codingLabel, 3, 0, 1, 1)
        gridLayout.addWidget(self.__outCodingEdit, 3, 1, 1, 1)
        self.__outCodingEdit.setFont(font)

        # Src coding comment
        srcCodingLabel = QLabel("File encoding\ncomment")
        self.__srcCodingEdit = QLineEdit()
        self.__srcCodingEdit.setText(self.__settings.settings["CODING_SPEC"])
        self.__srcCodingEdit.setToolTip(
            self.__settings.getDescription("CODING_SPEC"))
        self.__srcCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(srcCodingLabel, 3, 3, 1, 1)
        gridLayout.addWidget(self.__srcCodingEdit, 3, 4, 1, 1)
        self.__srcCodingEdit.setFont(font)

        layout.addLayout(gridLayout)

        # Boilerplate
        boilLabel = QLabel("Boilerplate  ")
        boilLabel.setAlignment(Qt.AlignTop)
        self.__boilEdit = QTextEdit()
        self.__boilEdit.setPlainText(self.__settings.settings["BOILERPLATE"])
        self.__boilEdit.setToolTip(
            self.__settings.getDescription("BOILERPLATE"))
        self.__boilEdit.setTabChangesFocus(True)
        self.__boilEdit.setAcceptRichText(False)
        self.__boilEdit.setFont(font)
        self.__boilEdit.textChanged.connect(self.__validate)
        boilLayout = QHBoxLayout()
        boilLayout.addWidget(boilLabel)
        boilLayout.addWidget(self.__boilEdit)
        layout.addLayout(boilLayout)

        # Now check boxes and radio buttons
        cbGridLayout = QGridLayout()
        self.__keepBlanks = QCheckBox("Keep blank lines")
        self.__keepBlanks.setChecked(
            self.__settings.settings["KEEP_BLANK_LINES"])
        self.__keepBlanks.setToolTip(
            self.__settings.getDescription("KEEP_BLANK_LINES"))
        cbGridLayout.addWidget(self.__keepBlanks, 0, 0, 1, 1)

        self.__addBlanks = QCheckBox("Add blank lines around comments")
        self.__addBlanks.setChecked(
            self.__settings.settings["ADD_BLANK_LINES_AROUND_COMMENTS"])
        self.__addBlanks.setToolTip(
            self.__settings.getDescription("ADD_BLANK_LINES_AROUND_COMMENTS"))
        cbGridLayout.addWidget(self.__addBlanks, 0, 2, 1, 1)

        self.__justifyDoc = QCheckBox("Left justify doc strings")
        self.__justifyDoc.setChecked(
            self.__settings.settings["LEFTJUST_DOC_STRINGS"])
        self.__justifyDoc.setToolTip(
            self.__settings.getDescription("LEFTJUST_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__justifyDoc, 1, 0, 1, 1)

        self.__wrapDoc = QCheckBox("Wrap long doc strings")
        self.__wrapDoc.setChecked(self.__settings.settings["WRAP_DOC_STRINGS"])
        self.__wrapDoc.setToolTip(
            self.__settings.getDescription("WRAP_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__wrapDoc, 1, 2, 1, 1)

        self.__recodeStrings = QCheckBox("Try to decode strings")
        self.__recodeStrings.setChecked(
            self.__settings.settings["RECODE_STRINGS"])
        self.__recodeStrings.setToolTip(
            self.__settings.getDescription("RECODE_STRINGS"))
        cbGridLayout.addWidget(self.__recodeStrings, 2, 0, 1, 1)

        self.__splitStrings = QCheckBox("Split long strings")
        self.__splitStrings.setChecked(
            self.__settings.settings["CAN_SPLIT_STRINGS"])
        self.__splitStrings.setToolTip(
            self.__settings.getDescription("CAN_SPLIT_STRINGS"))
        cbGridLayout.addWidget(self.__splitStrings, 2, 2, 1, 1)

        self.__keepUnassignedConst = QCheckBox("Keep unassigned constants")
        self.__keepUnassignedConst.setChecked(
            self.__settings.settings["KEEP_UNASSIGNED_CONSTANTS"])
        self.__keepUnassignedConst.setToolTip(
            self.__settings.getDescription("KEEP_UNASSIGNED_CONSTANTS"))
        cbGridLayout.addWidget(self.__keepUnassignedConst, 3, 0, 1, 1)

        self.__parenTuple = QCheckBox("Parenthesize tuple display")
        self.__parenTuple.setChecked(
            self.__settings.settings["PARENTHESIZE_TUPLE_DISPLAY"])
        self.__parenTuple.setToolTip(
            self.__settings.getDescription("PARENTHESIZE_TUPLE_DISPLAY"))
        cbGridLayout.addWidget(self.__parenTuple, 3, 2, 1, 1)

        self.__javaListDedent = QCheckBox("Java style list dedent")
        self.__javaListDedent.setChecked(
            self.__settings.settings["JAVA_STYLE_LIST_DEDENT"])
        self.__javaListDedent.setToolTip(
            self.__settings.getDescription("JAVA_STYLE_LIST_DEDENT"))
        cbGridLayout.addWidget(self.__javaListDedent, 4, 0, 1, 1)

        layout.addLayout(cbGridLayout)

        # Quotes radio buttons
        quotesGroupbox = QGroupBox("Quotes")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        quotesGroupbox.sizePolicy().hasHeightForWidth() )
        quotesGroupbox.setSizePolicy(sizePolicy)

        layoutQG = QVBoxLayout(quotesGroupbox)
        self.__use1RButton = QRadioButton(
            "Use apostrophes instead of quotes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use1RButton)
        self.__use2RButton = QRadioButton(
            "Use quotes instead of apostrophes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use2RButton)
        self.__useAsIsRButton = QRadioButton("Do not make changes",
                                             quotesGroupbox)
        layoutQG.addWidget(self.__useAsIsRButton)
        use1 = self.__settings.settings["SINGLE_QUOTED_STRINGS"]
        use2 = self.__settings.settings["DOUBLE_QUOTED_STRINGS"]
        if use1:
            self.__use1RButton.setChecked(True)
        elif use2:
            self.__use2RButton.setChecked(True)
        else:
            self.__useAsIsRButton.setChecked(True)
        layout.addWidget(quotesGroupbox)

        fontMetrics = QFontMetrics(font)
        editWidth = fontMetrics.width("iso8859-10  ") + 20
        self.__colsEdit.setFixedWidth(editWidth)
        self.__funcAssignEdit.setFixedWidth(editWidth)
        self.__sliceSepEdit.setFixedWidth(editWidth)
        self.__outCodingEdit.setFixedWidth(editWidth)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__resetButton = buttonBox.addButton("Reset to Default",
                                                 QDialogButtonBox.ActionRole)
        self.__resetButton.setToolTip(
            "Mostly as recommended by PEP 8 / PEP 308")
        self.__resetButton.clicked.connect(self.__reset)
        self.__tidyButton = buttonBox.addButton("Tidy",
                                                QDialogButtonBox.ActionRole)
        self.__tidyButton.setToolTip("Save settings and run PythonTidy")
        self.__tidyButton.setDefault(True)
        self.__tidyButton.clicked.connect(self.__saveAndAccept)
        layout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return
Пример #41
0
class PinMatrixWidget(QWidget):
    '''
        Displays widget with nine blank buttons and password box.
        Encodes button clicks into sequence of numbers for passing
        into PinAck messages of TREZOR.

        show_strength=True may be useful for entering new PIN
    '''
    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)

        if QT_VERSION_STR >= '5':
            self.password.textChanged.connect(self._password_changed)
        elif QT_VERSION_STR >= '4':
            QObject.connect(self.password, SIGNAL('textChanged(QString)'),
                            self._password_changed)
        else:
            raise RuntimeError('Unsupported Qt version')

        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)

    def _set_strength(self, strength):
        if strength < 3000:
            self.strength.setText('weak')
            self.strength.setStyleSheet("QLabel { color : #d00; }")
        elif strength < 60000:
            self.strength.setText('fine')
            self.strength.setStyleSheet("QLabel { color : #db0; }")
        elif strength < 360000:
            self.strength.setText('strong')
            self.strength.setStyleSheet("QLabel { color : #0a0; }")
        else:
            self.strength.setText('ULTIMATE')
            self.strength.setStyleSheet(
                "QLabel { color : #000; font-weight: bold;}")

    def _password_changed(self, password):
        self._set_strength(self.get_strength())

    def get_strength(self):
        digits = len(set(str(self.password.text())))
        strength = math.factorial(9) / math.factorial(9 - digits)
        return strength

    def get_value(self):
        return self.password.text()
Пример #42
0
 def setupUI(self, mainData):
     ####
     #Creation of supporting layouts
     baseLayout = QVBoxLayout()
     controlsLayout = QGridLayout() #This is everything except the buttons
     
     ####
     #Mode controls
     modeGrpBox = QGroupBox("Mode:")
     self.modeRadBtns = [QRadioButton("Live"),
                         QRadioButton("Offline")]
     for i in range(len(self.modeRadBtns)):
         self.modeRadBtns[i].setChecked(mainData.mode[i])
         self.modeRadBtns[i].clicked.connect(self.modeRadBtnClick)
     modeLayout = QHBoxLayout()
     self.addWidgetListToLayout(self.modeRadBtns, modeLayout)
     modeGrpBox.setLayout(modeLayout)
     controlsLayout.addWidget(modeGrpBox, 0, 0)
     
     ####
     #Calib controls
     calibLayout = QVBoxLayout()
     calibGrpBox = QGroupBox("Calibration Type:")
     self.calibRadBtns = [QRadioButton("Calibration"),
                          QRadioButton("Calibration F1"),
                          QRadioButton("Calibration F2")]
     for i in range(len(self.calibRadBtns)):
         self.calibRadBtns[i].clicked.connect(self.calibRadBtnClick)
         self.calibRadBtns[i].setChecked(mainData.calibType[i])
     calibGrpLayout = QVBoxLayout()
     self.addWidgetListToLayout(self.calibRadBtns, calibGrpLayout)
     calibGrpBox.setLayout(calibGrpLayout)
     calibLayout.addWidget(calibGrpBox)
     
     calibConfBtn = QPushButton("Configure Calibration...")
     calibConfBtn.clicked.connect(self.calibConfClick)
     calibLayout.addWidget(calibConfBtn)
     
     controlsLayout.addLayout(calibLayout, 1, 0, 3, 1)
     
     ####
     #Data location
     dataDirGrpBox = QGroupBox("Data directory:")
     self.dataDirTextBox = QLineEdit()
     self.dataDirTextBox.setText(str(mainData.dataDir))
     self.dataDirTextBox.textChanged.connect(self.dataDirPathChanged)
     self.browseDataDirBtn = QPushButton("Browse...")
     self.browseDataDirBtn.clicked.connect(self.dataDirBrowseBtnClick)
     
     dataDirLayout = QHBoxLayout()
     dataDirLayout.addWidget(self.dataDirTextBox)
     dataDirLayout.addWidget(self.browseDataDirBtn)
     dataDirGrpBox.setLayout(dataDirLayout)
     controlsLayout.addWidget(dataDirGrpBox, 0, 1, 1, 2)
     
     ####
     #US/DS selector
     fileGrpBox = QGroupBox("Spectrum data files (US/DS) :")
     self.prevUSDSPairBtn = QPushButton("<")
     self.prevUSDSPairBtn.setFixedWidth(40)
     self.prevUSDSPairBtn.clicked.connect(self.changeUSDSPairBtnClick)
     self.nextUSDSPairBtn = QPushButton(">")
     self.nextUSDSPairBtn.clicked.connect(self.changeUSDSPairBtnClick)
     self.nextUSDSPairBtn.setFixedWidth(40)
     self.usdsPairTextBoxes = []
     for i in range(2):
         self.usdsPairTextBoxes.append(QLineEdit())
         #Set initial values of USDS pair boxes.
         if mainData.usdsPair[i] == '':
             self.usdsPairTextBoxes[i].setText(mainData.usdsPair[i])
         else:
             self.usdsPairTextBoxes[i].setText(os.path.basename(mainData.usdsPair[i]))
         self.usdsPairTextBoxes[i].textChanged.connect(self.usdsPairTextChanged)
         self.usdsPairTextBoxes[i].setFixedWidth(100)
     
     fileLayout = QHBoxLayout()
     fileLayout.addWidget(self.prevUSDSPairBtn)
     fileLayout.addWidget(self.usdsPairTextBoxes[0])
     fileLayout.addWidget(self.usdsPairTextBoxes[1])
     fileLayout.addWidget(self.nextUSDSPairBtn)
     fileGrpBox.setLayout(fileLayout)
     controlsLayout.addWidget(fileGrpBox, 1, 1, 1, 2)
     
     ###
     #Integration range
     # - N.B. set text values before setting the textchanged slot
     integRangeGrpBox = QGroupBox("Integration Range:")
     integRangeLayout = QGridLayout()
     integrationTextInputWidth = 40
     integElemNames = ["Beginning:", "End:", "Window Size:"]
     integElemLabels = []
     integNmLabels = []
     self.integElemTextBoxes = []
     colNr, rowNr = 0, 0
     for i in range(len(integElemNames)):
         integElemLabels.append(QLabel(integElemNames[i]))
         self.integElemTextBoxes.append(QLineEdit())
         self.integElemTextBoxes[i].setFixedWidth(integrationTextInputWidth)
         self.integElemTextBoxes[i].setText(str(mainData.integrationConf[i]))
         self.integElemTextBoxes[i].textChanged.connect(self.integConfigChanged)
         integNmLabels.append(QLabel("nm"))
         
         colNr = i%2
         if colNr == 0:
             rowNr += 1
         integRangeLayout.addWidget(integElemLabels[i], rowNr, 3*colNr)
         integRangeLayout.addWidget(self.integElemTextBoxes[i], rowNr, (3*colNr)+1)
         integRangeLayout.addWidget(integNmLabels[i], rowNr, (3*colNr)+2)
     
     integRangeGrpBox.setLayout(integRangeLayout)
     controlsLayout.addWidget(integRangeGrpBox, 2, 1, 2, 2)
     
     ###
     #Calculation results
     planckTempLabel = QLabel("Average T(Planck):")
     self.planckTempValLabel = QLabel()
     self.planckTempValLabel.setFixedWidth(50)
     self.planckTempValLabel.setAlignment(QtCore.Qt.AlignRight)
     planckKLabel = QLabel("K")
     planckKLabel.setAlignment(QtCore.Qt.AlignLeft)
     dPlancKTempLabel = QLabel(u"\u0394 T(Planck):")
     self.dPlanckTempValLabel = QLabel()
     self.dPlanckTempValLabel.setFixedWidth(50)
     self.dPlanckTempValLabel.setAlignment(QtCore.Qt.AlignRight)
     dPlanckKLabel = QLabel("K")
     dPlanckKLabel.setAlignment(QtCore.Qt.AlignLeft)
     wienTempLabel = QLabel("Average T(Wien):")
     self.wienTempValLabel = QLabel()
     self.wienTempValLabel.setFixedWidth(50)
     self.wienTempValLabel.setAlignment(QtCore.Qt.AlignRight)
     wienKLabel = QLabel("K")
     wienKLabel.setAlignment(QtCore.Qt.AlignLeft)
     dWienTempLabel = QLabel(u"\u0394 T(Wien):")
     self.dWienTempValLabel = QLabel()
     self.dWienTempValLabel.setFixedWidth(50)
     self.dWienTempValLabel.setAlignment(QtCore.Qt.AlignRight)
     dWienKLabel = QLabel("K")
     dWienKLabel.setAlignment(QtCore.Qt.AlignLeft)
     self.updateTTextLabels()
     
     resultsLayout = QGridLayout()
     resultsLayout.addWidget(planckTempLabel, 0, 0)
     resultsLayout.addWidget(self.planckTempValLabel, 0, 1, alignment=QtCore.Qt.AlignRight)
     resultsLayout.addWidget(planckKLabel, 0, 2, alignment=QtCore.Qt.AlignLeft)
     resultsLayout.addWidget(dPlancKTempLabel, 1, 0)
     resultsLayout.addWidget(self.dPlanckTempValLabel, 1, 1, alignment=QtCore.Qt.AlignRight)
     resultsLayout.addWidget(dPlanckKLabel, 1, 2, alignment=QtCore.Qt.AlignLeft)
     resultsLayout.addWidget(wienTempLabel, 0, 3)
     resultsLayout.addWidget(self.wienTempValLabel, 0, 4, alignment=QtCore.Qt.AlignRight)
     resultsLayout.addWidget(wienKLabel, 0, 5, alignment=QtCore.Qt.AlignLeft)
     resultsLayout.addWidget(dWienTempLabel, 1, 3)
     resultsLayout.addWidget(self.dWienTempValLabel, 1, 4, alignment=QtCore.Qt.AlignRight)
     resultsLayout.addWidget(dWienKLabel, 1, 5, alignment=QtCore.Qt.AlignLeft)
     
     controlsLayout.addLayout(resultsLayout, 4, 0, 1, 3)
     
     ####
     #Control buttons
     self.runBtn = QPushButton('Run')
     self.runBtn.clicked.connect(self.runBtnClicked)
     self.stopBtn = QPushButton('Stop')
     self.stopBtn.clicked.connect(self.stopBtnClicked)
     quitBtn = QPushButton('Quit')
     quitBtn.clicked.connect(QtCore.QCoreApplication.instance().quit)#TODO Add control to kill plots properly
     
     buttonLayout = QHBoxLayout()
     buttonLayout.addWidget(self.runBtn)
     buttonLayout.addWidget(self.stopBtn)
     buttonLayout.addWidget(quitBtn)
     
     ####
     #Add the 1st tier layouts & set the base layout
     baseLayout.addLayout(controlsLayout)
     baseLayout.addLayout(buttonLayout)
     self.setLayout(baseLayout)
Пример #43
0
class MyMplToolbar(NavigationToolbar):
    """
    Custom Matplotlib Navigationtoolbar, derived (sublassed) from
    Navigationtoolbar with the following changes:
    - new icon set
    - new functions and icons grid, full view
    - removed buttons for configuring subplots and editing curves
    - added an x,y location widget and icon


    derived from http://www.python-forum.de/viewtopic.php?f=24&t=26437

    http://pydoc.net/Python/pyQPCR/0.7/pyQPCR.widgets.matplotlibWidget/  !!
    http://matplotlib.org/users/navigation_toolbar.html !!

    see also http://stackoverflow.com/questions/17711099/programmatically-change-matplotlib-toolbar-mode-in-qt4
             http://matplotlib-users.narkive.com/C8XwIXah/need-help-with-darren-dale-qt-example-of-extending-toolbar
             https://sukhbinder.wordpress.com/2013/12/16/simple-pyqt-and-matplotlib-example-with-zoompan/

    Changing the info:
    http://stackoverflow.com/questions/15876011/add-information-to-matplotlib-navigation-toolbar-status-bar
    """

    #    toolitems = (
    #        ('Home', 'Reset original view', 'home', 'home'),
    #        ('Back', 'Back to  previous view', 'action-undo', 'back'),
    #        ('Forward', 'Forward to next view', 'action-redo', 'forward'),
    #        (None, None, None, None),
    #        ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),
    #        ('Zoom', 'Zoom to rectangle', 'magnifying-glass', 'zoom'),
    #        (None, None, None, None),
    #        ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
    #        ('Save', 'Save the figure', 'file', 'save_figure'),
    #      )

    # subclass NavigationToolbar, passing through arguments:
    #def __init__(self, canvas, parent, coordinates=True):
    def __init__(self, *args, **kwargs):
        NavigationToolbar.__init__(self, *args, **kwargs)

#        QtWidgets.QToolBar.__init__(self, parent)

#    def _icon(self, name):
#        return QtGui.QIcon(os.path.join(self.basedir, name))
#
#------------------------------------------------------------------------------

    def _init_toolbar(self):
        #       Using the following path to the icons seems to fail in some cases, we
        #       rather rely on qrc files containing all icons
        #        iconDir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
        #           '..','images','icons', '')
        #        self.basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
        #           '..','images', 'icons', '')

        #---------------- Construct Toolbar using QRC icons ---------------------------

        # ENABLE:
        a = self.addAction(QtGui.QIcon(':/circle-check.svg'), 'Enable Plot',
                           self.enable_update)
        a.setToolTip('Enable plot update')
        a.setCheckable(True)
        a.setChecked(True)
        #        a.setEnabled(False)

        self.addSeparator()  #---------------------------------------------

        # HOME:
        self.a_ho = self.addAction(QtGui.QIcon(':/home.svg'), 'Home',
                                   self.home)
        self.a_ho.setToolTip('Reset original view')
        # BACK:
        self.a_ba = self.addAction(QtGui.QIcon(':/action-undo.svg'), 'Back',
                                   self.back)
        self.a_ba.setToolTip('Back to previous view')
        # FORWARD:
        self.a_fw = self.addAction(QtGui.QIcon(':/action-redo.svg'), 'Forward',
                                   self.forward)
        self.a_fw.setToolTip('Forward to next view')

        self.addSeparator()  #---------------------------------------------

        # PAN:
        self.a_pa = self.addAction(QtGui.QIcon(':/move.svg'), 'Pan', self.pan)
        self.a_pa.setToolTip(
            "Pan axes with left mouse button, zoom with right,\n"
            "pressing x / y / CTRL yields horizontal / vertical / diagonal constraints."
        )
        self._actions['pan'] = self.a_pa
        self.a_pa.setCheckable(True)

        # ZOOM RECTANGLE:
        self.a_zo = self.addAction(QtGui.QIcon(':/magnifying-glass.svg'),
                                   'Zoom', self.zoom)
        self.a_zo.setToolTip(
            "Zoom in / out to rectangle with left / right mouse button,\n"
            "pressing x / y / CTRL yields horizontal / vertical / diagonal constraints."
        )
        self._actions['zoom'] = self.a_zo
        self.a_zo.setCheckable(True)

        # FULL VIEW:
        self.a_fv = self.addAction(QtGui.QIcon(':/fullscreen-enter.svg'), \
            'Zoom full extent', self.parent.plt_full_view)
        self.a_fv.setToolTip('Zoom to full extent')

        # LOCK VIEW:
        self.a_lk = self.addAction(QtGui.QIcon(':/lock-locked.svg'), \
                                   'Lock zoom', self.toggle_lock_zoom)
        self.a_lk.setCheckable(True)
        self.a_lk.setChecked(False)
        self.a_lk.setToolTip('Lock current zoom setting')

        # --------------------------------------
        self.addSeparator()
        # --------------------------------------

        # GRID:
        self.a_gr = self.addAction(QtGui.QIcon(':/grid-four-up.svg'), 'Grid',
                                   self.toggle_grid)
        self.a_gr.setToolTip('Toggle Grid')
        self.a_gr.setCheckable(True)
        self.a_gr.setChecked(True)

        # REDRAW:
        self.a_rd = self.addAction(QtGui.QIcon(':/brush.svg'), 'Redraw',
                                   self.parent.redraw)
        self.a_rd.setToolTip('Redraw Plot')

        # SAVE:
        self.a_sv = self.addAction(QtGui.QIcon(':/file.svg'), 'Save',
                                   self.save_figure)
        self.a_sv.setToolTip('Save the figure')

        self.cb = None  #will be used for the clipboard
        self.temp_file = os.path.join(pyfda_lib.get_home_dir(), 'tempMPL.png')

        self.a_cb = self.addAction(QtGui.QIcon(':/camera-slr.svg'), 'Save',
                                   self.mpl2Clip)
        self.a_cb.setToolTip('Copy to clipboard')
        self.a_cb.setShortcut("Ctrl+C")

        # --------------------------------------
        self.addSeparator()
        # --------------------------------------

        if figureoptions is not None:
            self.a_op = self.addAction(QtGui.QIcon(':/cog.svg'), 'Customize',
                                       self.edit_parameters)
            self.a_op.setToolTip('Edit curves line and axes parameters')

        self.buttons = {}

        # Add the x,y location widget at the right side of the toolbar
        # The stretch factor is 1 which means any resizing of the toolbar
        # will resize this label instead of the buttons.
        if self.coordinates:
            self.locLabel = QLabel("", self)
            self.locLabel.setAlignment(QtCore.Qt.AlignRight
                                       | QtCore.Qt.AlignTop)
            self.locLabel.setSizePolicy(
                QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored))
            labelAction = self.addWidget(self.locLabel)
            labelAction.setVisible(True)

        # reference holder for subplots_adjust window
        self.adj_window = None

    if figureoptions is not None:

        def edit_parameters(self):
            allaxes = self.canvas.figure.get_axes()
            if len(allaxes) == 1:
                axes = allaxes[0]
            else:
                titles = []
                for axes in allaxes:
                    title = axes.get_title()
                    ylabel = axes.get_ylabel()
                    label = axes.get_label()
                    if title:
                        fmt = "%(title)s"
                        if ylabel:
                            fmt += ": %(ylabel)s"
                        fmt += " (%(axes_repr)s)"
                    elif ylabel:
                        fmt = "%(axes_repr)s (%(ylabel)s)"
                    elif label:
                        fmt = "%(axes_repr)s (%(label)s)"
                    else:
                        fmt = "%(axes_repr)s"
                    titles.append(fmt % dict(title=title,
                                             ylabel=ylabel,
                                             label=label,
                                             axes_repr=repr(axes)))
                item, ok = QInputDialog.getItem(self.parent, 'Customize',
                                                'Select axes:', titles, 0,
                                                False)
                if ok:
                    axes = allaxes[titles.index(six.text_type(item))]
                else:
                    return

            figureoptions.figure_edit(axes, self)

#    def mouse_move(self, event):
#        if not event.inaxes or not self._active:
#            if self._lastCursor != mplCursors.POINTER:
#                self.set_cursor(mplCursors.POINTER)
#                self._lastCursor = mplCursors.POINTER
#        else:
#            if self._active == 'ZOOM':
#                if self._lastCursor != mplCursors.SELECT_REGION:
#                    self.set_cursor(mplCursors.SELECT_REGION)
#                    self._lastCursor = mplCursors.SELECT_REGION
#                if self._xypress:
#                    x, y = event.x, event.y
#                    lastx, lasty, _, _, _, _ = self._xypress[0]
#                    self.draw_rubberband(event, x, y, lastx, lasty)
#            elif (self._active == 'PAN' and
#                  self._lastCursor != mplCursors.MOVE):
#                self.set_cursor(mplCursors.MOVE)
#
#                self._lastCursor = mplCursors.MOVE
#
#        if event.inaxes and event.inaxes.get_navigate():
#
#            try: s = event.inaxes.format_coord(event.xdata, event.ydata)
#            except ValueError: pass
#            except OverflowError: pass
#            else:
#                if len(self.mode):
#                    self.set_message('%s : %s' % (self.mode, s))
#                else:
#                    self.set_message(s)
#        else: self.set_message(self.mode)

#------------------------------------------------------------------------------

    def toggle_grid(self):
        """Toggle the grid and redraw the figure."""
        self.grid = not self.grid
        for ax in self.parent.fig.axes:
            ax.grid(self.grid)
        self.parent.pltCanv.draw()  # don't use self.parent.redraw()

#------------------------------------------------------------------------------

    def toggle_lock_zoom(self):
        """
        Toggle the lock zoom settings and save the plot limits in any case:
            when previously unlocked, settings need to be saved
            when previously locked, current settings can be saved without effect
        """
        self.parent.save_limits(
        )  # save limits in any case: when previously unlocked
        self.lock_zoom = not self.lock_zoom

#------------------------------------------------------------------------------

    def enable_update(self):
        """
        Toggle the enable button and setting and enable / disable all 
        buttons accordingly. 
        """
        self.enable_update = not self.enable_update
        self.a_gr.setEnabled(self.enable_update)
        self.a_ho.setEnabled(self.enable_update)
        self.a_ba.setEnabled(self.enable_update)
        self.a_fw.setEnabled(self.enable_update)
        self.a_pa.setEnabled(self.enable_update)
        self.a_zo.setEnabled(self.enable_update)
        self.a_fv.setEnabled(self.enable_update)
        self.a_rd.setEnabled(self.enable_update)
        self.a_sv.setEnabled(self.enable_update)
        self.a_cb.setEnabled(self.enable_update)
        self.a_op.setEnabled(self.enable_update)

#------------------------------------------------------------------------------

    def mpl2Clip(self):
        """
        Save current figure to temporary file and copy it to the clipboard.
        """
        try:
            self.canvas.figure.savefig(self.temp_file, dpi=300, type='png')
            #  savefig(fname, dpi=None, facecolor='w', edgecolor='w',
            #  orientation='portrait', papertype=None, format=None,
            #  transparent=False):
            temp_img = QtGui.QImage(self.temp_file)
            self.cb = QtGui.QApplication.clipboard()
            self.cb.setImage(temp_img)
        except:
            print('Error copying figure to clipboard')
            errorMsg = "Sorry: %s\n\n:%s\n" % (sys.exc_type, sys.exc_value)
            print(errorMsg)
Пример #44
0
class ControlFlowNavigationBar(QFrame):
    " Navigation bar at the top of the flow UI widget "

    STATE_OK_UTD = 0  # Parsed OK, control flow up to date
    STATE_OK_CHN = 1  # Parsed OK, control flow changed
    STATE_BROKEN_UTD = 2  # Parsed with errors, control flow up to date
    STATE_BROKEN_CHN = 3  # Parsed with errors, control flow changed
    STATE_UNKNOWN = 4

    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.__infoIcon = None
        self.__warningsIcon = None
        self.__layout = None
        self.__pathLabel = None
        self.__createLayout()
        self.__currentIconState = self.STATE_UNKNOWN
        return

    def __createLayout(self):
        " Creates the layout "
        self.setFixedHeight(24)
        self.__layout = QHBoxLayout(self)
        self.__layout.setMargin(0)
        self.__layout.setContentsMargins(0, 0, 0, 0)

        # Create info icon
        self.__infoIcon = QLabel()
        self.__infoIcon.setPixmap(getPixmap('cfunknown.png'))
        self.__layout.addWidget(self.__infoIcon)

        self.__warningsIcon = QLabel()
        self.__warningsIcon.setPixmap(getPixmap('cfwarning.png'))
        self.__layout.addWidget(self.__warningsIcon)

        self.clearWarnings()

        # Create the path label
        self.__pathLabel = QLabel(self)
        self.__pathLabel.setTextFormat(Qt.PlainText)
        self.__pathLabel.setAlignment(Qt.AlignLeft)
        self.__pathLabel.setWordWrap(False)
        self.__pathLabel.setFrameStyle(QFrame.StyledPanel)
        self.__pathLabel.setTextInteractionFlags(Qt.NoTextInteraction)
        self.__pathLabel.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        self.__layout.addWidget(self.__pathLabel)

        self.__spacer = QWidget()
        self.__spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.__spacer.setMinimumWidth(0)
        self.__layout.addWidget(self.__spacer)

        # Create the selection label
        self.__selectionLabel = QLabel(self)
        self.__selectionLabel.setTextFormat(Qt.PlainText)
        self.__selectionLabel.setAlignment(Qt.AlignCenter)
        self.__selectionLabel.setWordWrap(False)
        self.__selectionLabel.setFrameStyle(QFrame.StyledPanel)
        self.__selectionLabel.setTextInteractionFlags(Qt.NoTextInteraction)
        self.__selectionLabel.setSizePolicy(QSizePolicy.Fixed,
                                            QSizePolicy.Fixed)
        self.__selectionLabel.setMinimumWidth(40)
        self.__layout.addWidget(self.__selectionLabel)
        self.setSelectionLabel(0, None)
        return

    def clearWarnings(self):
        self.__warningsIcon.setVisible(False)
        self.__warningsIcon.setToolTip("")
        return

    def setWarnings(self, warnings):
        self.__warningsIcon.setToolTip("Control flow parser warnings:\n" +
                                       "\n".join(warnings))
        self.__warningsIcon.setVisible(True)
        return

    def clearErrors(self):
        self.__infoIcon.setToolTip("")
        return

    def setErrors(self, errors):
        self.__infoIcon.setToolTip("Control flow parser errors:\n" +
                                   "\n".join(errors))
        return

    def updateInfoIcon(self, state):
        " Updates the information icon "
        if state == self.__currentIconState:
            return

        if state == self.STATE_OK_UTD:
            self.__infoIcon.setPixmap(getPixmap('cfokutd.png'))
            self.__infoIcon.setToolTip("Control flow is up to date")
            self.__currentIconState = self.STATE_OK_UTD
        elif state == self.STATE_OK_CHN:
            self.__infoIcon.setPixmap(getPixmap('cfokchn.png'))
            self.__infoIcon.setToolTip(
                "Control flow is not up to date; will be updated on idle")
            self.__currentIconState = self.STATE_OK_CHN
        elif state == self.STATE_BROKEN_UTD:
            self.__infoIcon.setPixmap(getPixmap('cfbrokenutd.png'))
            self.__infoIcon.setToolTip(
                "Control flow might be invalid due to invalid python code")
            self.__currentIconState = self.STATE_BROKEN_UTD
        elif state == self.STATE_BROKEN_CHN:
            self.__infoIcon.setPixmap(getPixmap('cfbrokenchn.png'))
            self.__infoIcon.setToolTip(
                "Control flow might be invalid; will be updated on idle")
            self.__currentIconState = self.STATE_BROKEN_CHN
        else:
            # STATE_UNKNOWN
            self.__infoIcon.setPixmap(getPixmap('cfunknown.png'))
            self.__infoIcon.setToolTip("Control flow state is unknown")
            self.__currentIconState = self.STATE_UNKNOWN
        return

    def getCurrentState(self):
        return self.__currentIconState

    def setPath(self, txt):
        " Sets the path label content "
        self.__pathLabel.setText(txt)
        return

    def setPathVisible(self, on):
        self.__pathLabel.setVisible(on)
        self.__spacer.setVisible(not on)
        return

    def setSelectionLabel(self, text, tooltip):
        self.__selectionLabel.setText(str(text))
        if tooltip:
            self.__selectionLabel.setToolTip("Selected items:\n" +
                                             str(tooltip))
        else:
            self.__selectionLabel.setToolTip("Number of selected items")
        return

    def resizeEvent(self, event):
        " Editor has resized "
        QFrame.resizeEvent(self, event)
        return
Пример #45
0
class RefDlg(QDialog):
    """
    A dialog for adding new reference.
    """
    def __init__(self, mc, iw):
        """
        Constructor.

        :param mc: A reference to the main class.
        :type mc: object
        :param iw: A reference to the insert window.
        :type iw: QMainWindow
        """

        super(QDialog, self).__init__()

        self.mc = mc
        self.iw = iw

        self._setup_self()

    def _setup_self(self):
        """
        Sets up self.
        """

        self.setObjectName(u'RefDlg')

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.setWindowTitle(u'Add Reference')

        self.grid_lyt = QGridLayout(self)
        self.grid_lyt.setObjectName(u'grid_lyt')
        self.grid_lyt.setColumnMinimumWidth(1, 300)

        self._build_wdgs()

    def _build_wdgs(self):
        """
        Builds own widgets.
        """

        self.ttl_lbl = QLabel(self)
        self.ttl_lbl.setObjectName(u'ttl_lbl')
        self.ttl_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.ttl_lbl.setText(u'title')
        self.grid_lyt.addWidget(self.ttl_lbl, 0, 0, 1, 1)

        self.ttl_le = QLineEdit(self)
        self.ttl_le.setObjectName(u'ttl_le')
        self.grid_lyt.addWidget(self.ttl_le, 0, 1, 1, 1)

        self.au_lbl = QLabel(self)
        self.au_lbl.setObjectName(u'au_lbl')
        self.au_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.au_lbl.setText(u'author(s)')
        self.grid_lyt.addWidget(self.au_lbl, 1, 0, 1, 1)

        self.au_le = QLineEdit(self)
        self.au_le.setObjectName(u'au_le')
        self.grid_lyt.addWidget(self.au_le, 1, 1, 1, 1)

        self.yr_lbl = QLabel(self)
        self.yr_lbl.setObjectName(u'yr_lbl')
        self.yr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.yr_lbl.setText(u'year')
        self.grid_lyt.addWidget(self.yr_lbl, 2, 0, 1, 1)

        today_dt = QDate.currentDate()

        self.yr_mde = de.MtyDe(self)
        self.yr_mde.setObjectName(u'yr_mde')
        self.yr_mde.setDisplayFormat('yyyy')
        self.grid_lyt.addWidget(self.yr_mde, 2, 1, 1, 1)

        self.isbn_lbl = QLabel(self)
        self.isbn_lbl.setObjectName(u'isbn_lbl')
        self.isbn_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.isbn_lbl.setText(u'isbn')
        self.grid_lyt.addWidget(self.isbn_lbl, 3, 0, 1, 1)

        self.isbn_le = QLineEdit(self)
        self.isbn_le.setObjectName(u'isbn_le')
        self.grid_lyt.addWidget(self.isbn_le, 3, 1, 1, 1)

        self.issn_lbl = QLabel(self)
        self.issn_lbl.setObjectName(u'issn_lbl')
        self.issn_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.issn_lbl.setText(u'issn')
        self.grid_lyt.addWidget(self.issn_lbl, 4, 0, 1, 1)

        self.issn_le = QLineEdit(self)
        self.issn_le.setObjectName(u'issn_le')
        self.grid_lyt.addWidget(self.issn_le, 4, 1, 1, 1)

        self.tp_lbl = QLabel(self)
        self.tp_lbl.setObjectName(u'tp_lbl')
        self.tp_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.tp_lbl.setText(u'referenceType')
        self.grid_lyt.addWidget(self.tp_lbl, 5, 0, 1, 1)

        self.tp_cb = QComboBox(self)
        self.tp_cb.setObjectName(u'tp_cb')
        self.grid_lyt.addWidget(self.tp_cb, 5, 1, 1, 1)

        self.jrn_lbl = QLabel(self)
        self.jrn_lbl.setObjectName(u'jrn_lbl')
        self.jrn_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.jrn_lbl.setText(u'journalName')
        self.grid_lyt.addWidget(self.jrn_lbl, 6, 0, 1, 1)

        self.jrn_le = QLineEdit(self)
        self.jrn_le.setObjectName(u'jrn_le')
        self.grid_lyt.addWidget(self.jrn_le, 6, 1, 1, 1)

        self.vol_lbl = QLabel(self)
        self.vol_lbl.setObjectName(u'vol_lbl')
        self.vol_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.vol_lbl.setText(u'volume')
        self.grid_lyt.addWidget(self.vol_lbl, 7, 0, 1, 1)

        self.vol_le = QLineEdit(self)
        self.vol_le.setObjectName(u'vol_le')
        self.grid_lyt.addWidget(self.vol_le, 7, 1, 1, 1)

        self.pg_lbl = QLabel(self)
        self.pg_lbl.setObjectName(u'pg_lbl')
        self.pg_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.pg_lbl.setText(u'page')
        self.grid_lyt.addWidget(self.pg_lbl, 8, 0, 1, 1)

        self.pg_le = QLineEdit(self)
        self.pg_le.setObjectName(u'pg_le')
        self.grid_lyt.addWidget(self.pg_le, 8, 1, 1, 1)

        self.mand_wdgs = [self.ttl_le, self.au_le, self.yr_mde, self.tp_cb]

        self.iw.set_mand_wdgs(self.mand_wdgs)

        # temporary workaround
        self.vol_le.setValidator(vald.LenIntVald(self.vol_le, 1, 32767))

        self._fetch_ref_data()

        # to keep order
        self.input_wdgs = [
            self.ttl_le, self.au_le, self.yr_mde, self.isbn_le, self.issn_le,
            self.tp_cb, self.jrn_le, self.vol_le, self.pg_le
        ]

        self.btn_lyt = QHBoxLayout()
        self.grid_lyt.addLayout(self.btn_lyt, 9, 1, 1, 1)

        self.sv_btn = QPushButton(self)
        self.sv_btn.setObjectName(u'sv_btn')
        self.sv_btn.setText(u'Save')
        self.sv_btn.clicked.connect(self._save_ref)
        self.btn_lyt.addWidget(self.sv_btn)

        self.cl_btn = QPushButton(self)
        self.cl_btn.setObjectName(u'ok_btn')
        self.cl_btn.setText(u'Close')
        self.cl_btn.clicked.connect(self.close)
        self.btn_lyt.addWidget(self.cl_btn)

    def _fetch_ref_data(self):
        """
        Fetches data from the NOFA database and populates widgets.
        """

        ref_cb_dict = self._ref_cb_dict

        self.iw.pop_cb(ref_cb_dict)

    @property
    def _ref_cb_dict(self):
        """
        Returns a reference combo box dictionary.

        :returns:
         | A reference combo box dictionary:
         |    - key - combo_box_name
         |    - value - [<fill method>, [<arguments>], <default value>]
        :rtype: dict.
        """

        ref_cb_dict = {
            self.tp_cb: [db.get_reftp_list, [self.mc.con], self.iw.sel_str]
        }

        return ref_cb_dict

    def _save_ref(self):
        """
        Saves a reference into the database.
        """

        try:
            self.iw.chck_mand_wdgs(self.mand_wdgs, exc.MandNotFldExc)

            ref_list = self.iw.get_wdg_list(self.input_wdgs)

            # temporary fix
            ref_list[2] = ref_list[2].year

            id = db.ins_ref(self.mc.con, ref_list)

            db.ins_ref_log(self.mc.con, id, self.mc.con_info[self.mc.usr_str])

            self.iw.pop_ref_cb()
            self.iw.upd_ref(
                db.get_ref_str(ref_list[1], ref_list[0], ref_list[2], id))

            QMessageBox.information(self, u'Saved', u'Reference saved.')
        except exc.MandNotFldExc as e:
            e.wdg.setFocus()
            QMessageBox.warning(self, u'Mandatory Fields',
                                u'Fill/select all mandatory fields.')
Пример #46
0
    def __init__(self, parent=None, conflictCallback=None, *cbArgs):
        """conflictCallback is a optional method called when a shortcut is changed.
        
        cbArgs is optional arguments of the conflictCallback method.
        it should return the name of the potential conflict or a null value """

        super(ShortcutEditDialog, self).__init__(parent)
        self.conflictCallback = conflictCallback
        self.cbArgs = cbArgs
        self.setMinimumWidth(400)
        # create gui

        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)

        top = QHBoxLayout()
        top.setSpacing(4)
        p = self.toppixmap = QLabel()
        l = self.toplabel = QLabel()
        top.addWidget(p)
        top.addWidget(l, 1)
        layout.addLayout(top)
        grid = QGridLayout()
        grid.setSpacing(4)
        grid.setColumnStretch(1, 2)
        layout.addLayout(grid)

        self.buttonDefault = QRadioButton(
            self, toggled=self.slotButtonDefaultToggled)
        self.buttonNone = QRadioButton(self)
        self.lconflictDefault = QLabel('test')
        self.lconflictDefault.setStyleSheet("color : red;")
        self.lconflictDefault.setVisible(False)
        self.buttonCustom = QRadioButton(self)
        grid.addWidget(self.buttonDefault, 0, 0, 1, 2)
        grid.addWidget(self.lconflictDefault, 1, 0, 1, 2)
        grid.addWidget(self.buttonNone, 2, 0, 1, 2)
        grid.addWidget(self.buttonCustom, 3, 0, 1, 2)

        self.keybuttons = []
        self.keylabels = []
        self.conflictlabels = []
        for num in range(4):
            l = QLabel(self)
            l.setStyleSheet("margin-left: 2em;")
            l.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            b = KeySequenceWidget(self, num)
            b.keySequenceChanged.connect(self.slotKeySequenceChanged)
            l.setBuddy(b)
            self.keylabels.append(l)
            self.keybuttons.append(b)
            grid.addWidget(l, num + 4 + num, 0)
            grid.addWidget(b, num + 4 + num, 1)
            lconflict = QLabel()
            lconflict.setStyleSheet("color : red;")
            self.conflictlabels.append(lconflict)
            lconflict.setVisible(False)
            grid.addWidget(lconflict, num + 5 + num, 0, 1, 2, Qt.AlignHCenter)

        layout.addWidget(Separator(self))

        b = QDialogButtonBox(self)
        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout.addWidget(b)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        app.translateUI(self)
Пример #47
0
class ThumbnailWidget(QFrame):
    def __init__(self, parent, svg_data="", text=""):
        QFrame.__init__(self, parent)

        self.setFrameStyle(QFrame.StyledPanel)

        self.label = QLabel(text, self)
        self.label.setWordWrap(True)

        self.label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setAttribute(Qt.WA_TransparentForMouseEvents)

        self.svg = SVGThumbnailWidget(svg_data, parent=self)
        self.svg.setAttribute(Qt.WA_TransparentForMouseEvents)

        layout = QVBoxLayout()
        layout.addWidget(self.label, stretch=1, alignment=Qt.AlignCenter)
        layout.addWidget(self.svg, stretch=4, alignment=Qt.AlignCenter)

        self.setLayout(layout)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self._selected = False

    def setSelected(self, val):
        if self._selected != val:
            self._selected = val
            self.svg.setSelected(val)

    def getSelected(self):
        return self._selected

    selected = property(getSelected, setSelected)

    def setData(self, data):
        self.svg.setData(data)

    def setImageSize(self, width, height):
        self.svg.setFixedSize(width, height)

    def paintEvent(self, event):
        QFrame.paintEvent(self, event)

    def mousePressEvent(self, event):
        if event.button() & Qt.LeftButton:
            parent = self.parent()
            if event.modifiers() & Qt.ControlModifier:
                self.setSelected(not self._selected)
            else:
                for child in parent.findChildren(ThumbnailWidget):
                    child.setSelected(False)

                self.setSelected(True)

            parent.selectionChanged.emit()

        super(ThumbnailWidget, self).mousePressEvent(event)

    def mouseDoubleClickEvent(self, event):
        self._bigimage = BigSvgWidget()
        self._bigimage.load(QByteArray(self.svg._data))
        self._bigimage.show()

    def customEvent(self, event):
        self.layout().invalidate()
        self.update()
Пример #48
0
    def initGui(self):
        """
        Initialize the GUI.
        """
        self.resize(self._init_window_width, self._init_window_height)
        grid = QGridLayout(self)
        grid.setSpacing(10)

        ### Functions.
        group_func = QGroupBox(self)
        font = group_func.font()
        font.setPointSize(self._font_size_groupbox_title)
        group_func.setFont(font)
        group_func.resize(400, 100)
        grid_func = QGridLayout(group_func)
        grid_func.setSpacing(10)

        # Some buttons.
        self._is_bp = self.kwargs.get("bp", True)
        if self._is_bp:
            self.bp = QPushButton(group_func)
            self.bp.setText("Start plotting")
            self.bp.clicked.connect(self.pushButton)

        # Some options.
        label_logscale = QLabel(group_func)
        label_logscale.setText("Log")

        self.checkbox_logscale = QCheckBox(group_func)

        # Construct.
        if self._is_bp:
            grid_func.addWidget(self.bp, 0, 0, 1, 1)
        grid_func.addWidget(label_logscale, 0, 1)
        grid_func.addWidget(self.checkbox_logscale, 0, 2)

        ### Coordinate and Value of the mouse pointer.
        widget_coor_value = QWidget(self)
        widget_coor_value.resize(self._init_window_width, 30)
        grid_coor_value = QGridLayout(widget_coor_value)
        grid_coor_value.setSpacing(10)

        label_coor_value = QLabel(self)
        label_coor_value.setText("Coor, Value:")
        label_coor_value.setAlignment(Qt.AlignRight)
        # label_coor_value.setFixedWidth(120)
        font = label_coor_value.font()
        font.setPointSize(self._font_size_groupbox_title)
        font.setBold(True)
        label_coor_value.setFont(font)

        self.label_coor_value = QLabel(self)
        # self.label_coor_value.setFixedSize(200, 30)
        self.label_coor_value.setText("")
        font = self.label_coor_value.font()
        font.setPointSize(self._font_size_groupbox_title)
        font.setBold(True)
        self.label_coor_value.setFont(font)

        # Construct.
        grid_coor_value.addWidget(label_coor_value, 0, 0)
        grid_coor_value.addWidget(self.label_coor_value, 0, 1, 1, 3)

        ### Plotting area.
        self.initPlotArea()

        ### Construct the layout.
        grid.addWidget(group_func, 0, 0)
        grid.addWidget(self.glw, 1, 0)
        grid.addWidget(widget_coor_value, 1, 0)
Пример #49
0
class MainView(QWidget, AllViews):
    def __init__(self, parent=None):
        super(MainView, self).__init__(parent)
        self.setWindowTitle("Lucky")
        #self.SetWindowIcon(QtGui.QIcon('SomeLocalIcon.png'))
        
        self.alreadyUpdating = False
        
        self.presenter = MainPresenter()
        
        self.setupUI(self.presenter.dataModel)
        self.updateWidgetStates(self.presenter.dataModel)
        
    def setupUI(self, mainData):
        ####
        #Creation of supporting layouts
        baseLayout = QVBoxLayout()
        controlsLayout = QGridLayout() #This is everything except the buttons
        
        ####
        #Mode controls
        modeGrpBox = QGroupBox("Mode:")
        self.modeRadBtns = [QRadioButton("Live"),
                            QRadioButton("Offline")]
        for i in range(len(self.modeRadBtns)):
            self.modeRadBtns[i].setChecked(mainData.mode[i])
            self.modeRadBtns[i].clicked.connect(self.modeRadBtnClick)
        modeLayout = QHBoxLayout()
        self.addWidgetListToLayout(self.modeRadBtns, modeLayout)
        modeGrpBox.setLayout(modeLayout)
        controlsLayout.addWidget(modeGrpBox, 0, 0)
        
        ####
        #Calib controls
        calibLayout = QVBoxLayout()
        calibGrpBox = QGroupBox("Calibration Type:")
        self.calibRadBtns = [QRadioButton("Calibration"),
                             QRadioButton("Calibration F1"),
                             QRadioButton("Calibration F2")]
        for i in range(len(self.calibRadBtns)):
            self.calibRadBtns[i].clicked.connect(self.calibRadBtnClick)
            self.calibRadBtns[i].setChecked(mainData.calibType[i])
        calibGrpLayout = QVBoxLayout()
        self.addWidgetListToLayout(self.calibRadBtns, calibGrpLayout)
        calibGrpBox.setLayout(calibGrpLayout)
        calibLayout.addWidget(calibGrpBox)
        
        calibConfBtn = QPushButton("Configure Calibration...")
        calibConfBtn.clicked.connect(self.calibConfClick)
        calibLayout.addWidget(calibConfBtn)
        
        controlsLayout.addLayout(calibLayout, 1, 0, 3, 1)
        
        ####
        #Data location
        dataDirGrpBox = QGroupBox("Data directory:")
        self.dataDirTextBox = QLineEdit()
        self.dataDirTextBox.setText(str(mainData.dataDir))
        self.dataDirTextBox.textChanged.connect(self.dataDirPathChanged)
        self.browseDataDirBtn = QPushButton("Browse...")
        self.browseDataDirBtn.clicked.connect(self.dataDirBrowseBtnClick)
        
        dataDirLayout = QHBoxLayout()
        dataDirLayout.addWidget(self.dataDirTextBox)
        dataDirLayout.addWidget(self.browseDataDirBtn)
        dataDirGrpBox.setLayout(dataDirLayout)
        controlsLayout.addWidget(dataDirGrpBox, 0, 1, 1, 2)
        
        ####
        #US/DS selector
        fileGrpBox = QGroupBox("Spectrum data files (US/DS) :")
        self.prevUSDSPairBtn = QPushButton("<")
        self.prevUSDSPairBtn.setFixedWidth(40)
        self.prevUSDSPairBtn.clicked.connect(self.changeUSDSPairBtnClick)
        self.nextUSDSPairBtn = QPushButton(">")
        self.nextUSDSPairBtn.clicked.connect(self.changeUSDSPairBtnClick)
        self.nextUSDSPairBtn.setFixedWidth(40)
        self.usdsPairTextBoxes = []
        for i in range(2):
            self.usdsPairTextBoxes.append(QLineEdit())
            #Set initial values of USDS pair boxes.
            if mainData.usdsPair[i] == '':
                self.usdsPairTextBoxes[i].setText(mainData.usdsPair[i])
            else:
                self.usdsPairTextBoxes[i].setText(os.path.basename(mainData.usdsPair[i]))
            self.usdsPairTextBoxes[i].textChanged.connect(self.usdsPairTextChanged)
            self.usdsPairTextBoxes[i].setFixedWidth(100)
        
        fileLayout = QHBoxLayout()
        fileLayout.addWidget(self.prevUSDSPairBtn)
        fileLayout.addWidget(self.usdsPairTextBoxes[0])
        fileLayout.addWidget(self.usdsPairTextBoxes[1])
        fileLayout.addWidget(self.nextUSDSPairBtn)
        fileGrpBox.setLayout(fileLayout)
        controlsLayout.addWidget(fileGrpBox, 1, 1, 1, 2)
        
        ###
        #Integration range
        # - N.B. set text values before setting the textchanged slot
        integRangeGrpBox = QGroupBox("Integration Range:")
        integRangeLayout = QGridLayout()
        integrationTextInputWidth = 40
        integElemNames = ["Beginning:", "End:", "Window Size:"]
        integElemLabels = []
        integNmLabels = []
        self.integElemTextBoxes = []
        colNr, rowNr = 0, 0
        for i in range(len(integElemNames)):
            integElemLabels.append(QLabel(integElemNames[i]))
            self.integElemTextBoxes.append(QLineEdit())
            self.integElemTextBoxes[i].setFixedWidth(integrationTextInputWidth)
            self.integElemTextBoxes[i].setText(str(mainData.integrationConf[i]))
            self.integElemTextBoxes[i].textChanged.connect(self.integConfigChanged)
            integNmLabels.append(QLabel("nm"))
            
            colNr = i%2
            if colNr == 0:
                rowNr += 1
            integRangeLayout.addWidget(integElemLabels[i], rowNr, 3*colNr)
            integRangeLayout.addWidget(self.integElemTextBoxes[i], rowNr, (3*colNr)+1)
            integRangeLayout.addWidget(integNmLabels[i], rowNr, (3*colNr)+2)
        
        integRangeGrpBox.setLayout(integRangeLayout)
        controlsLayout.addWidget(integRangeGrpBox, 2, 1, 2, 2)
        
        ###
        #Calculation results
        planckTempLabel = QLabel("Average T(Planck):")
        self.planckTempValLabel = QLabel()
        self.planckTempValLabel.setFixedWidth(50)
        self.planckTempValLabel.setAlignment(QtCore.Qt.AlignRight)
        planckKLabel = QLabel("K")
        planckKLabel.setAlignment(QtCore.Qt.AlignLeft)
        dPlancKTempLabel = QLabel(u"\u0394 T(Planck):")
        self.dPlanckTempValLabel = QLabel()
        self.dPlanckTempValLabel.setFixedWidth(50)
        self.dPlanckTempValLabel.setAlignment(QtCore.Qt.AlignRight)
        dPlanckKLabel = QLabel("K")
        dPlanckKLabel.setAlignment(QtCore.Qt.AlignLeft)
        wienTempLabel = QLabel("Average T(Wien):")
        self.wienTempValLabel = QLabel()
        self.wienTempValLabel.setFixedWidth(50)
        self.wienTempValLabel.setAlignment(QtCore.Qt.AlignRight)
        wienKLabel = QLabel("K")
        wienKLabel.setAlignment(QtCore.Qt.AlignLeft)
        dWienTempLabel = QLabel(u"\u0394 T(Wien):")
        self.dWienTempValLabel = QLabel()
        self.dWienTempValLabel.setFixedWidth(50)
        self.dWienTempValLabel.setAlignment(QtCore.Qt.AlignRight)
        dWienKLabel = QLabel("K")
        dWienKLabel.setAlignment(QtCore.Qt.AlignLeft)
        self.updateTTextLabels()
        
        resultsLayout = QGridLayout()
        resultsLayout.addWidget(planckTempLabel, 0, 0)
        resultsLayout.addWidget(self.planckTempValLabel, 0, 1, alignment=QtCore.Qt.AlignRight)
        resultsLayout.addWidget(planckKLabel, 0, 2, alignment=QtCore.Qt.AlignLeft)
        resultsLayout.addWidget(dPlancKTempLabel, 1, 0)
        resultsLayout.addWidget(self.dPlanckTempValLabel, 1, 1, alignment=QtCore.Qt.AlignRight)
        resultsLayout.addWidget(dPlanckKLabel, 1, 2, alignment=QtCore.Qt.AlignLeft)
        resultsLayout.addWidget(wienTempLabel, 0, 3)
        resultsLayout.addWidget(self.wienTempValLabel, 0, 4, alignment=QtCore.Qt.AlignRight)
        resultsLayout.addWidget(wienKLabel, 0, 5, alignment=QtCore.Qt.AlignLeft)
        resultsLayout.addWidget(dWienTempLabel, 1, 3)
        resultsLayout.addWidget(self.dWienTempValLabel, 1, 4, alignment=QtCore.Qt.AlignRight)
        resultsLayout.addWidget(dWienKLabel, 1, 5, alignment=QtCore.Qt.AlignLeft)
        
        controlsLayout.addLayout(resultsLayout, 4, 0, 1, 3)
        
        ####
        #Control buttons
        self.runBtn = QPushButton('Run')
        self.runBtn.clicked.connect(self.runBtnClicked)
        self.stopBtn = QPushButton('Stop')
        self.stopBtn.clicked.connect(self.stopBtnClicked)
        quitBtn = QPushButton('Quit')
        quitBtn.clicked.connect(QtCore.QCoreApplication.instance().quit)#TODO Add control to kill plots properly
        
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.runBtn)
        buttonLayout.addWidget(self.stopBtn)
        buttonLayout.addWidget(quitBtn)
        
        ####
        #Add the 1st tier layouts & set the base layout
        baseLayout.addLayout(controlsLayout)
        baseLayout.addLayout(buttonLayout)
        self.setLayout(baseLayout)

###        
    def addWidgetListToLayout(self, widgetList, layout):
        for i in range(len(widgetList)):
            layout.addWidget(widgetList[i])
    
    def runBtnClicked(self):
        self.presenter.runTrigger()
        self.updateWidgetStates()
        self.updateTTextLabels()
    
    def stopBtnClicked(self):
        self.presenter.stopTrigger()
        self.updateWidgetStates()
    
    def getRadBtnStates(self, btnList):
        return tuple([int(radBtn.isChecked()) for radBtn in btnList])
            
    def modeRadBtnClick(self):
        self.presenter.setModeTrigger(self.getRadBtnStates(self.modeRadBtns))
        
        self.presenter.dataChangeTrigger()
        self.updateWidgetStates()
              
    def calibRadBtnClick(self):
        self.presenter.setCalibTypeTrigger(self.getRadBtnStates(self.calibRadBtns))
        
        self.presenter.dataChangeTrigger()
        self.updateWidgetStates()
        
    def calibConfClick(self):
        self.calibConfInput = CalibrationConfigView(self, self.presenter.dataModel.calibConfigData)
        self.calibConfInput.exec_()
        
        self.presenter.dataChangeTrigger()
        self.updateWidgetStates()
    
    def dataDirPathChanged(self):
        textBox = self.sender()
        if self.presenter.changeDataDirTrigger(textBox.text()):
            textBox.setStyleSheet("color: rgb(0, 0, 0);")
        else:
            textBox.setStyleSheet("color: rgb(255, 0, 0);")
        
        #If dataDir changes, US/DS files change too:
        for i in range(2):
            updatedPath = os.path.join(str(textBox.text()), os.path.basename(self.presenter.dataModel.usdsPair[i]))
            self.usdsPairTextBoxes[i].textChanged.emit(updatedPath)
        
        self.presenter.dataChangeTrigger()
        self.updateWidgetStates()
    
    def dataDirBrowseBtnClick(self):
        currDir = self.presenter.dataModel.dataDir
        newDir = self.showDirBrowserDialog(initDir=currDir, caption="Select a new data directory")
        if (newDir == None) or (newDir == ''):
            return
        else:
            self.dataDirTextBox.setText(newDir) #No need to fire an update as it happens automatically
    
    def changeUSDSPairBtnClick(self):
        btn = self.sender()
        if btn == self.prevUSDSPairBtn:
            self.presenter.changeUSDSPairTrigger(dec=True)
        elif btn == self.nextUSDSPairBtn:
            self.presenter.changeUSDSPairTrigger(inc=True)
        else:
            raise IllegalArgumentException(str(btn)+" unknown in this context")
        
        #TODO This is such an ugly hack
        dsFileName = os.path.split(self.presenter.dataModel.usdsPair[0])[1]
        usFileName = os.path.split(self.presenter.dataModel.usdsPair[1])[1]
        self.usdsPairTextBoxes[0].setText(usFileName)
        self.usdsPairTextBoxes[1].setText(dsFileName)
        
#         for i in range(2):
#             pathParts = os.path.split(self.presenter.dataModel.usdsPair[i])
#             self.usdsPairTextBoxes[i].setText(pathParts[1])
    
    def usdsPairTextChanged(self):
        textBox = self.sender()
        if textBox == self.usdsPairTextBoxes[0]:
            if self.presenter.changeUSDSPairTrigger(usFile=textBox.text()):
                textBox.setStyleSheet("color: rgb(0, 0, 0);")
            else:
                textBox.setStyleSheet("color: rgb(255, 0, 0);")
        elif textBox == self.usdsPairTextBoxes[1]:
            if self.presenter.changeUSDSPairTrigger(dsFile=textBox.text()):
                textBox.setStyleSheet("color: rgb(0, 0, 0);")
            else:
                textBox.setStyleSheet("color: rgb(255, 0, 0);")
        else:
            raise IllegalArgumentException(str(textBox)+" unknown in this context")
        
        prevState = self.presenter.dataModel.usdsPairGTE
        if self.presenter.dsLTEqualusFile():
            for i in range(2):
                self.usdsPairTextBoxes[i].setStyleSheet("color: rgb(255, 0, 0);")
        elif not prevState == self.presenter.dataModel.usdsPairGTE:
            for i in range(2):
                self.usdsPairTextBoxes[i].textChanged.emit(self.presenter.dataModel.usdsPair[i])
        
        self.presenter.dataChangeTrigger()
        self.updateWidgetStates()
    
    def integConfigChanged(self):
        textBox = self.sender()
        changeResult = self.presenter.changeIntegrationValueTrigger(textBox.text())
        
        if changeResult:
            integConfig = [integTextBox.text() for integTextBox in self.integElemTextBoxes]
            if self.presenter.changeIntegrationConfigTrigger(integConfig):
                styleSheetColour = "color: rgb(0, 0, 0);"
            else:
                styleSheetColour = "color: rgb(255, 0, 0);"
            [integTextBox.setStyleSheet(styleSheetColour) for integTextBox in self.integElemTextBoxes]
        else:
            if textBox.text() == '':
                textBox.setStyleSheet("color: rgb(0, 0, 0);")
                self.presenter.invalidateIntegration()
            else:
                textBox.setStyleSheet("color: rgb(255, 0, 0);")
                self.presenter.invalidateIntegration()
        
        self.presenter.dataChangeTrigger()
        self.updateWidgetStates()
        
    def updateTTextLabels(self):
        planckResults, wienResults = self.presenter.getTResults()
        
        if (planckResults[0] <= 0) and (planckResults[1] <=0):
            planckT = "-"
            dPlanckT = "-"
            wienT = "-"
            dWienT = "-"
        else:
            planckT = "{0:10.2f}".format(planckResults[2])
            dPlanckT = "{0:10.2f}".format(planckResults[3])
            wienT = "{0:10.2f}".format(wienResults[2])
            dWienT = "{0:10.2f}".format(wienResults[3])
        
        self.planckTempValLabel.setText(planckT)
        self.dPlanckTempValLabel.setText(dPlanckT)
        self.wienTempValLabel.setText(wienT)
        self.dWienTempValLabel.setText(dWienT)
        
###
    def updateWidgetStates(self, extraData=None):
        mainData = self.presenter.dataModel if (extraData == None) else extraData
        
        #Mode radio buttons
        for i in range(len(self.modeRadBtns)):
            self.modeRadBtns[i].setEnabled(mainData.allUIControlsEnabled)
        
        #Calibration type radio buttons
        for i in range(len(self.calibRadBtns)):
            self.calibRadBtns[i].setEnabled(mainData.allUIControlsEnabled)
        
        #Datadir
        self.browseDataDirBtn.setEnabled(mainData.allUIControlsEnabled)
        self.dataDirTextBox.setEnabled(mainData.allUIControlsEnabled)
        
        #US/DS pair
        self.prevUSDSPairBtn.setEnabled((mainData.allUIControlsEnabled) or (mainData.usdsControlsEnabled))
        self.nextUSDSPairBtn.setEnabled((mainData.allUIControlsEnabled) or (mainData.usdsControlsEnabled))
        for i in range(2):
            self.usdsPairTextBoxes[i].setEnabled((mainData.allUIControlsEnabled) and (mainData.usdsControlsEnabled)) 
        
        #Integration controls
        for textBox in self.integElemTextBoxes:
            textBox.setEnabled(mainData.allUIControlsEnabled)
        
        ###
        #Buttons
        self.runBtn.setEnabled(mainData.runEnabled)
        self.stopBtn.setEnabled(mainData.stopEnabled)
Пример #50
0
    def initGui(self):
        """
        Initialize the GUI.
        """
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.initMainWidget()
        self.setMenuBar()

        self.setWindowTitle("VMI Viewer")
        self.resize(self._init_window_width, self._init_window_height)

        ### RunInfo.
        group_runinfo = QGroupBox(self)
        group_runinfo.setTitle("RunInfo")
        font = group_runinfo.font()
        font.setPointSize(self._font_size_groupbox_title)
        group_runinfo.setFont(font)
        group_runinfo.resize(400, 100)
        grid_runinfo = QGridLayout(group_runinfo)

        # Run No.
        label_run = QLabel(self)
        label_run.setText("Run No. : ")
        label_run.setAlignment(Qt.AlignRight)
        font = label_run.font()
        font.setPointSize(self._font_size_label)
        font.setBold(self._font_bold_label)
        label_run.setFont(font)

        self.label_run_number = QLabel(self)
        self.label_run_number.setText("Unknown")
        pal = QPalette()
        pal.setColor(QPalette.Foreground, QColor("#0B5345"))
        self.label_run_number.setPalette(pal)
        font = self.label_run_number.font()
        font.setBold(True)
        font.setPointSize(self._font_size_label)
        self.label_run_number.setFont(font)

        # Tag No.
        label_tag = QLabel(self)
        label_tag.setText("Tag No. : ")
        label_tag.setAlignment(Qt.AlignRight)
        font = label_tag.font()
        font.setPointSize(self._font_size_label)
        font.setBold(self._font_bold_label)
        label_tag.setFont(font)

        self.label_tag_start = QLabel(self)
        self.label_tag_start.setText("None")
        font = self.label_tag_start.font()
        font.setBold(True)
        font.setPointSize(self._font_size_label)
        self.label_tag_start.setFont(font)

        label_tag_hyphen = QLabel(self)
        label_tag_hyphen.setText(" - ")
        label_tag_hyphen.setFixedWidth(30)
        font = label_tag_hyphen.font()
        font.setPointSize(self._font_size_label)
        font.setBold(self._font_bold_label)
        label_tag_hyphen.setFont(font)

        self.label_tag_end = QLabel(self)
        self.label_tag_end.setText("None")
        font = self.label_tag_end.font()
        font.setBold(True)
        font.setPointSize(self._font_size_label)
        self.label_tag_end.setFont(font)

        # Sig / BG.
        label_sig = QLabel(self)
        label_sig.setText("# of Sig : ")
        label_sig.setAlignment(Qt.AlignRight)
        font = label_sig.font()
        font.setPointSize(self._font_size_label)
        font.setBold(self._font_bold_label)
        label_sig.setFont(font)

        self.label_nbr_of_sig = QLabel(self)
        self.label_nbr_of_sig.setText("None")
        font = self.label_nbr_of_sig.font()
        font.setBold(True)
        font.setPointSize(self._font_size_label)
        self.label_nbr_of_sig.setFont(font)

        label_bg = QLabel(self)
        label_bg.setText("# of BG : ")
        label_bg.setAlignment(Qt.AlignRight)
        font = label_bg.font()
        font.setPointSize(self._font_size_label)
        font.setBold(self._font_bold_label)
        label_bg.setFont(font)

        self.label_nbr_of_bg = QLabel(self)
        self.label_nbr_of_bg.setText("None")
        font = self.label_nbr_of_bg.font()
        font.setBold(True)
        font.setPointSize(self._font_size_label)
        self.label_nbr_of_bg.setFont(font)

        # Construct the layout.
        grid_runinfo.addWidget(label_run, 0, 0)
        grid_runinfo.addWidget(self.label_run_number, 0, 1, 1, 3)

        grid_runinfo.addWidget(label_tag, 1, 0)
        grid_runinfo.addWidget(self.label_tag_start, 1, 1)
        grid_runinfo.addWidget(label_tag_hyphen, 1, 2)
        grid_runinfo.addWidget(self.label_tag_end, 1, 3)

        grid_runinfo.addWidget(label_sig, 2, 0)
        grid_runinfo.addWidget(self.label_nbr_of_sig, 2, 1)
        grid_runinfo.addWidget(label_bg, 2, 2)
        grid_runinfo.addWidget(self.label_nbr_of_bg, 2, 3)

        ### Settings.
        # group_settings = QGroupBox(self)
        # group_settings.setTitle("Settings")
        # font = group_settings.font()
        # font.setPointSize(self._font_size_groupbox_title)
        # group_settings.setFont(font)
        # group_settings.resize(400, 100)
        # grid_settings = QGridLayout(group_settings)

        # # Update interval.
        # label_upd_rate = QLabel(self)
        # label_upd_rate.setText("Upd. image interval: ")
        # font = label_upd_rate.font()
        # font.setPointSize(self._font_size_label)
        # font.setBold(self._font_bold_label)
        # label_upd_rate.setFont(font)

        # self.spinbox_upd_img_interval = QDoubleSpinBox(self)
        # self.spinbox_upd_img_interval.setValue(self._get_data_interval)
        # self.spinbox_upd_img_interval.setFixedWidth(100)
        # self.spinbox_upd_img_interval.setAlignment(Qt.AlignRight)
        # font = self.spinbox_upd_img_interval.font()
        # font.setBold(True)
        # font.setPointSize(self._font_size_label)
        # self.spinbox_upd_img_interval.setFont(font)

        # label_upd_rate_unit = QLabel(self)
        # label_upd_rate_unit.setText("sec")
        # font = label_upd_rate_unit.font()
        # font.setPointSize(self._font_size_label)
        # font.setBold(self._font_bold_label)
        # label_upd_rate_unit.setFont(font)

        # Construct the layout.
        # grid_settings.addWidget(label_upd_rate, 0, 0, 1, 3)
        # grid_settings.addWidget(self.spinbox_upd_img_interval, 0, 3)
        # grid_settings.addWidget(label_upd_rate_unit, 0, 4)

        ### Function buttons.
        group_func = QGroupBox(self)
        group_func.setTitle("Function")
        font = group_func.font()
        font.setPointSize(self._font_size_groupbox_title)
        group_func.setFont(font)
        group_func.resize(400, 100)
        grid_func = QGridLayout(group_func)
        grid_func.setSpacing(10)

        # Start/Stop main process button.
        self.brun = QPushButton(group_func)
        self.brun.setText("Start")
        font = self.brun.font()
        font.setPointSize(self._font_size_button)
        self.brun.setFont(font)
        self.brun.resize(400, 50)
        self.brun.setStyleSheet("background-color:{};".format(
            self._init_button_color))
        self.brun.clicked.connect(self.runMainProcess)

        # Clear data button.
        bclear = QPushButton(group_func)
        bclear.setText("Clear")
        font = bclear.font()
        font.setPointSize(self._font_size_button)
        bclear.setFont(font)
        bclear.resize(400, 50)
        bclear.setStyleSheet("background-color:{};".format(
            self._init_button_color))
        bclear.clicked.connect(self.clearData)

        # Save images button.
        bsave = QPushButton(group_func)
        bsave.setText("Save")
        font = bsave.font()
        font.setPointSize(self._font_size_button)
        bsave.setFont(font)
        bsave.resize(400, 50)
        bsave.setStyleSheet("background-color:{};".format(
            self._init_button_color))
        bsave.clicked.connect(self.saveData)

        # New window button.
        bwindow = QPushButton(group_func)
        bwindow.setText("Window")
        font = bwindow.font()
        font.setPointSize(self._font_size_button)
        bwindow.setFont(font)
        bwindow.resize(400, 50)
        bwindow.setStyleSheet("background-color:{};".format(
            self._init_button_color))
        bwindow.clicked.connect(self.showWindow)

        # Construct the layout of RunInfo groupbox.
        grid_func.addWidget(self.brun, 0, 0)
        grid_func.addWidget(bclear, 0, 1)
        grid_func.addWidget(bsave, 1, 0)
        grid_func.addWidget(bwindow, 1, 1)

        ### Plotting area.
        grp1 = QGroupBox(self)
        # grp1.setTitle("SIG WL")
        grp1.setTitle("SIG")
        font = grp1.font()
        font.setPointSize(self._font_size_groupbox_title)
        grp1.setFont(font)
        gp1 = QGridLayout(grp1)
        gp1.setSpacing(10)

        grp2 = QGroupBox(self)
        # grp2.setTitle("SIG WOL")
        grp2.setTitle("BG")
        font = grp2.font()
        font.setPointSize(self._font_size_groupbox_title)
        grp2.setFont(font)
        gp2 = QGridLayout(grp2)
        gp2.setSpacing(10)

        grp3 = QGroupBox(self)
        # grp3.setTitle("BG WL")
        grp3.setTitle("SIg - BG")
        font = grp3.font()
        font.setPointSize(self._font_size_groupbox_title)
        grp3.setFont(font)
        gp3 = QGridLayout(grp3)
        gp3.setSpacing(10)

        # grp4 = QGroupBox(self)
        # grp4.setTitle("BG WOL")
        # font = grp4.font()
        # font.setPointSize(self._font_size_groupbox_title)
        # grp4.setFont(font)
        # gp4 = QGridLayout(grp4)
        # gp4.setSpacing(10)

        kwargs = dict(px=False, py=False, ph=False, bp=False)
        self.pw1 = PlotWindow(self, **kwargs)
        self.pw2 = PlotWindow(self, **kwargs)
        self.pw3 = PlotWindow(self, **kwargs)
        # self.pw4 = PlotWindow(self, **kwargs)

        gp1.addWidget(self.pw1, 0, 0)
        gp2.addWidget(self.pw2, 0, 0)
        gp3.addWidget(self.pw3, 0, 0)
        # gp4.addWidget(self.pw4, 0, 0)

        ### Construct the layout.
        self.grid.addWidget(group_runinfo, 0, 0)
        # self.grid.addWidget(group_settings, 0, 1)
        self.grid.addWidget(group_func, 0, 1)
        self.grid.addWidget(grp1, 1, 0, 2, 1)
        self.grid.addWidget(grp2, 1, 1, 2, 1)
        self.grid.addWidget(grp3, 1, 2, 2, 1)
        # self.grid.addWidget(grp4, 1, 3, 2, 1)
        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)
Пример #51
0
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()
Пример #52
0
class CalcDlg(QDialog):
    def __init__(self, parent, point3d, startBearing, flagStr):
        QDialog.__init__(self, parent)
        self.parent0 = parent
        self.point = point3d
        self.flagStr = flagStr
        self.calcedPoint = None
        self.startBearing = startBearing
        # self.flagStrName = flagStr
        #         self.resize(326, 310)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setMargin(3)
        self.verticalLayout.setObjectName(("verticalLayout"))
        self.groupBox = QGroupBox(self)
        self.groupBox.setTitle((""))
        self.groupBox.setObjectName(("groupBox"))
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.verticalLayout_2.setSpacing(0)
        self.verticalLayout_2.setMargin(3)
        self.verticalLayout_2.setObjectName(("verticalLayout_2"))
        self.groupBox_5 = QGroupBox(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.groupBox_5.sizePolicy().hasHeightForWidth())
        self.groupBox_5.setSizePolicy(sizePolicy)
        font = QFont()
        font.setFamily(("Arial"))
        self.groupBox_5.setFont(font)
        self.groupBox_5.setObjectName(("groupBox_5"))
        self.horizontalLayout_19 = QHBoxLayout(self.groupBox_5)
        self.horizontalLayout_19.setSpacing(0)
        self.horizontalLayout_19.setMargin(0)
        self.horizontalLayout_19.setObjectName(("horizontalLayout_19"))
        self.groupBox_5.setVisible(False)

        self.frame_18 = QFrame(self.groupBox_5)
        self.frame_18.setFrameShape(QFrame.StyledPanel)
        self.frame_18.setFrameShadow(QFrame.Raised)
        self.frame_18.setObjectName(("frame_18"))
        self.verticalLayout_13 = QVBoxLayout(self.frame_18)
        self.verticalLayout_13.setSpacing(0)
        self.verticalLayout_13.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_13.setObjectName(("verticalLayout_13"))
        self.frame_19 = QFrame(self.frame_18)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_19.sizePolicy().hasHeightForWidth())
        self.frame_19.setSizePolicy(sizePolicy)
        self.frame_19.setFrameShape(QFrame.StyledPanel)
        self.frame_19.setFrameShadow(QFrame.Raised)
        self.frame_19.setObjectName(("frame_19"))
        self.horizontalLayout_20 = QHBoxLayout(self.frame_19)
        self.horizontalLayout_20.setSpacing(0)
        self.horizontalLayout_20.setMargin(0)
        self.horizontalLayout_20.setObjectName(("horizontalLayout_20"))
        self.label_9 = QLabel(self.frame_19)
        self.label_9.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_9.setFont(font)
        self.label_9.setObjectName(("label_9"))
        self.horizontalLayout_20.addWidget(self.label_9)
        self.txtTHR_X = QLineEdit(self.frame_19)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtTHR_X.sizePolicy().hasHeightForWidth())
        self.txtTHR_X.setSizePolicy(sizePolicy)
        self.txtTHR_X.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtTHR_X.setFont(font)
        self.txtTHR_X.setObjectName(("txtTHR_X"))
        self.horizontalLayout_20.addWidget(self.txtTHR_X)
        self.verticalLayout_13.addWidget(self.frame_19)
        self.frame_20 = QFrame(self.frame_18)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_20.sizePolicy().hasHeightForWidth())
        self.frame_20.setSizePolicy(sizePolicy)
        self.frame_20.setFrameShape(QFrame.StyledPanel)
        self.frame_20.setFrameShadow(QFrame.Raised)
        self.frame_20.setObjectName(("frame_20"))
        self.horizontalLayout_21 = QHBoxLayout(self.frame_20)
        self.horizontalLayout_21.setSpacing(0)
        self.horizontalLayout_21.setMargin(0)
        self.horizontalLayout_21.setObjectName(("horizontalLayout_21"))
        self.label_10 = QLabel(self.frame_20)
        self.label_10.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_10.setFont(font)
        self.label_10.setObjectName(("label_10"))
        self.horizontalLayout_21.addWidget(self.label_10)
        self.txtTHR_Y = QLineEdit(self.frame_20)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtTHR_Y.sizePolicy().hasHeightForWidth())
        self.txtTHR_Y.setSizePolicy(sizePolicy)
        self.txtTHR_Y.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtTHR_Y.setFont(font)
        self.txtTHR_Y.setObjectName(("txtTHR_Y"))
        self.horizontalLayout_21.addWidget(self.txtTHR_Y)
        self.verticalLayout_13.addWidget(self.frame_20)
        self.horizontalLayout_19.addWidget(self.frame_18)
        self.frame_21 = QFrame(self.groupBox_5)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_21.sizePolicy().hasHeightForWidth())
        self.frame_21.setSizePolicy(sizePolicy)
        self.frame_21.setMaximumSize(QSize(30, 70))
        self.frame_21.setFrameShape(QFrame.StyledPanel)
        self.frame_21.setFrameShadow(QFrame.Raised)
        self.frame_21.setObjectName(("frame_21"))
        self.verticalLayout_14 = QVBoxLayout(self.frame_21)
        self.verticalLayout_14.setSpacing(0)
        self.verticalLayout_14.setMargin(0)
        self.verticalLayout_14.setObjectName(("verticalLayout_14"))
        self.btnCaptureRunwayTHR = QToolButton(self.frame_21)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureRunwayTHR.sizePolicy().hasHeightForWidth())
        self.btnCaptureRunwayTHR.setSizePolicy(sizePolicy)
        self.btnCaptureRunwayTHR.setMaximumSize(QSize(16777215, 47))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")),
                       QIcon.Normal, QIcon.Off)
        self.btnCaptureRunwayTHR.setIcon(icon)
        self.btnCaptureRunwayTHR.setObjectName(("btnCaptureRunwayTHR"))
        self.verticalLayout_14.addWidget(self.btnCaptureRunwayTHR)
        #         self.btnToolTHR = QToolButton(self.frame_21)
        #         sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        #         sizePolicy.setHorizontalStretch(0)
        #         sizePolicy.setVerticalStretch(0)
        #         sizePolicy.setHeightForWidth(self.btnToolTHR.sizePolicy().hasHeightForWidth())
        #         self.btnToolTHR.setSizePolicy(sizePolicy)
        #         self.btnToolTHR.setMaximumSize(QSize(16777215, 20))
        #         icon1 = QIcon()
        #         icon1.addPixmap(QPixmap(("Resource/sort2.png")), QIcon.Normal, QIcon.Off)
        #         self.btnToolTHR.setIcon(icon1)
        #         self.btnToolTHR.setObjectName(("btnToolTHR"))
        #         self.verticalLayout_14.addWidget(self.btnToolTHR)
        self.horizontalLayout_19.addWidget(self.frame_21)
        self.verticalLayout_2.addWidget(self.groupBox_5)
        self.groupBox_4 = QGroupBox(self.groupBox)
        self.groupBox_4.setVisible(False)
        # self.groupBox.setVisible(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.groupBox_4.sizePolicy().hasHeightForWidth())
        self.groupBox_4.setSizePolicy(sizePolicy)
        font = QFont()
        font.setFamily(("Arial"))
        self.groupBox_4.setFont(font)
        self.groupBox_4.setObjectName(("groupBox_4"))
        self.horizontalLayout_16 = QHBoxLayout(self.groupBox_4)
        self.horizontalLayout_16.setSpacing(0)
        self.horizontalLayout_16.setMargin(0)
        self.horizontalLayout_16.setObjectName(("horizontalLayout_16"))
        self.frame_14 = QFrame(self.groupBox_4)
        self.frame_14.setFrameShape(QFrame.StyledPanel)
        self.frame_14.setFrameShadow(QFrame.Raised)
        self.frame_14.setObjectName(("frame_14"))
        self.verticalLayout_11 = QVBoxLayout(self.frame_14)
        self.verticalLayout_11.setSpacing(0)
        self.verticalLayout_11.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_11.setObjectName(("verticalLayout_11"))
        self.frame_15 = QFrame(self.frame_14)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_15.sizePolicy().hasHeightForWidth())
        self.frame_15.setSizePolicy(sizePolicy)
        self.frame_15.setFrameShape(QFrame.StyledPanel)
        self.frame_15.setFrameShadow(QFrame.Raised)
        self.frame_15.setObjectName(("frame_15"))
        self.horizontalLayout_17 = QHBoxLayout(self.frame_15)
        self.horizontalLayout_17.setSpacing(0)
        self.horizontalLayout_17.setMargin(0)
        self.horizontalLayout_17.setObjectName(("horizontalLayout_17"))
        self.label_7 = QLabel(self.frame_15)
        self.label_7.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_7.setFont(font)
        self.label_7.setObjectName(("label_7"))
        self.horizontalLayout_17.addWidget(self.label_7)
        self.txtEND_X = QLineEdit(self.frame_15)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtEND_X.sizePolicy().hasHeightForWidth())
        self.txtEND_X.setSizePolicy(sizePolicy)
        self.txtEND_X.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtEND_X.setFont(font)
        self.txtEND_X.setObjectName(("txtEND_X"))
        self.horizontalLayout_17.addWidget(self.txtEND_X)
        self.verticalLayout_11.addWidget(self.frame_15)
        self.frame_16 = QFrame(self.frame_14)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_16.sizePolicy().hasHeightForWidth())
        self.frame_16.setSizePolicy(sizePolicy)
        self.frame_16.setFrameShape(QFrame.StyledPanel)
        self.frame_16.setFrameShadow(QFrame.Raised)
        self.frame_16.setObjectName(("frame_16"))
        self.horizontalLayout_18 = QHBoxLayout(self.frame_16)
        self.horizontalLayout_18.setSpacing(0)
        self.horizontalLayout_18.setMargin(0)
        self.horizontalLayout_18.setObjectName(("horizontalLayout_18"))
        self.label_8 = QLabel(self.frame_16)
        self.label_8.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_8.setFont(font)
        self.label_8.setObjectName(("label_8"))
        self.horizontalLayout_18.addWidget(self.label_8)
        self.txtEND_Y = QLineEdit(self.frame_16)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtEND_Y.sizePolicy().hasHeightForWidth())
        self.txtEND_Y.setSizePolicy(sizePolicy)
        self.txtEND_Y.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtEND_Y.setFont(font)
        self.txtEND_Y.setObjectName(("txtEND_Y"))
        self.horizontalLayout_18.addWidget(self.txtEND_Y)
        self.verticalLayout_11.addWidget(self.frame_16)
        self.horizontalLayout_16.addWidget(self.frame_14)
        self.frame_17 = QFrame(self.groupBox_4)
        self.frame_17.setMaximumSize(QSize(30, 16777215))
        self.frame_17.setFrameShape(QFrame.StyledPanel)
        self.frame_17.setFrameShadow(QFrame.Raised)
        self.frame_17.setObjectName(("frame_17"))
        self.verticalLayout_12 = QVBoxLayout(self.frame_17)
        self.verticalLayout_12.setSpacing(0)
        self.verticalLayout_12.setMargin(0)
        self.verticalLayout_12.setObjectName(("verticalLayout_12"))
        self.btnCaptureRunwayEND = QToolButton(self.frame_17)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureRunwayEND.sizePolicy().hasHeightForWidth())
        self.btnCaptureRunwayEND.setSizePolicy(sizePolicy)
        self.btnCaptureRunwayEND.setMaximumSize(QSize(16777215, 47))
        self.btnCaptureRunwayEND.setIcon(icon)
        self.btnCaptureRunwayEND.setObjectName(("btnCaptureRunwayEND"))
        self.verticalLayout_12.addWidget(self.btnCaptureRunwayEND)
        #         self.btnToolEND = QToolButton(self.frame_17)
        #         sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        #         sizePolicy.setHorizontalStretch(0)
        #         sizePolicy.setVerticalStretch(0)
        #         sizePolicy.setHeightForWidth(self.btnToolEND.sizePolicy().hasHeightForWidth())
        #         self.btnToolEND.setSizePolicy(sizePolicy)
        #         self.btnToolEND.setMaximumSize(QSize(16777215, 20))
        #         self.btnToolEND.setIcon(icon1)
        #         self.btnToolEND.setObjectName(("btnToolEND"))
        #         self.verticalLayout_12.addWidget(self.btnToolEND)
        self.horizontalLayout_16.addWidget(self.frame_17)
        self.verticalLayout_2.addWidget(self.groupBox_4)
        self.lbl1 = QLabel(self.groupBox)
        font = QFont()
        font.setFamily(("Arial"))
        self.lbl1.setFont(font)
        self.lbl1.setText((""))
        self.lbl1.setAlignment(Qt.AlignCenter)
        self.lbl1.setWordWrap(False)
        self.lbl1.setMargin(0)
        self.lbl1.setObjectName(("lbl1"))
        self.verticalLayout_2.addWidget(self.lbl1)
        self.lbl2 = QLabel(self.groupBox)
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lbl2.setFont(font)
        self.lbl2.setText((""))
        self.lbl2.setAlignment(Qt.AlignCenter)
        self.lbl2.setObjectName(("lbl2"))
        self.verticalLayout_2.addWidget(self.lbl2)
        self.frame_22 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_22.sizePolicy().hasHeightForWidth())
        self.frame_22.setSizePolicy(sizePolicy)
        self.frame_22.setFrameShape(QFrame.StyledPanel)
        self.frame_22.setFrameShadow(QFrame.Raised)
        self.frame_22.setObjectName(("frame_22"))
        self.horizontalLayout_22 = QHBoxLayout(self.frame_22)
        self.horizontalLayout_22.setSpacing(0)
        self.horizontalLayout_22.setMargin(0)
        self.horizontalLayout_22.setObjectName(("horizontalLayout_22"))
        self.label_11 = QLabel(self.frame_22)
        self.label_11.setMinimumSize(QSize(170, 0))
        self.label_11.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_11.setFont(font)
        self.label_11.setObjectName(("label_11"))
        self.horizontalLayout_22.addWidget(self.label_11)
        self.txtForm = QLineEdit(self.frame_22)
        self.txtForm.setEnabled(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtForm.sizePolicy().hasHeightForWidth())
        self.txtForm.setSizePolicy(sizePolicy)
        self.txtForm.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtForm.setFont(font)
        self.txtForm.setObjectName(("txtForm"))
        self.horizontalLayout_22.addWidget(self.txtForm)
        self.verticalLayout_2.addWidget(self.frame_22)
        self.frame_23 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_23.sizePolicy().hasHeightForWidth())
        self.frame_23.setSizePolicy(sizePolicy)
        self.frame_23.setFrameShape(QFrame.StyledPanel)
        self.frame_23.setFrameShadow(QFrame.Raised)
        self.frame_23.setObjectName(("frame_23"))
        self.horizontalLayout_23 = QHBoxLayout(self.frame_23)
        self.horizontalLayout_23.setSpacing(0)
        self.horizontalLayout_23.setMargin(0)
        self.horizontalLayout_23.setObjectName(("horizontalLayout_23"))
        self.label_12 = QLabel(self.frame_23)
        self.label_12.setMinimumSize(QSize(170, 0))
        self.label_12.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_12.setFont(font)
        self.label_12.setObjectName(("label_12"))
        self.horizontalLayout_23.addWidget(self.label_12)
        self.txtBearing = QLineEdit(self.frame_23)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtBearing.sizePolicy().hasHeightForWidth())
        self.txtBearing.setSizePolicy(sizePolicy)
        self.txtBearing.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtBearing.setFont(font)
        self.txtBearing.setObjectName(("txtBearing"))
        self.horizontalLayout_23.addWidget(self.txtBearing)
        self.btnCaptureBearing = QToolButton(self.frame_23)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureBearing.sizePolicy().hasHeightForWidth())
        self.btnCaptureBearing.setSizePolicy(sizePolicy)
        self.btnCaptureBearing.setMaximumSize(QSize(16777215, 25))
        self.btnCaptureBearing.setStyleSheet((""))
        self.btnCaptureBearing.setIcon(icon)
        self.btnCaptureBearing.setObjectName(("btnCaptureBearing"))
        self.horizontalLayout_23.addWidget(self.btnCaptureBearing)
        self.verticalLayout_2.addWidget(self.frame_23)
        self.frame_24 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_24.sizePolicy().hasHeightForWidth())
        self.frame_24.setSizePolicy(sizePolicy)
        self.frame_24.setFrameShape(QFrame.StyledPanel)
        self.frame_24.setFrameShadow(QFrame.Raised)
        self.frame_24.setObjectName(("frame_24"))
        self.horizontalLayout_24 = QHBoxLayout(self.frame_24)
        self.horizontalLayout_24.setSpacing(0)
        self.horizontalLayout_24.setMargin(0)
        self.horizontalLayout_24.setObjectName(("horizontalLayout_24"))
        self.lblDistance = QLabel(self.frame_24)
        self.lblDistance.setMinimumSize(QSize(170, 0))
        self.lblDistance.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lblDistance.setFont(font)
        self.lblDistance.setObjectName(("lblDistance"))
        self.horizontalLayout_24.addWidget(self.lblDistance)
        self.txtDistance = QLineEdit(self.frame_24)
        self.txtDistance.setEnabled(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtDistance.sizePolicy().hasHeightForWidth())
        self.txtDistance.setSizePolicy(sizePolicy)
        self.txtDistance.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtDistance.setFont(font)
        self.txtDistance.setObjectName(("txtDistance"))
        self.horizontalLayout_24.addWidget(self.txtDistance)
        self.btnCaptureDistance = QToolButton(self.frame_24)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureDistance.sizePolicy().hasHeightForWidth())
        self.btnCaptureDistance.setSizePolicy(sizePolicy)
        self.btnCaptureDistance.setMaximumSize(QSize(16777215, 23))
        self.btnCaptureDistance.setStyleSheet((""))
        self.btnCaptureDistance.setIcon(icon)
        self.btnCaptureDistance.setObjectName(("btnCaptureDistance"))
        self.horizontalLayout_24.addWidget(self.btnCaptureDistance)
        self.verticalLayout_2.addWidget(self.frame_24)
        self.verticalLayout.addWidget(self.groupBox)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(("buttonBox"))
        self.verticalLayout.addWidget(self.buttonBox)
        self.btnCaptureDistance.clicked.connect(self.method_9)
        self.btnCaptureBearing.clicked.connect(self.method_8)
        self.txtEND_X.textChanged.connect(self.method_4)
        self.txtEND_Y.textChanged.connect(self.method_4)
        self.txtTHR_X.textChanged.connect(self.method_4)
        self.txtTHR_Y.textChanged.connect(self.method_4)
        # self.type = rnavType
        # self.category = category
        # self.resultPosionList = position_List
        self.MinBearing2 = 0
        self.MaxBearing2 = 0
        self.waypoint = None
        self.distanceMeasureTool = MeasureTool(define._canvas,
                                               self.txtDistance,
                                               DistanceUnits.NM)
        self.bearingTool = CaptureBearingTool(define._canvas, self.txtBearing)
        self.CaptureTHRCoordTool = CaptureCoordinateTool(
            define._canvas, self.txtTHR_X, self.txtTHR_Y)
        self.CaptureTHRCoordTool.rubberBandClick.setColor(Qt.green)
        self.CaptureENDCoordTool = CaptureCoordinateTool(
            define._canvas, self.txtEND_X, self.txtEND_Y)
        self.CaptureENDCoordTool.rubberBandClick.setColor(Qt.blue)
        #         if rnavType == RnavCommonWaypoint.FAWP or rnavType == RnavCommonWaypoint.MAWP:
        #             self.from1 = position_0
        #
        #             self.resize(326, 310)
        #             if position_List[0] != None:
        #                 self.setThrPosition(position_List[0].x(),position_List[0].y())
        #                 self.CaptureTHRCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[0].x(),position_List[0].y()))
        # #                 self.CaptureTHRCoordTool.rubberBandClick.show()
        #             if position_List[1] != None:
        #                 self.setEndPosition(position_List[1].x(),position_List[1].y())
        #                 self.CaptureENDCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[1].x(),position_List[1].y()))
        # #             self.setWaypoint(position_List[2])
        #         else:
        #             self.from1 = position_1
        #             num = RnavWaypoints.smethod_0(position_0, position_1)
        #             self.MinBearing = RnavWaypoints.smethod_7(rnavType, category, num)
        #             self.MaxBearing= RnavWaypoints.smethod_8(rnavType, category, num)
        #             self.MinDistance = RnavWaypoints.smethod_4(rnavType, category)
        #             if flagStr == "Y-Bar":
        #                 if (rnavType == RnavCommonWaypoint.IAWP1):
        #                     self.setBearing(self.MaxBearing)
        #                 elif (rnavType != RnavCommonWaypoint.IAWP3):
        #                     self.setBearing(num)
        #                 else:
        #                     self.setBearing(self.MinBearing)
        #             else:
        #                 if (rnavType == RnavCommonWaypoint.IAWP1):
        #                     self.setBearing(self.MinBearing)
        #                 elif (rnavType != RnavCommonWaypoint.IAWP3):
        #                     self.setBearing(num)
        #                 else:
        #                     self.setBearing(self.MaxBearing)
        # #             if self.txtDistance.isEnabled():
        # #             self.setDistance(RnavWaypoints.smethod_6(rnavType, category).NauticalMiles)
        # #             self.setWaypoint(position_List.pop(0))
        #         self.method_4()
        self.retranslateUi()
        QObject.connect(self.buttonBox, SIGNAL(("accepted()")),
                        self.btnCalculate_Click)
        QObject.connect(self.buttonBox, SIGNAL(("rejected()")), self.reject)
        #         QMetaObject.connectSlotsByName(Dialog)

        #         self.btnToolEND.clicked.connect(self.removeEnd)
        #         self.btnToolTHR.clicked.connect(self.removeThr)
        self.btnCaptureRunwayTHR.clicked.connect(self.captureTHR)
        self.btnCaptureRunwayEND.clicked.connect(self.captureEND)

        self.txtDistance.setText("10")

    def retranslateUi(self):
        self.setWindowTitle("CaculaterDlg")
        self.groupBox_5.setTitle("Runway THR")
        self.label_9.setText("X:")
        self.label_10.setText("Y:")
        self.btnCaptureRunwayTHR.setText("...")
        #         self.btnToolTHR.setText("...")
        self.groupBox_4.setTitle("Runway END")
        self.label_7.setText("X:")
        self.label_8.setText("Y:")
        self.btnCaptureRunwayEND.setText("...")
        #         self.btnToolEND.setText("...")
        self.label_11.setText("From:")
        self.txtForm.setText("FAWP")
        self.label_12.setText(unicode("Bearing (°) :", "utf-8"))
        #         self.txtBearing.setText("188.25")
        self.btnCaptureBearing.setText("...")
        self.lblDistance.setText("Distance (nm):")
        self.txtDistance.setText("5")
        self.btnCaptureDistance.setText("...")

    def captureTHR(self):
        define._canvas.setMapTool(self.CaptureTHRCoordTool)

    def captureEND(self):
        define._canvas.setMapTool(self.CaptureENDCoordTool)

    def close(self):
        scene = define._canvas.scene()
        scene.removeItem(self.CaptureTHRCoordTool.rubberBandClick)
        scene.removeItem(self.CaptureENDCoordTool.rubberBandClick)
        scene.removeItem(self.bearingTool.rubberBand)
        scene.removeItem(self.distanceMeasureTool.rubberBand)
        #         self.CaptureTHRCoordTool.rubberBand.hide()
        #         self.CaptureENDCoordTool.rubberBand.hide()
        define._canvas.setMapTool(QgsMapToolPan(define._canvas))
#         self.reject()

    def reject(self):
        self.close()
        QDialog.reject(self)

    def getThrPoint3D(self):
        if self.txtTHR_X.text() != "" and self.txtTHR_Y.text() != "":
            try:
                x = float(self.txtTHR_X.text())
            except ValueError:
                x = 0
            try:
                y = float(self.txtTHR_Y.text())
            except ValueError:
                y = 0
            return Point3D(x, y, 0)
        else:
            return None

    def getEndPoint3D(self):
        if self.txtEND_X.text() != "" and self.txtEND_Y.text() != "":
            try:
                x = float(self.txtEND_X.text())
            except ValueError:
                x = 0
            try:
                y = float(self.txtEND_Y.text())
            except ValueError:
                y = 0
            return Point3D(x, y, 0)
        else:
            return None

    def setEndPosition(self, x, y):
        self.txtEND_X.setText(str(x))
        self.txtEND_Y.setText(str(y))

    def setThrPosition(self, x, y):
        self.txtTHR_X.setText(str(x))
        self.txtTHR_Y.setText(str(y))

    def getWaypoint(self):
        if (self.type == RnavCommonWaypoint.FAWP):
            nauticalMiles = float(self.txtDistance.text())
            value = float(self.txtBearing.text())
            num1 = math.fabs(self.rethr - value)
            if (num1 > 180):
                num1 = 360 - num1
            num2 = math.sin(Unit.smethod_0(num1)) * 0.7559395
            num3 = Unit.smethod_1(math.asin(num2 / nauticalMiles))
            num4 = math.cos(Unit.smethod_0(num1)) * 0.755939525
            num5 = math.cos(Unit.smethod_0(num3)) * nauticalMiles
            return RnavWaypoints.smethod_3(
                self.pos1400m, float(self.txtBearing.text()),
                Distance(math.fabs(num5 - num4), DistanceUnits.NM))
        if (self.type != RnavCommonWaypoint.MAWP):
            return RnavWaypoints.smethod_3(
                self.from1, float(self.txtBearing.text()),
                Distance(float(self.txtDistance.text()), DistanceUnits.NM))
        if (float(self.txtBearing.text()) > self.thrre
                or float(self.txtBearing.text()) - self.thrre >= 90):

            angle = 90
            if self.flagStrName == "Y-Bar":
                angle = 70
            num = self.rethr - angle
            if (num < 0):
                num = num + 360
        else:
            num = self.rethr + angle
            if (num > 360):
                num = num - 360
        point3d1 = self.from1
        point3d2 = self.getThrPoint3D()
        point3d = MathHelper.getIntersectionPoint(
            point3d1,
            RnavWaypoints.smethod_3(self.from1, float(self.txtBearing.text()),
                                    Distance(1000)), point3d2,
            RnavWaypoints.smethod_3(self.getThrPoint3D(), num, Distance(1000)))
        if point3d == None:
            raise UserWarning, Messages.ERR_FAILED_TO_CALCULATE_INTERSECTION_POINT
        return RnavWaypoints.smethod_3(
            self.getThrPoint3D(), num,
            Distance(MathHelper.calcDistance(point3d2, point3d)))

    def setWaypoint(self, value):
        self.waypoint = value
        if self.from1 != None and self.waypoint != None:
            #             self.setBearing(RnavWaypoints.smethod_0(self.from1, value))
            #             if self.txtDistance.isEnabled():
            #             print RnavWaypoints.smethod_2(self.from1, value).NauticalMiles
            #             print RnavWaypoints.smethod_2(self.from1, value).NauticalMiles
            self.setDistance(
                RnavWaypoints.smethod_2(self.from1, value).NauticalMiles)

    def setDistance(self, value):
        self.txtDistance.setText("%i" % round(value))

    def setBearing(self, value):
        self.txtBearing.setText(str(value))

    def btnCalculate_Click(self):
        try:
            bearing = Unit.ConvertDegToRad(float(self.txtBearing.text()))
            distance0 = Distance(float(self.txtDistance.text()),
                                 DistanceUnits.NM).Metres
            self.calcedPoint = MathHelper.distanceBearingPoint(
                self.point, bearing, distance0)
            if self.flagStr == "R":
                self.parent0.parametersPanel.pnlIAWP1.Point3d = self.calcedPoint
                self.parent0.parametersPanel.txtRadiusIAWP1.setText(
                    self.txtDistance.text())
            elif self.flagStr == "L":
                self.parent0.parametersPanel.txtRadiusIAWP3.setText(
                    self.txtDistance.text())
                self.parent0.parametersPanel.pnlIAWP3.Point3d = self.calcedPoint
            elif self.flagStr == "C":
                self.parent0.parametersPanel.txtRadiusIAWP2.setText(
                    self.txtDistance.text())
                self.parent0.parametersPanel.pnlIAWP2.Point3d = self.calcedPoint

            self.accept()

        except UserWarning as e:
            QMessageBox.warning(self, "warning", e.message)

    def method_9(self):
        #         self.distanceMeasureTool = MeasureTool(define._canvas, self.txtDistance, DistanceUnits.NM)
        define._canvas.setMapTool(self.distanceMeasureTool)

    def method_8(self):
        #         self.bearingTool = CaptureBearingTool(define._canvas, self.txtBearing)
        define._canvas.setMapTool(self.bearingTool)

    def method_4(self):
        num = None
        num1 = None
        num2 = None
        num3 = None
        num4 = None
        num5 = None
        num6 = None
        num7 = None
        num8 = None
        num9 = None
        self.lbl1.setText(Validations.PLEASE_ENTER_VALID_RUNWAY_POSITIONS)
        self.lbl2.setText(" ")
        if (self.type == RnavCommonWaypoint.FAWP):
            position = self.getThrPoint3D()
            position1 = self.getEndPoint3D()
            if position is None or position1 is None:
                self.txtBearing.setText("")
                #                 self.txtDistance.setText("")
                return
            self.thrre = RnavWaypoints.smethod_0(position, position1)
            self.rethr = RnavWaypoints.smethod_0(position1, position)
            self.pos1400m = RnavWaypoints.smethod_3(position, self.rethr,
                                                    Distance(1400))
            self.MinDistance = RnavWaypoints.smethod_4(self.type,
                                                       self.category)
            #             if self.txtDistance.isEnabled():
            #             self.setDistance(RnavWaypoints.smethod_6(self.type, self.category).NauticalMiles)

            self.setBearing(self.rethr)
            self.MinBearing = RnavWaypoints.smethod_7(self.type, self.category,
                                                      self.rethr)
            self.MaxBearing = RnavWaypoints.smethod_8(self.type, self.category,
                                                      self.rethr)
#             if self.waypoint is not None:
#                 self.setBearing(round(RnavWaypoints.smethod_0(self.pos1400m, self.waypoint), 2))
# #                 if self.txtDistance.isEnabled():
#                 self.setDistance(RnavWaypoints.smethod_2(position, self.waypoint).NauticalMiles)

        elif (self.type == RnavCommonWaypoint.MAWP):
            position2 = self.getThrPoint3D()
            position3 = self.getEndPoint3D()
            if position2 is None or position3 is None:
                self.txtBearing.setText("")
                return
            self.thrre = RnavWaypoints.smethod_0(position2, position3)
            self.rethr = RnavWaypoints.smethod_0(position3, position2)

            self.pos1400m = RnavWaypoints.smethod_3(position2, self.rethr,
                                                    Distance(1400))
            num10 = RnavWaypoints.smethod_1(self.pos1400m, self.from1)
            num = RnavWaypoints.smethod_1(self.from1, self.pos1400m)
            num11 = 15
            position4 = None
            if (self.category == AircraftSpeedCategory.A
                    or self.category == AircraftSpeedCategory.B
                    or self.category == AircraftSpeedCategory.H):
                num11 = 30
            if (num10 > self.rethr or self.rethr - num10 >= 90):
                num1 = self.thrre + num11
                num2 = num
                if (num2 > 360):
                    num2 = num2 - 360
            else:
                num1 = num
                num2 = self.thrre - num11
                if (num2 < 0):
                    num2 = num2 + 360
            if (max(num1, num2) <= 270 or min(num1, num2) >= 90):
                num3 = min(num1, num2)
                num4 = max(num1, num2)
            else:
                num3 = max(num1, num2)
                num4 = min(num1, num2)
            position4 = RnavWaypoints.smethod_3(position2, self.thrre,
                                                Distance(466))
            num12 = RnavWaypoints.smethod_0(position4, self.from1)
            num13 = math.fabs(num12 - self.rethr)
            if (num13 > 180):
                num13 = 360 - num13
            if (num13 > 5):
                num5 = 0
                num6 = 0
                num7 = 0
                num8 = 0
            else:
                if (num12 > self.rethr or self.rethr - num12 >= 90):
                    num9 = self.rethr + 90
                    if (num9 > 360):
                        num9 = num9 - 360
                else:
                    num9 = self.rethr - 90
                    if (num9 < 0):
                        num9 = num9 + 360
                position5 = RnavWaypoints.smethod_3(self.pos1400m, num9,
                                                    Distance(150))
                num5 = RnavWaypoints.smethod_0(self.from1, position5)
                num6 = RnavWaypoints.smethod_0(self.from1, self.pos1400m)
                if (max(num5, num6) <= 270 or min(num5, num6) >= 90):
                    num7 = min(num5, num6)
                    num8 = max(num5, num6)
                else:
                    num7 = max(num5, num6)
                    num8 = min(num5, num6)
            if (MathHelper.smethod_99(num, self.thrre, 1)):
                position6 = RnavWaypoints.smethod_3(self.pos1400m,
                                                    self.rethr - 90,
                                                    Distance(150))
                position7 = RnavWaypoints.smethod_3(self.pos1400m,
                                                    self.rethr + 90,
                                                    Distance(150))
                num1 = RnavWaypoints.smethod_0(self.from1, position6)
                num2 = RnavWaypoints.smethod_0(self.from1, position7)
                num7 = 0
                num8 = 0
                if (max(num1, num2) <= 270 or min(num1, num2) >= 90):
                    num3 = min(num1, num2)
                    num4 = max(num1, num2)
                else:
                    num3 = max(num1, num2)
                    num4 = min(num1, num2)
            if (MathHelper.smethod_96(num7) or MathHelper.smethod_96(num8)):
                self.MinBearing = MathHelper.smethod_3(num3)
                self.MaxBearing = MathHelper.smethod_3(num4)
                self.MinBearing2 = MathHelper.smethod_3(num7)
                self.MaxBearing2 = MathHelper.smethod_3(num8)
            elif (min(num3, num4) >= min(num7, num8)):
                if (MathHelper.smethod_99(num8, num3, 0.3)):
                    num8 = num4
                    num3 = 0
                    num4 = 0
                self.MinBearing = MathHelper.smethod_3(num7)
                self.MaxBearing = MathHelper.smethod_3(num8)
                self.MinBearing2 = MathHelper.smethod_3(num3)
                self.MaxBearing2 = MathHelper.smethod_3(num4)
            else:
                if (MathHelper.smethod_99(num4, num7, 0.3)):
                    num4 = num8
                    num7 = 0
                    num8 = 0
                self.MinBearing = MathHelper.smethod_3(num3)
                self.MaxBearing = MathHelper.smethod_3(num4)
                self.MinBearing2 = MathHelper.smethod_3(num7)
                self.MaxBearing2 = MathHelper.smethod_3(num8)
            self.MinDistance = RnavWaypoints.smethod_4(self.type,
                                                       self.category)
            #             if self.txtDistance.isEnabled():
            #                 self.setDistance(RnavWaypoints.smethod_6(self.type, self.category).NauticalMiles)
            if (self.MinBearing <= self.MaxBearing):
                self.setBearing((self.MinBearing + self.MaxBearing) / 2)
            else:
                self.setBearing(
                    MathHelper.smethod_3(self.MinBearing +
                                         (360 - self.MinBearing +
                                          self.MaxBearing)))
#             if (self.waypoint is not None):
#                 self.setBearing(RnavWaypoints.smethod_0(self.from1, self.waypoint))
        if (MathHelper.smethod_96(self.MinBearing2)
                or MathHelper.smethod_96(self.MaxBearing2)):
            self.lbl1.setText(
                unicode("Acceptable bearings are %.1f° - %.1f°", "utf-8") %
                (self.MinBearing, self.MaxBearing))
        else:
            self.lbl1.setText(Validations.ACCEPTABLE_BEARINGS_ARE_X_Y_AND_X_Y %
                              (self.MinBearing, self.MaxBearing,
                               self.MinBearing2, self.MaxBearing2))
        if self.MinDistance != None and self.type != RnavCommonWaypoint.MAWP:
            self.lbl2.setText(Validations.ACCEPTABLE_MINIMUM_DISTANCE_IS_X %
                              (self.MinDistance.NauticalMiles))


#     def removeEnd(self):
#         self.txtEND_X.setText("")
#         self.txtEND_Y.setText("")
#     def removeThr(self):
#         self.txtTHR_X.setText("")
#         self.txtTHR_Y.setText("")
#     @staticmethod
#     def smethod_0( parent, rnavCommonWaypoint_0, aircraftSpeedCategory_0, position_0, position_1, position_List):
#         flag = None
#         using (DlgCalculateWaypoint dlgCalculateWaypoint = new DlgCalculateWaypoint())
#         {
#             dlgCalculateWaypoint.Text = string.Format("{0} {1}", Captions.CALCULATE, EnumHelper.smethod_0(rnavCommonWaypoint_0))
#             dlgCalculateWaypoint.Type = rnavCommonWaypoint_0
#             dlgCalculateWaypoint.Category = aircraftSpeedCategory_0
#             dlgCalculateWaypoint.From = position_1
#             double num = RnavWaypoints.smethod_0(position_0, position_1)
#             dlgCalculateWaypoint.MinBearing = RnavWaypoints.smethod_7(rnavCommonWaypoint_0, aircraftSpeedCategory_0, num)
#             dlgCalculateWaypoint.MaxBearing = RnavWaypoints.smethod_8(rnavCommonWaypoint_0, aircraftSpeedCategory_0, num)
#             dlgCalculateWaypoint.MinDistance = RnavWaypoints.smethod_4(rnavCommonWaypoint_0, aircraftSpeedCategory_0)
#             if (rnavCommonWaypoint_0 == RnavCommonWaypoint.IAWP1)
#             {
#                 dlgCalculateWaypoint.Bearing = dlgCalculateWaypoint.MinBearing
#             }
#             else if (rnavCommonWaypoint_0 != RnavCommonWaypoint.IAWP3)
#             {
#                 dlgCalculateWaypoint.Bearing = num
#             }
#             else
#             {
#                 dlgCalculateWaypoint.Bearing = dlgCalculateWaypoint.MaxBearing
#             }
#             dlgCalculateWaypoint.Distance = RnavWaypoints.smethod_6(rnavCommonWaypoint_0, aircraftSpeedCategory_0)
#             dlgCalculateWaypoint.Waypoint = position_2
#             if (dlgCalculateWaypoint.method_2(iwin32Window_0) != System.Windows.Forms.DialogResult.OK)
#             {
#                 flag = false
#             }
#             else
#             {
#                 position_2 = dlgCalculateWaypoint.Waypoint
#                 flag = true
#             }
#         }
#         return flag
#     }
#
#     public static bool smethod_1(IWin32Window iwin32Window_0, RnavCommonWaypoint rnavCommonWaypoint_0, AircraftSpeedCategory aircraftSpeedCategory_0, Position position_0, ref Position position_1, ref Position position_2, ref Position position_3)
#     {
#         bool flag
#         using (DlgCalculateWaypoint dlgCalculateWaypoint = new DlgCalculateWaypoint())
#         {
#             dlgCalculateWaypoint.Text = string.Format("{0} {1}", Captions.CALCULATE, EnumHelper.smethod_0(rnavCommonWaypoint_0))
#             dlgCalculateWaypoint.Type = rnavCommonWaypoint_0
#             dlgCalculateWaypoint.Category = aircraftSpeedCategory_0
#             dlgCalculateWaypoint.From = position_0
#             dlgCalculateWaypoint.RwyThr = position_1
#             dlgCalculateWaypoint.RwyEnd = position_2
#             dlgCalculateWaypoint.Waypoint = position_3
#             bool flag1 = dlgCalculateWaypoint.method_2(iwin32Window_0) == System.Windows.Forms.DialogResult.OK
#             position_1 = dlgCalculateWaypoint.RwyThr
#             position_2 = dlgCalculateWaypoint.RwyEnd
#             if (flag1)
#             {
#                 position_3 = dlgCalculateWaypoint.Waypoint
#             }
#             flag = flag1
#         }
#         return flag
#     }
# }
Пример #53
0
class MainWidget(QWidget):
    def __init__(self,
                 q1,
                 q2,
                 windowsize=(320, 240),
                 usecam2=False,
                 useforce=False,
                 parent=None):
        if PYTHON_VERSION == 3:
            super().__init__(parent)
        else:
            super(MainWidget, self).__init__(parent)
        self.setGeometry(800, 800, 800, 800)
        self.setWindowTitle('Robot Control Panel')

        self.q1 = q1  # Send to ROS
        self.adapter = Pipe2Signal(q2)  # Recv from ROS
        self.adapter.robot_signal.connect(self.adapter_handler)
        self.adapter.robot_heartbeat.connect(self.adapter_handler)

        self.usecam2 = usecam2
        self.useforce = useforce
        """
        4 Real-time displayers
        """

        self.image_widget_1 = ImageWidget(size=windowsize)
        self.record_video_1 = RecordVideo(camera_port=CAMERA_PORT_0)
        self.record_video_1.image_data.connect(
            self.image_widget_1.image_data_slot)
        self.image_saver_1 = ImageSaver(prefix="cam0")
        self.record_video_1.image_data.connect(
            self.image_saver_1.image_data_slot)

        if usecam2:
            self.image_widget_2 = ImageWidget(size=windowsize)
            self.record_video_2 = RecordVideo(camera_port=CAMERA_PORT_1)
            self.record_video_2.image_data.connect(
                self.image_widget_2.image_data_slot)
            self.image_saver_2 = ImageSaver(prefix="cam1")
            self.record_video_2.image_data.connect(
                self.image_saver_2.image_data_slot)
        else:
            self.image_widget_2 = QLabel("Cam2 Disabled")
            self.image_widget_2.setFixedSize(*windowsize)
            self.image_widget_2.setAlignment(Qt.AlignCenter)

        if useforce:
            self.force_widget_1 = ForceWidget(size=windowsize)
            self.record_video_1.image_data.connect(
                self.force_widget_1.image_data_slot)
            if usecam2:
                self.force_widget_2 = ForceWidget(size=windowsize)
                self.record_video_2.image_data.connect(
                    self.force_widget_2.image_data_slot)
            else:
                self.force_widget_2 = QLabel("Force2 Disabled")
                self.force_widget_2.setFixedSize(*windowsize)
                self.force_widget_2.setAlignment(Qt.AlignCenter)
        """
        Prediction
        """
        self.prediction_1 = -1
        self.prediction_lbl_1 = QLabel("Pred_1: -1")
        self.prediction_2 = -1
        self.prediction_lbl_2 = QLabel("Pred_1: -1")
        """
        Command buttons & other labels
        """

        self.run_button = QPushButton('Open camera')
        self.stop_button = QPushButton('Close camera')
        self.run_button.clicked.connect(
            self.start_all)  # self.record_video_1.start_recording)
        self.stop_button.clicked.connect(
            self.stop_all)  # self.record_video_1.stop_recording)

        self.sample_idx = 0
        self.sample_idx_lbl = QLabel("Index: 0")
        self.sample_idx_edit = QLineEdit()
        self.sample_idx_edit.setText(QString("0"))
        self.sample_idx_set_btn = QPushButton("Set", self)
        self.sample_idx_set_btn.clicked.connect(self.set_sample_idx)

        self.sample_times = 0
        self.sample_times_lbl = QLabel("Times: 0")
        # TODO: Update this shit

        self.grasp_button = QPushButton("Grasp")
        self.grasp_button.clicked.connect(self.grasp)
        self.regrasp_button = QPushButton("Regrasp")
        self.regrasp_button.clicked.connect(self.regrasp)

        self.grasp50_button = QPushButton("Grasp 50x")
        self.grasp50_button.clicked.connect(self.grasp50)
        self.open_button = QPushButton("Open")
        self.open_button.clicked.connect(self.open_gripper)
        self.close_button = QPushButton("Close")
        self.close_button.clicked.connect(self.close_gripper)

        self.moving_flag = QLabel("Moving: False")
        self.detected_flag = QLabel("Detect: False")
        self.position_flag = QLabel("Position: N/A")
        self.current_flag = QLabel("Current: N/A")

        self.exit_button = QPushButton("Exit", self)
        self.exit_button.clicked.connect(self.close)

        self.init_ui()
        self.adapter.start()

        # self.action_response = False
        self.multitimes = 0

    def init_ui(self):
        """
        Layouts
        """
        hlines = [QFrame() for _ in range(4)]
        for hline in hlines:
            hline.setFrameShape(QFrame.HLine)
            hline.setFrameShadow(QFrame.Sunken)

        vlines = [QFrame() for _ in range(1)]
        for vline in vlines:
            vline.setFrameShape(QFrame.VLine)
            vline.setFrameShadow(QFrame.Sunken)

        def getimgbox(name, imgwidget):
            imgbox = QVBoxLayout()
            imgbox.addWidget(QLabel(name))
            imgbox.addWidget(imgwidget)
            return imgbox

        layout = QVBoxLayout()

        hbox1 = QHBoxLayout()
        hbox1.addStretch(1)
        hbox1.addLayout(getimgbox("Image1", self.image_widget_1))
        hbox1.addStretch(1)
        hbox1.addLayout(getimgbox("Image2", self.image_widget_2))
        hbox1.addStretch(1)

        vbox1 = QVBoxLayout()
        vbox1.addStretch(1)
        vbox1.addLayout(hbox1)
        vbox1.addStretch(1)
        vbox1.addWidget(hlines[0])
        vbox1.addStretch(1)

        if self.useforce:
            hbox2 = QHBoxLayout()
            hbox2.addStretch(1)
            hbox2.addLayout(getimgbox("Force1", self.force_widget_1))
            hbox2.addStretch(1)
            hbox2.addLayout(getimgbox("Force2", self.force_widget_2))
            hbox2.addStretch(1)
            vbox1.addLayout(hbox2)
            vbox1.addStretch(1)
        else:
            pass

        vbox2 = QGridLayout()
        vbox2.addWidget(self.sample_idx_lbl, 1, 1)
        vbox2.addWidget(self.sample_idx_edit, 2, 1, 2, 4)
        vbox2.addWidget(self.sample_idx_set_btn, 2, 5, 2, 6)
        vbox2.addWidget(self.sample_times_lbl, 4, 1, 4, 2)

        vbox3 = QGridLayout()
        vbox3.addWidget(QLabel("Predictions"), 1, 1)
        vbox3.addWidget(self.prediction_lbl_1, 3, 1)
        vbox3.addWidget(self.prediction_lbl_2, 4, 1)

        vbox4 = QGridLayout()
        vbox4.addWidget(QLabel("Robot commands"), 1, 1, 1, 2)
        vbox4.addWidget(self.open_button, 3, 2)
        vbox4.addWidget(self.close_button, 4, 2)
        vbox4.addWidget(self.grasp_button, 5, 2)
        vbox4.addWidget(self.regrasp_button, 6, 2)
        vbox4.addWidget(self.grasp50_button, 7, 2)
        vbox4.addWidget(QLabel(""), 6, 3)
        vbox4.addWidget(self.moving_flag, 9, 2)
        vbox4.addWidget(self.detected_flag, 10, 2)
        vbox4.addWidget(self.position_flag, 11, 2)
        vbox4.addWidget(self.current_flag, 12, 2)

        vbox5 = QVBoxLayout()
        vbox5.addStretch(1)
        vbox5.addLayout(vbox2)
        vbox5.addStretch(1)
        vbox5.addWidget(hlines[1])
        vbox5.addStretch(1)
        vbox5.addLayout(vbox3)
        vbox5.addStretch(1)
        vbox5.addWidget(hlines[2])
        vbox5.addStretch(1)
        vbox5.addLayout(vbox4)
        vbox5.addStretch(1)

        hbox6 = QHBoxLayout()
        hbox6.addStretch(1)
        hbox6.addLayout(vbox1)
        hbox6.addStretch(1)
        hbox6.addWidget(vlines[0])
        hbox6.addStretch(1)
        hbox6.addLayout(vbox5)
        hbox6.addStretch(1)

        hbox7 = QHBoxLayout()
        hbox7.addStretch(2)
        hbox7.addWidget(self.run_button)
        hbox7.addStretch(1)
        hbox7.addWidget(self.stop_button)
        hbox7.addStretch(1)
        hbox7.addWidget(self.exit_button)
        hbox7.addStretch(2)

        layout.addStretch(1)
        layout.addLayout(hbox6)
        layout.addStretch(1)
        layout.addWidget(hlines[3])
        layout.addStretch(1)
        layout.addLayout(hbox7)
        layout.addStretch(1)

        self.setLayout(layout)

    def closeEvent(self, event):
        self.deleteLater()

    def start_all(self):
        self.record_video_1.start_recording()
        if self.usecam2:
            self.record_video_2.start_recording()

    def stop_all(self):
        self.record_video_1.stop_recording()
        if self.usecam2:
            self.record_video_2.stop_recording()

    def set_sample_idx(self):
        self.sample_idx = int(self.sample_idx_edit.text())
        self.sample_idx_lbl.setText("Index: {}".format(self.sample_idx))
        self.image_saver_1.setidx(self.sample_idx)
        if self.usecam2:
            self.image_saver_2.setidx(self.sample_idx)

        self.sample_times = self.image_saver_1.times_idx
        if self.usecam2:
            assert (self.sample_times == self.image_saver_2.times_idx)

    def adapter_handler(self, value):
        if isinstance(value, QString):  # Robot status heartbeat
            _value = str(value).split(',')
            assert (len(_value) == 4)
            self.moving_flag.setText("Moving: {}".format(_value[0]))
            self.detected_flag.setText("Detect: {}".format(_value[1]))
            self.position_flag.setText("Position: {0:.4f}".format(
                float(_value[2])))
            self.current_flag.setText("Current: {0:.4f}".format(
                float(_value[3])))
        else:  # Robot action response
            if value == 1:  # Debug
                self.shutdown_savers()
            elif value == 2:  # Opened
                print("Gripper opened.")
            elif value == 3:  # Closed
                print("Gripper closed.")
            elif value == 4:  # Grasped
                self.shutdown_savers()
                # self.action_response = True
                if self.multitimes > 0:
                    self.multitimes -= 1
                    print("{} times left".format(self.multitimes))
                    time.sleep(2)
                    self.grasp()
                else:
                    print("Grasping completed.")
            else:
                print("Adapter handler got undefined signal {} with type {}".
                      format(value, type(value)))

    def grasp(self):
        # Sync
        assert (self.sample_times == self.image_saver_1.times_idx
                ), "sample times = {}, image saver 1 time idx = {}".format(
                    self.sample_times, self.image_saver_1.times_idx)
        if self.usecam2:
            assert (self.sample_times == self.image_saver_2.times_idx
                    ), "sample times = {}, image saver 2 time idx = {}".format(
                        self.sample_times, self.image_saver_2.times_idx)

        self.image_saver_1.enable()
        if self.usecam2:
            self.image_saver_2.enable()
        # self.pipe.send(1)   # 1 when debugging
        self.q1.put(4)
        self.sample_times += 1
        self.sample_times_lbl.setText("Times: {}".format(self.sample_times))

    def grasp50(self):
        self.multitimes = 50
        self.q1.put(5)

    def open_gripper(self):
        self.q1.put(2)

    def close_gripper(self):
        self.q1.put(3)

    def regrasp(self):
        self.sample_times -= 1
        self.grasp()
        # TODO: Needs lots of tests here lol

    def shutdown_savers(self):
        self.image_saver_1.disable()
        if self.usecam2:
            self.image_saver_2.disable()
Пример #54
0
class OWDatabasesUpdate(OWWidget):

    name = "Databases Update"
    description = "Update local systems biology databases."
    icon = "../widgets/icons/Databases.svg"
    priority = 10

    inputs = []
    outputs = []

    want_main_area = False

    def __init__(self, parent=None, signalManager=None,
                 name="Databases update", domains=None):
        OWWidget.__init__(self, parent, signalManager, name,
                          wantMainArea=False)

        self.searchString = ""
        self.accessCode = ""
        self.domains = domains or DOMAINS
        self.serverFiles = serverfiles.ServerFiles()

        fbox = gui.widgetBox(self.controlArea, "Filter")
        self.completer = TokenListCompleter(
            self, caseSensitivity=Qt.CaseInsensitive)
        self.lineEditFilter = QLineEdit(textChanged=self.SearchUpdate)
        self.lineEditFilter.setCompleter(self.completer)

        fbox.layout().addWidget(self.lineEditFilter)

        box = gui.widgetBox(self.controlArea, "Files")

        self.filesView = QTreeWidget(self)
        self.filesView.setHeaderLabels(
            ["", "Data Source", "Update", "Last Updated", "Size"])

        self.filesView.setRootIsDecorated(False)
        self.filesView.setUniformRowHeights(True)
        self.filesView.setSelectionMode(QAbstractItemView.NoSelection)
        self.filesView.setSortingEnabled(True)
        self.filesView.sortItems(1, Qt.AscendingOrder)
        self.filesView.setItemDelegateForColumn(
            0, UpdateOptionsItemDelegate(self.filesView))

        self.filesView.model().layoutChanged.connect(self.SearchUpdate)

        box.layout().addWidget(self.filesView)

        box = gui.widgetBox(self.controlArea, orientation="horizontal")
        self.updateButton = gui.button(
            box, self, "Update all",
            callback=self.UpdateAll,
            tooltip="Update all updatable files",
         )

        self.downloadButton = gui.button(
            box, self, "Download all",
            callback=self.DownloadFiltered,
            tooltip="Download all filtered files shown"
        )

        self.cancelButton = gui.button(
            box, self, "Cancel", callback=self.Cancel,
            tooltip="Cancel scheduled downloads/updates."
        )

        self.retryButton = gui.button(
            box, self, "Reconnect", callback=self.RetrieveFilesList
        )
        self.retryButton.hide()

        gui.rubber(box)

        gui.lineEdit(box, self, "accessCode", "Access Code",
                     orientation="horizontal",
                     callback=self.RetrieveFilesList)

        self.warning(0)

        box = gui.widgetBox(self.controlArea, orientation="horizontal")
        gui.rubber(box)

        self.infoLabel = QLabel()
        self.infoLabel.setAlignment(Qt.AlignCenter)

        self.controlArea.layout().addWidget(self.infoLabel)
        self.infoLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        self.updateItems = []

        self.resize(800, 600)

        self.progress = ProgressState(self, maximum=3)
        self.progress.valueChanged.connect(self._updateProgress)
        self.progress.rangeChanged.connect(self._updateProgress)
        self.executor = ThreadExecutor(
            threadPool=QThreadPool(maxThreadCount=2)
        )

        task = Task(self, function=self.RetrieveFilesList)
        task.exceptionReady.connect(self.HandleError)
        task.start()

        self._tasks = []
        self._haveProgress = False

    def RetrieveFilesList(self):
        self.retryButton.hide()
        self.warning(0)
        self.progress.setRange(0, 3)
        self.serverFiles = serverfiles.ServerFiles(access_code=self.accessCode)

        task = Task(function=partial(retrieveFilesList, self.serverFiles,
                                     self.domains,
                                     methodinvoke(self.progress, "advance")))

        task.resultReady.connect(self.SetFilesList)
        task.exceptionReady.connect(self.HandleError)

        self.executor.submit(task)

        self.setEnabled(False)

    def SetFilesList(self, serverInfo):
        """
        Set the files to show.
        """
        self.setEnabled(True)

        domains = serverInfo.keys()
        if not domains:
            if self.domains:
                domains = self.domains
            else:
                domains = serverfiles.listdomains()

        localInfo = dict([(dom, serverfiles.allinfo(dom)) for dom in domains])

        all_tags = set()

        self.filesView.clear()
        self.updateItems = []

        for item in join_info_dict(localInfo, serverInfo):
            tree_item = UpdateTreeWidgetItem(item)
            options_widget = UpdateOptionsWidget(item.state)
            options_widget.item = item

            options_widget.installClicked.connect(
                partial(self.SubmitDownloadTask, item.domain, item.filename)
            )
            options_widget.removeClicked.connect(
                partial(self.SubmitRemoveTask, item.domain, item.filename)
            )

            self.updateItems.append((item, tree_item, options_widget))
            all_tags.update(item.tags)

        self.filesView.addTopLevelItems(
            [tree_item for _, tree_item, _ in self.updateItems]
        )

        for item, tree_item, options_widget in self.updateItems:
            self.filesView.setItemWidget(tree_item, 0, options_widget)

            # Add an update button if the file is updateable
            if item.state == OUTDATED:
                button = QToolButton(
                    None, text="Update",
                    maximumWidth=120,
                    minimumHeight=20,
                    maximumHeight=20
                )

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

                button.clicked.connect(
                    partial(self.SubmitDownloadTask, item.domain,
                            item.filename)
                )

                self.filesView.setItemWidget(tree_item, 2, button)

        self.progress.advance()

        self.filesView.setColumnWidth(0, self.filesView.sizeHintForColumn(0))

        for column in range(1, 4):
            contents_hint = self.filesView.sizeHintForColumn(column)
            header_hint = self.filesView.header().sectionSizeHint(column)
            width = max(min(contents_hint, 400), header_hint)
            self.filesView.setColumnWidth(column, width)

        hints = [hint for hint in sorted(all_tags) if not hint.startswith("#")]
        self.completer.setTokenList(hints)
        self.SearchUpdate()
        self.UpdateInfoLabel()
        self.toggleButtons()
        self.cancelButton.setEnabled(False)

        self.progress.setRange(0, 0)

    def buttonCheck(self, selected_items, state, button):
        for item in selected_items:
            if item.state != state:
                button.setEnabled(False)
            else:
                button.setEnabled(True)
                break

    def toggleButtons(self):
        selected_items = [item for item, tree_item, _ in self.updateItems if not tree_item.isHidden()]
        self.buttonCheck(selected_items, OUTDATED, self.updateButton)
        self.buttonCheck(selected_items, AVAILABLE, self.downloadButton)

    def HandleError(self, exception):
        if isinstance(exception, ConnectionError):
            self.warning(0,
                       "Could not connect to server! Check your connection "
                       "and try to reconnect.")
            self.SetFilesList({})
            self.retryButton.show()
        else:
            sys.excepthook(type(exception), exception.args, None)
            self.progress.setRange(0, 0)
            self.setEnabled(True)

    def UpdateInfoLabel(self):
        local = [item for item, tree_item, _ in self.updateItems
                 if item.state != AVAILABLE and not tree_item.isHidden()]
        size = sum(float(item.size) for item in local)

        onServer = [item for item, tree_item, _ in self.updateItems if not tree_item.isHidden()]
        sizeOnServer = sum(float(item.size) for item in onServer)

        text = ("%i items, %s (on server: %i items, %s)" %
                (len(local),
                 sizeof_fmt(size),
                 len(onServer),
                 sizeof_fmt(sizeOnServer)))

        self.infoLabel.setText(text)

    def UpdateAll(self):
        self.warning(0)
        for item, tree_item, _ in self.updateItems:
            if item.state == OUTDATED and not tree_item.isHidden():
                self.SubmitDownloadTask(item.domain, item.filename)

    def DownloadFiltered(self):
        # TODO: submit items in the order shown.
        for item, tree_item, _ in self.updateItems:
            if not tree_item.isHidden() and item.state in \
                    [AVAILABLE, OUTDATED]:
                self.SubmitDownloadTask(item.domain, item.filename)

    def SearchUpdate(self, searchString=None):
        strings = str(self.lineEditFilter.text()).split()
        for item, tree_item, _ in self.updateItems:
            hide = not all(UpdateItem_match(item, string)
                           for string in strings)
            tree_item.setHidden(hide)
        self.UpdateInfoLabel()
        self.toggleButtons()

    def SubmitDownloadTask(self, domain, filename):
        """
        Submit the (domain, filename) to be downloaded/updated.
        """
        self.cancelButton.setEnabled(True)

        index = self.updateItemIndex(domain, filename)
        _, tree_item, opt_widget = self.updateItems[index]

        if self.accessCode:
            sf = serverfiles.ServerFiles(access_code=self.accessCode)
        else:
            sf = serverfiles.ServerFiles()

        task = DownloadTask(domain, filename, sf)

        self.progress.adjustRange(0, 100)

        pb = ItemProgressBar(self.filesView)
        pb.setRange(0, 100)
        pb.setTextVisible(False)

        task.advanced.connect(pb.advance)
        task.advanced.connect(self.progress.advance)
        task.finished.connect(pb.hide)
        task.finished.connect(self.onDownloadFinished, Qt.QueuedConnection)
        task.exception.connect(self.onDownloadError, Qt.QueuedConnection)

        self.filesView.setItemWidget(tree_item, 2, pb)

        # Clear the text so it does not show behind the progress bar.
        tree_item.setData(2, Qt.DisplayRole, "")
        pb.show()

        # Disable the options widget
        opt_widget.setEnabled(False)
        self._tasks.append(task)

        self.executor.submit(task)

    def EndDownloadTask(self, task):
        future = task.future()
        index = self.updateItemIndex(task.domain, task.filename)
        item, tree_item, opt_widget = self.updateItems[index]

        self.filesView.removeItemWidget(tree_item, 2)
        opt_widget.setEnabled(True)

        if future.cancelled():
            # Restore the previous state
            tree_item.setUpdateItem(item)
            opt_widget.setState(item.state)

        elif future.exception():
            tree_item.setUpdateItem(item)
            opt_widget.setState(item.state)

            # Show the exception string in the size column.
            self.warning(0, "Error while downloading. Check your connection "
                            "and retry.")

            # recreate button for download
            button = QToolButton(
                None, text="Retry",
                maximumWidth=120,
                minimumHeight=20,
                maximumHeight=20
            )

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

            button.clicked.connect(
                partial(self.SubmitDownloadTask, item.domain,
                        item.filename)
            )

            self.filesView.setItemWidget(tree_item, 2, button)

        else:
            # get the new updated info dict and replace the the old item
            self.warning(0)
            info = serverfiles.info(item.domain, item.filename)
            new_item = update_item_from_info(item.domain, item.filename,
                                             info, info)

            self.updateItems[index] = (new_item, tree_item, opt_widget)

            tree_item.setUpdateItem(new_item)
            opt_widget.setState(new_item.state)

            self.UpdateInfoLabel()

    def SubmitRemoveTask(self, domain, filename):
        serverfiles.remove(domain, filename)
        index = self.updateItemIndex(domain, filename)
        item, tree_item, opt_widget = self.updateItems[index]

        if item.info_server:
            new_item = item._replace(state=AVAILABLE, local=None,
                                      info_local=None)
        else:
            new_item = item._replace(local=None, info_local=None)
            # Disable the options widget. No more actions can be performed
            # for the item.
            opt_widget.setEnabled(False)

        tree_item.setUpdateItem(new_item)
        opt_widget.setState(new_item.state)
        self.updateItems[index] = (new_item, tree_item, opt_widget)

        self.UpdateInfoLabel()

    def Cancel(self):
        """
        Cancel all pending update/download tasks (that have not yet started).
        """
        for task in self._tasks:
            task.future().cancel()

    def onDeleteWidget(self):
        self.Cancel()
        self.executor.shutdown(wait=False)
        OWWidget.onDeleteWidget(self)

    def onDownloadFinished(self):
        # on download completed/canceled/error
        assert QThread.currentThread() is self.thread()
        for task in list(self._tasks):
            future = task.future()
            if future.done():
                self.EndDownloadTask(task)
                self._tasks.remove(task)

        if not self._tasks:
            # Clear/reset the overall progress
            self.progress.setRange(0, 0)
            self.cancelButton.setEnabled(False)

    def onDownloadError(self, exc_info):
        sys.excepthook(*exc_info)
        self.warning(0, "Error while downloading. Check your connection and "
                        "retry.")

    def updateItemIndex(self, domain, filename):
        for i, (item, _, _) in enumerate(self.updateItems):
            if item.domain == domain and item.filename == filename:
                return i
        raise ValueError("%r, %r not in update list" % (domain, filename))

    def _updateProgress(self, *args):
        rmin, rmax = self.progress.range()
        if rmin != rmax:
            if not self._haveProgress:
                self._haveProgress = True
                self.progressBarInit()

            self.progressBarSet(self.progress.ratioCompleted() * 100,
                                processEvents=None)
        if rmin == rmax:
            self._haveProgress = False
            self.progressBarFinished()
Пример #55
0
class Entity(QWidget):
    def __init__(self, base_image, size, hp=100, pos=(0, 0), parent=None):
        super().__init__(parent)
        self._base_label = QLabel(self)
        self._base_image = base_image
        self._size = size
        self._decor_label = None
        self._decor_pixmap = None
        self._hp_max = hp

        self.__pixmap = None
        """:type: PyQt4.QtGui.QPixmap"""

        self.__cord_x = pos[0]
        self.__cord_y = pos[1]
        self.__angle = 0

        self.__hp_bar = QProgressBar(self)
        self.__hp_bar.setMaximum(self._hp_max)
        self.__hp_bar.setValue(self._hp_max)
        self.__hp_bar.setTextVisible(False)
        self.__hp_bar.setMaximumSize(size[0], 5)

        self.setAlignment(Qt.AlignCenter)
        self.updatePixmap()

        if _debugging:
            self.setStyleSheet("border: 1px solid black")

    @property
    def health(self):
        return self.__hp_bar.value()

    @health.setter
    def health(self, hp):
        if hp > self._hp_max:
            hp = self._hp_max
        elif hp < 0:
            hp = 0
        self.__hp_bar.setValue(hp)

    @property
    def angle(self):
        return self.__angle

    @angle.setter
    def angle(self, angle):
        self.__angle = angle
        self.updatePixmap()

    @property
    def cord_x(self):
        return self.__cord_x

    @cord_x.setter
    def cord_x(self, cord):
        self.__cord_x = cord
        self.move(self.cord_x, self.cord_y)

    @property
    def cord_y(self):
        return self.__cord_y

    @cord_y.setter
    def cord_y(self, cord):
        self.__cord_y = cord
        self.move(self.cord_x, self.cord_y)

    def hide_hp_bar(self, bool=False):
        if bool:
            self.__hp_bar.hide()
        else:
            self.__hp_bar.show()

    def add_decoration(self, path):
        if path is None:
            self._decor_label.deleteLater()
            self._decor_label = None
        else:
            self._decor_label = QLabel(self)
            self._decor_pixmap = QPixmap(path)
            # self._decor_pixmap = self._decor_pixmap.scaled(self._size[0], self._size[1])
            self._decor_pixmap = self._decor_pixmap.transformed(
                QTransform().rotate(self.angle))
            self._decor_label.setPixmap(self._decor_pixmap)
            self._decor_label.setAlignment(Qt.AlignCenter)
            self._decor_label.show()

    def updatePixmap(self):
        path = get_asset_path(self._base_image)
        self.__pixmap = QPixmap(path)
        self.__pixmap = self.__pixmap.scaled(self._size[0], self._size[1])
        self.__pixmap = self.__pixmap.transformed(QTransform().rotate(
            self.angle))
        self._base_label.setPixmap(self.__pixmap)
        self._base_label.show()
        # self.setFixedSize(self.__pixmap.width(), self.__pixmap.height())

    def setFixedSize(self, x, y):
        super().setFixedSize(x, y)
        self._base_label.setFixedSize(x, y)

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

        self.setFixedWidth(500)
        self.setFixedHeight(400)
        self.setStyleSheet("font-size:20px;")

        self.vLayout = QVBoxLayout()
        self.setLayout(self.vLayout)

        settingsLabel = QLabel(self)
        settingsLabel.setText("Default settings")
        settingsLabel.setStyleSheet("font-size:25px;")
        settingsLabel.setFixedWidth(500)
        settingsLabel.setAlignment(Qt.AlignCenter)
        self.vLayout.addWidget(settingsLabel)

        sectionColorLabel = QLabel(self)
        sectionColorLabel.setText("Section colors:")
        self.sectionColorChooser = ColorChooser()
        self.sectionColorChooser.setMaximumWidth(50)
        self.sectionSecondColorChooser = ColorChooser()
        self.sectionSecondColorChooser.setMaximumWidth(50)
        self.putInHorizontalLayout(sectionColorLabel, self.sectionColorChooser,
                                   self.sectionSecondColorChooser)

        subsectionColorLabel = QLabel(self)
        subsectionColorLabel.setText("Subsection colors: ")
        self.subsectionColorChooser = ColorChooser(self)
        self.subsectionColorChooser.setMaximumWidth(50)
        self.subsectionSecondColorChooser = ColorChooser(self)
        self.subsectionSecondColorChooser.setMaximumWidth(50)
        self.putInHorizontalLayout(subsectionColorLabel,
                                   self.subsectionColorChooser,
                                   self.subsectionSecondColorChooser)

        linacSectionSizeLabel = QLabel(self)
        linacSectionSizeLabel.setText("Linac section size: ")
        self.linacSectionSizeSpinBox = QDoubleSpinBox(self)
        self.linacSectionSizeSpinBox.setFixedWidth(100)
        self.linacSectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(linacSectionSizeLabel,
                                   self.linacSectionSizeSpinBox)

        linacSubsectionSizeLabel = QLabel(self)
        linacSubsectionSizeLabel.setText("Linac subsection size: ")
        self.linacSubsectionSizeSpinBox = QDoubleSpinBox(self)
        self.linacSubsectionSizeSpinBox.setFixedWidth(100)
        self.linacSubsectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(linacSubsectionSizeLabel,
                                   self.linacSubsectionSizeSpinBox)

        ringSectionSizeLabel = QLabel(self)
        ringSectionSizeLabel.setText("Ring section size: ")
        self.ringSectionSizeSpinBox = QDoubleSpinBox(self)
        self.ringSectionSizeSpinBox.setFixedWidth(100)
        self.ringSectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(ringSectionSizeLabel,
                                   self.ringSectionSizeSpinBox)

        ringSubectionSizeLabel = QLabel(self)
        ringSubectionSizeLabel.setText("Ring subsection size: ")
        self.ringSubsectionSizeSpinBox = QDoubleSpinBox(self)
        self.ringSubsectionSizeSpinBox.setFixedWidth(100)
        self.ringSubsectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(ringSubectionSizeLabel,
                                   self.ringSubsectionSizeSpinBox)

        centerCoordinatesLabel = QLabel(self)
        centerCoordinatesLabel.setText("Real coordinates of ring center:")
        self.centerCoordinatesEditX = QLineEdit()
        self.centerCoordinatesEditX.setPlaceholderText("X")
        self.centerCoordinatesEditX.setFixedWidth(80)
        self.centerCoordinatesEditY = QLineEdit()
        self.centerCoordinatesEditY.setPlaceholderText("Y")
        self.centerCoordinatesEditY.setFixedWidth(80)
        self.putInHorizontalLayout(centerCoordinatesLabel,
                                   self.centerCoordinatesEditX,
                                   self.centerCoordinatesEditY)

        showDeviceCaptionsLabel = QLabel(self)
        showDeviceCaptionsLabel.setText("Show device captions:")
        showDeviceCaptionsLabel.setFixedWidth(500)
        self.showDeviceCaptionsCheckBox = QCheckBox(self)
        self.putInHorizontalLayout(showDeviceCaptionsLabel,
                                   self.showDeviceCaptionsCheckBox)

        useDbParametersLabel = QLabel(self)
        useDbParametersLabel.setText("Use parameters from database")
        useDbParametersLabel.setFixedWidth(500)
        self.useDbParametersCheckBox = QCheckBox(self)
        self.putInHorizontalLayout(useDbParametersLabel,
                                   self.useDbParametersCheckBox)

        tangoHostLabel = QLabel(self)
        tangoHostLabel.setText("Tango Host")
        self.tangoHostEdit = QLineEdit(self)
        self.tangoHostEdit.setFixedHeight(25)
        self.tangoHostEdit.setText("127.0.0.1:10000")
        self.tangoHostEdit.setStyleSheet("font-size:18px;")
        self.putInHorizontalLayout(tangoHostLabel, self.tangoHostEdit)

        self.setDefaultSettings()
Пример #57
0
class ScreenShot(QWidget):
    def __init__(self):
        super(ScreenShot, self).__init__()

        self.initUI()

    def initUI(self):
        self.originalPixmap = QPixmap()

        self.screenshotLabel = QLabel("screenshotlabel", self)
        self.screenshotLabel.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)
        self.screenshotLabel.setAlignment(Qt.AlignCenter)

        self.screenGeometry = QApplication.desktop().screenGeometry(
        )  # Qrect()
        print self.screenGeometry, self.screenGeometry.width()
        self.screenshotLabel.setMinimumSize(self.screenGeometry.width() / 8,
                                            self.screenGeometry.height() / 8)

        mainlayout = QVBoxLayout(self)
        mainlayout.addWidget(self.screenshotLabel)

        self.optionsGroupBox = QGroupBox(u"选项", self)

        self.hideThisWindowCheckBox = QCheckBox(u"隐藏这个窗口",
                                                self.optionsGroupBox)
        self.optionsGroupBoxLayout = QGridLayout(self.optionsGroupBox)

        mainlayout.addWidget(self.optionsGroupBox)
        self.delaySpinBox = QSpinBox(self.optionsGroupBox)
        self.delaySpinBox.setSuffix(u"s")
        self.delaySpinBox.setMaximum(60)

        self.optionsGroupBoxLayout.addWidget(QLabel(u"截屏延时:", self), 0, 0)
        self.optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1)
        self.optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0)

        buttonLayout = QHBoxLayout()

        self.newScreenshotButton = QPushButton(u"新截图", self)
        self.newScreenshotButton.clicked.connect(self.__newScreenshot)
        buttonLayout.addWidget(self.newScreenshotButton)

        saveScreenshotButton = QPushButton(u"保存截图", self)
        buttonLayout.addWidget(saveScreenshotButton)

        quitScreenshotButton = QPushButton(u"退出截图", self)
        quitScreenshotButton.setShortcut("Ctrl+Q")
        buttonLayout.addWidget(saveScreenshotButton)
        buttonLayout.addStretch()
        mainlayout.addLayout(buttonLayout)
        quitScreenshotButton.clicked.connect(self.close)

        saveScreenshotButton.clicked.connect(self.__saveScreenshot)
        self.delaySpinBox.valueChanged.connect(self.__updateCheckBox)
        self.delaySpinBox.setValue(5)
        self.setWindowTitle(u"截图")
        self.resize(300, 200)

    def resizeEvent(self, QResizeEvent):
        scaledSize = self.originalPixmap.size()
        scaledSize.scale(self.screenshotLabel.size(), Qt.KeepAspectRatio)
        if (not self.screenshotLabel.pixmap()) or (
                scaledSize != self.screenshotLabel.pixmap().size()):
            self.__updateScreenshotLabel()

    def __newScreenshot(self):
        if self.hideThisWindowCheckBox.isChecked():
            self.hide()

        self.newScreenshotButton.setDisabled(True)

        QTimer.singleShot(self.delaySpinBox.value() * 1000, self.__shootScreen)

    def __saveScreenshot(self):
        format = "png"
        initialPath = QDesktopServices.storageLocation(
            QDesktopServices.PicturesLocation)
        # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
        if initialPath.isEmpty():
            initialPath = QDir.currentPath()
        initialPath += "/untitled." + format

        fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath)
        fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
        fileDialog.setDirectory(initialPath)
        mimeTypes = QStringList()

        for bf in QImageWriter.supportedImageFormats():
            mimeTypes.append(QLatin1String(bf))

        # fileDialog.setMin setMimeTypeFilters(mimeTypes)
        # fileDialog.selectMimeTypeFilter("image/" + format);
        fileDialog.setDefaultSuffix(format)
        if fileDialog.accept():
            return

        fileName = fileDialog.selectedFiles().first()

        if not self.originalPixmap.save(fileName):
            QtGui.QMessageBox.Warning(
                self, u"保存错误",
                u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName)))

    def __shootScreen(self):

        if self.delaySpinBox.value() != 0:
            QApplication.beep()

        self.originalPixmap = QPixmap.grabWindow(
            QApplication.desktop().winId())
        self.__updateScreenshotLabel()

        self.newScreenshotButton.setDisabled(False)
        if self.hideThisWindowCheckBox.isChecked():
            self.show()

    def __updateCheckBox(self):
        print "sssss"
        if self.delaySpinBox.value() == 0:
            self.hideThisWindowCheckBox.setDisabled(True)
            self.hideThisWindowCheckBox.setChecked(False)
        else:
            self.hideThisWindowCheckBox.setDisabled(False)

    def __updateScreenshotLabel(self):
        self.screenshotLabel.setPixmap(
            self.originalPixmap.scaled(self.screenshotLabel.size(),
                                       Qt.KeepAspectRatio,
                                       Qt.SmoothTransformation))
Пример #58
0
class AutoRecordWidget(QWidget):
    """Widget that displays the fullscreen countdown for Freeseer's automated recording mode"""
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.secs = None
        self.recording = False
        self.flashMillisecs = 1000
        self.flashTimes = [0, 250, 500, 750]

        self.resize(400, 400)
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)
        self.talkInfoFont = QFont('Serif', 50, QFont.Light)
        self.countdownFont = QFont('Serif', 300, QFont.Light)

        self.talkInfoString = QLabel()
        self.mainLayout.addWidget(self.talkInfoString)
        self.talkInfoString.setFont(self.talkInfoFont)
        self.talkInfoString.setAlignment(Qt.AlignCenter)
        self.talkInfoString.setStyleSheet(
            "QLabel { background-color : white; color : black; }")

        self.countdownString = QLabel()
        self.mainLayout.addWidget(self.countdownString)
        self.countdownString.setFont(self.countdownFont)
        self.countdownString.setAlignment(Qt.AlignCenter)
        self.countdownString.setStyleSheet(
            "QLabel { background-color : white; color : black; }")

        self.countdownTimer = QTimer()
        self.countdownTimer.timeout.connect(self.timertick)

        self.flashTimer = QTimer()
        self.flashTimer.timeout.connect(self.flash_display_text)

        QShortcut(QKeySequence("Esc"), self, self.showNormal)

    def set_recording(self, recording):
        """Sets recording to true or false"""
        self.recording = recording

    def set_display_message(self, title="", speaker=""):
        """Sets the part of the display message on screen that is not related to countdown"""
        if self.recording:
            self.talkInfoString.setText("RECORDING\n\nTime remaining:")
        else:
            self.talkInfoString.setText(
                "NEXT TALK\nTitle: %s\nSpeaker: %s\n\nTime until recording:" %
                (title, speaker))

    def start_timer(self, secs):
        """Sets how much time to count down and starts the timer"""
        self.secs = secs
        self.countdownTimer.start(1000)

    def start_flash_timer(self):
        """Sets how much time to flash the screen and starts the timer"""
        self.flashMillisecs = 1000
        self.flashTimer.start(50)

    def flash_display_text(self):
        """Sets the flashing talk info and countdown display, decrements flash countdown and stops timer"""
        if self.flashMillisecs in self.flashTimes:
            self.countdownString.setStyleSheet(
                "QLabel { background-color : white; color : black; }")
            self.talkInfoString.setStyleSheet(
                "QLabel { background-color : white; color : black; }")
        else:
            self.countdownString.setStyleSheet(
                "QLabel { background-color : black; color : white; }")
            self.talkInfoString.setStyleSheet(
                "QLabel { background-color : black; color : white; }")
        self.flashMillisecs -= 50
        if self.flashMillisecs < 0:
            self.flashTimer.stop()

    def timertick(self):
        """Sets the countdown display string, decrements countdown, plays alert and stops timer.

        Sets and displays the countdown until the start or end of recording of a talk using a countdown timer.
        The size of one unit of timer tick is one second. Before recording starts, plays an alert sound.
        """
        if self.secs > 120:
            self.countdownString.setText("%d min." %
                                         (self.secs / 60 + 1))  # e.g., 5 min
        else:
            self.countdownString.setText(
                "%02d:%02d" % (self.secs / 60, self.secs % 60))  # e.g., 01:36

        # Flash the screen when there is 1 minute and when there is 30 seconds left
        if self.secs == 60 or self.secs == 30:
            self.start_flash_timer()

        # In the last 10 seconds, display countdown in red
        if self.secs <= 10:
            self.countdownString.setStyleSheet(
                "QLabel { background-color : white; color : red; }")

        self.secs -= 1
        if self.secs < 0:
            self.stop_timer()
            self.countdownString.setStyleSheet(
                "QLabel { background-color : white; color : black; }")

    def stop_timer(self):
        """Stops the countdown timer"""
        self.countdownTimer.stop()
Пример #59
0
class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.image = QImage()
        self.dirty = False
        self.filename = None
        self.mirroredvertically = False
        self.mirroredhorizontally = False
        self.printer = None
        self.create_widgets()
        self.create_actions()
        self.load_settings()
        self.setWindowTitle("Image Changer")
        self.updateFileMenu()
        QTimer.singleShot(0, self.loadInitialFile)

    def create_widgets(self):
        self.imageLabel = QLabel()
        self.imageLabel.setMinimumSize(200, 200)
        self.imageLabel.setAlignment(Qt.AlignCenter)
        self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.setCentralWidget(self.imageLabel)

        logDockWidget = QDockWidget("Log", self)
        logDockWidget.setObjectName("LogDockWidget")
        logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea
                                      | Qt.RightDockWidgetArea)
        self.listWidget = QListWidget()
        logDockWidget.setWidget(self.listWidget)
        self.addDockWidget(Qt.RightDockWidgetArea, logDockWidget)

        self.sizeLabel = QLabel()
        self.sizeLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.addPermanentWidget(self.sizeLabel)
        status.showMessage("Ready", 5000)

    def create_actions(self):
        fileNewAction = self.createAction("&New...", self.fileNew,
                                          QKeySequence.New, "filenew",
                                          "Create an image file")
        fileOpenAction = self.createAction("&Open...", self.fileOpen,
                                           QKeySequence.Open, "fileopen",
                                           "Open an existing image file")
        fileSaveAction = self.createAction("&Save", self.fileSave,
                                           QKeySequence.Save, "filesave",
                                           "Save the image")
        fileSaveAsAction = self.createAction(
            "Save &As...",
            self.fileSaveAs,
            icon="filesaveas",
            tip="Save the image using a new name")
        filePrintAction = self.createAction("&Print", self.filePrint,
                                            QKeySequence.Print, "fileprint",
                                            "Print the image")
        fileQuitAction = self.createAction("&Quit", self.close, "Ctrl+Q",
                                           "filequit", "Close the application")
        editInvertAction = self.createAction("&Invert", None, "Ctrl+I",
                                             "editinvert",
                                             "Invert the image's colors", True)
        editInvertAction.toggled.connect(self.editInvert)
        editSwapRedAndBlueAction = self.createAction(
            "Sw&ap Red and Blue", None, "Ctrl+A", "editswap",
            "Swap the image's red and blue color components", True)
        editSwapRedAndBlueAction.toggled.connect(self.editSwapRedAndBlue)
        editZoomAction = self.createAction("&Zoom...", self.editZoom, "Alt+Z",
                                           "editzoom", "Zoom the image")
        mirrorGroup = QActionGroup(self)
        editUnMirrorAction = self.createAction("&Unmirror", None, "Ctrl+U",
                                               "editunmirror",
                                               "Unmirror the image", True)
        editUnMirrorAction.toggled.connect(self.editUnMirror)
        mirrorGroup.addAction(editUnMirrorAction)
        editMirrorHorizontalAction = self.createAction(
            "Mirror &Horizontally", None, "Ctrl+H", "editmirrorhoriz",
            "Horizontally mirror the image", True)
        editMirrorHorizontalAction.toggled.connect(self.editMirrorHorizontal)
        mirrorGroup.addAction(editMirrorHorizontalAction)
        editMirrorVerticalAction = self.createAction(
            "Mirror &Vertically", None, "Ctrl+V", "editmirrorvert",
            "Vertically mirror the image", True)
        editMirrorVerticalAction.toggled.connect(self.editMirrorVertical)
        mirrorGroup.addAction(editMirrorVerticalAction)
        editUnMirrorAction.setChecked(True)
        helpAboutAction = self.createAction("&About Image Changer",
                                            self.helpAbout)
        helpHelpAction = self.createAction("&Help", self.helpHelp,
                                           QKeySequence.HelpContents)

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenuActions = (fileNewAction, fileOpenAction, fileSaveAction,
                                fileSaveAsAction, None, filePrintAction,
                                fileQuitAction)
        self.fileMenu.aboutToShow.connect(self.updateFileMenu)
        editMenu = self.menuBar().addMenu("&Edit")
        self.addActions(
            editMenu,
            (editInvertAction, editSwapRedAndBlueAction, editZoomAction))
        mirrorMenu = editMenu.addMenu(QIcon(":/editmirror.png"), "&Mirror")
        self.addActions(mirrorMenu,
                        (editUnMirrorAction, editMirrorHorizontalAction,
                         editMirrorVerticalAction))
        helpMenu = self.menuBar().addMenu("&Help")
        self.addActions(helpMenu, (helpAboutAction, helpHelpAction))

        fileToolbar = self.addToolBar("File")
        fileToolbar.setObjectName("FileToolBar")
        self.addActions(fileToolbar,
                        (fileNewAction, fileOpenAction, fileSaveAsAction))
        editToolbar = self.addToolBar("Edit")
        editToolbar.setObjectName("EditToolBar")
        self.addActions(
            editToolbar,
            (editInvertAction, editSwapRedAndBlueAction, editUnMirrorAction,
             editMirrorVerticalAction, editMirrorHorizontalAction))
        self.zoomSpinBox = QSpinBox()
        self.zoomSpinBox.setRange(1, 400)
        self.zoomSpinBox.setSuffix(" %")
        self.zoomSpinBox.setValue(100)
        self.zoomSpinBox.setToolTip("Zoom the image")
        self.zoomSpinBox.setStatusTip(self.zoomSpinBox.toolTip())
        self.zoomSpinBox.setFocusPolicy(Qt.NoFocus)
        self.zoomSpinBox.valueChanged.connect(self.showImage)
        editToolbar.addWidget(self.zoomSpinBox)

        self.addActions(
            self.imageLabel,
            (editInvertAction, editSwapRedAndBlueAction, editUnMirrorAction,
             editMirrorVerticalAction, editMirrorHorizontalAction))

        self.resetableActions = ((editInvertAction,
                                  False), (editSwapRedAndBlueAction, False),
                                 (editUnMirrorAction, True))

    def load_settings(self):
        settings = QSettings()
        self.recentFiles = settings.value("RecentFiles").toStringList()
        self.restoreGeometry(
            settings.value("MainWindow/Geometry").toByteArray())
        self.restoreState(settings.value("MainWindow/State").toByteArray())

    def createAction(self,
                     text,
                     slot=None,
                     shortcut=None,
                     icon=None,
                     tip=None,
                     checkable=False):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/{0}.png".format(icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        if checkable:
            action.setCheckable(True)
        return action

    def addActions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def closeEvent(self, event):
        if self.okToContinue():
            settings = QSettings()
            filename = (QVariant(QString(self.filename))
                        if self.filename is not None else QVariant())
            settings.setValue("LastFile", filename)
            recentFiles = (QVariant(self.recentFiles)
                           if self.recentFiles else QVariant())
            settings.setValue("RecentFiles", recentFiles)
            settings.setValue("MainWindow/Geometry",
                              QVariant(self.saveGeometry()))
            settings.setValue("MainWindow/State", QVariant(self.saveState()))
        else:
            event.ignore()

    def okToContinue(self):
        if self.dirty:
            reply = QMessageBox.question(
                self, "Image Changer - Unsaved Changes",
                "Save unsaved changes?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                return self.fileSave()
        return True

    def loadInitialFile(self):
        settings = QSettings()
        fname = unicode(settings.value("LastFile").toString())
        if fname and QFile.exists(fname):
            self.loadFile(fname)

    def updateStatus(self, message):
        self.statusBar().showMessage(message, 5000)
        self.listWidget.addItem(message)
        if self.filename is not None:
            self.setWindowTitle("Image Changer - {0}[*]".format(
                os.path.basename(self.filename)))
        elif not self.image.isNull():
            self.setWindowTitle("Image Changer - Unnamed[*]")
        else:
            self.setWindowTitle("Image Changer[*]")
        self.setWindowModified(self.dirty)

    def updateFileMenu(self):
        self.fileMenu.clear()
        self.addActions(self.fileMenu, self.fileMenuActions[:-1])
        current = (QString(self.filename)
                   if self.filename is not None else None)
        recentFiles = []
        for fname in self.recentFiles:
            if fname != current and QFile.exists(fname):
                recentFiles.append(fname)
        if recentFiles:
            self.fileMenu.addSeparator()
            for i, fname in enumerate(recentFiles):
                action = QAction(
                    QIcon(":/icon.png"),
                    "&{0} {1}".format(i + 1,
                                      QFileInfo(fname).fileName()), self)
                action.setData(QVariant(fname))
                action.triggered.connect(self.loadFile)
                self.fileMenu.addAction(action)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.fileMenuActions[-1])

    def fileNew(self):
        if not self.okToContinue():
            return
        dialog = newimagedlg.NewImageDlg(self)
        if dialog.exec_():
            self.addRecentFile(self.filename)
            self.image = QImage()
            for action, check in self.resetableActions:
                action.setChecked(check)
            self.image = dialog.image()
            self.filename = None
            self.dirty = True
            self.showImage()
            self.sizeLabel.setText("{0} x {1}".format(self.image.width(),
                                                      self.image.height()))
            self.updateStatus("Created new image")

    def fileOpen(self):
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        formats = ([
            "*.{0}".format(unicode(format).lower())
            for format in QImageReader.supportedImageFormats()
        ])
        fname = unicode(
            QFileDialog.getOpenFileName(
                self, "Image Changer - Choose Image", dir,
                "Image files ({0})".format(" ".join(formats))))
        if fname:
            self.loadFile(fname)

    def loadFile(self, fname=None):
        if fname is None:
            action = self.sender()
            if isinstance(action, QAction):
                fname = unicode(action.data().toString())
                if not self.okToContinue():
                    return
            else:
                return
        if fname:
            self.filename = None
            image = QImage(fname)
            if image.isNull():
                message = "Failed to read {0}".format(fname)
            else:
                self.addRecentFile(fname)
                self.image = QImage()
                for action, check in self.resetableActions:
                    action.setChecked(check)
                self.image = image
                self.filename = fname
                self.showImage()
                self.dirty = False
                self.sizeLabel.setText("{0} x {1}".format(
                    image.width(), image.height()))
                message = "Loaded {0}".format(os.path.basename(fname))
            self.updateStatus(message)

    def addRecentFile(self, fname):
        if fname is None:
            return
        if not self.recentFiles.contains(fname):
            self.recentFiles.prepend(QString(fname))
            while self.recentFiles.count() > 9:
                self.recentFiles.takeLast()

    def fileSave(self):
        if self.image.isNull():
            return True
        if self.filename is None:
            return self.fileSaveAs()
        else:
            if self.image.save(self.filename, None):
                self.updateStatus("Saved as {0}".format(self.filename))
                self.dirty = False
                return True
            else:
                self.updateStatus("Failed to save {0}".format(self.filename))
                return False

    def fileSaveAs(self):
        if self.image.isNull():
            return True
        fname = self.filename if self.filename is not None else "."
        formats = ([
            "*.{0}".format(unicode(format).lower())
            for format in QImageWriter.supportedImageFormats()
        ])
        fname = unicode(
            QFileDialog.getSaveFileName(
                self, "Image Changer - Save Image", fname,
                "Image files ({0})".format(" ".join(formats))))
        if fname:
            if "." not in fname:
                fname += ".png"
            self.addRecentFile(fname)
            self.filename = fname
            return self.fileSave()
        return False

    def filePrint(self):
        if self.image.isNull():
            return
        if self.printer is None:
            self.printer = QPrinter(QPrinter.HighResolution)
            self.printer.setPageSize(QPrinter.Letter)
        form = QPrintDialog(self.printer, self)
        if form.exec_():
            painter = QPainter(self.printer)
            rect = painter.viewport()
            size = self.image.size()
            size.scale(rect.size(), Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(),
                                size.height())
            painter.drawImage(0, 0, self.image)

    def editInvert(self, on):
        if self.image.isNull():
            return
        self.image.invertPixels()
        self.showImage()
        self.dirty = True
        self.updateStatus("Inverted" if on else "Uninverted")

    def editSwapRedAndBlue(self, on):
        if self.image.isNull():
            return
        self.image = self.image.rgbSwapped()
        self.showImage()
        self.dirty = True
        self.updateStatus(
            ("Swapped Red and Blue" if on else "Unswapped Red and Blue"))

    def editUnMirror(self, on):
        if self.image.isNull():
            return
        if self.mirroredhorizontally:
            self.editMirrorHorizontal(False)
        if self.mirroredvertically:
            self.editMirrorVertical(False)

    def editMirrorHorizontal(self, on):
        if self.image.isNull():
            return
        self.image = self.image.mirrored(True, False)
        self.showImage()
        self.mirroredhorizontally = not self.mirroredhorizontally
        self.dirty = True
        self.updateStatus(
            ("Mirrored Horizontally" if on else "Unmirrored Horizontally"))

    def editMirrorVertical(self, on):
        if self.image.isNull():
            return
        self.image = self.image.mirrored(False, True)
        self.showImage()
        self.mirroredvertically = not self.mirroredvertically
        self.dirty = True
        self.updateStatus(
            ("Mirrored Vertically" if on else "Unmirrored Vertically"))

    def editZoom(self):
        if self.image.isNull():
            return
        percent, ok = QInputDialog.getInteger(self, "Image Changer - Zoom",
                                              "Percent:",
                                              self.zoomSpinBox.value(), 1, 400)
        if ok:
            self.zoomSpinBox.setValue(percent)

    def showImage(self, percent=None):
        if self.image.isNull():
            return
        if percent is None:
            percent = self.zoomSpinBox.value()
        factor = percent / 100.0
        width = self.image.width() * factor
        height = self.image.height() * factor
        image = self.image.scaled(width, height, Qt.KeepAspectRatio)
        self.imageLabel.setPixmap(QPixmap.fromImage(image))

    def helpAbout(self):
        QMessageBox.about(
            self, "About Image Changer", """<b>Image Changer</b> v {0}
                <p>Copyright &copy; 2008-14 Qtrac Ltd. 
                All rights reserved.
                <p>This application can be used to perform
                simple image manipulations.
                <p>Python {1} - Qt {2} - PyQt {3} on {4}""".format(
                __version__, platform.python_version(), QT_VERSION_STR,
                PYQT_VERSION_STR, platform.system()))

    def helpHelp(self):
        form = helpform.HelpForm("index.html", self)
        form.show()
Пример #60
0
 def __init__(self, parent, mainWindow, pid):
     QDialog.__init__(self, parent)
     self.translation()
     self.setWindowTitle(self.nameTitle)
     self.processusManager = ProcessusManager()
     self.pid = pid
     res = {}
     args = {}
     self.tabwidget = QTabWidget(self)
     stream = None
     proc = self.processusManager[int(str(self.pid))]
     res = proc.res
     args = proc.args
     if proc.streamOut == None:
         try:
             proc.streamOut = ''
             txt = proc.stream.get(0)
             proc.streamOut += txt
             while txt:
                 txt = proc.stream.get(0)
                 proc.streamOut += txt
         except Empty:
             pass
         if proc.streamOut and proc.streamOut != '':
             stream = proc.streamOut
     self.box = QVBoxLayout()
     self.setLayout(self.box)
     self.box.addWidget(self.tabwidget)
     self.dialogButtonsLayout = QHBoxLayout()
     self.dialogButtonsBox = QDialogButtonBox()
     self.dialogButtonsBox.setStandardButtons(QDialogButtonBox.Ok)
     self.connect(self.dialogButtonsBox, SIGNAL("accepted()"), self.accept)
     self.dialogButtonsLayout.addWidget(self.dialogButtonsBox)
     self.setMinimumSize(800, 600)
     if args and len(args) > 0:
         self.treeargs = VariantTreeWidget(self)
         self.treeargs.fillMap(self.treeargs, args)
         self.tabwidget.addTab(self.treeargs, self.argname)
         for i in [0, 1]:
             self.treeargs.resizeColumnToContents(i)
     if stream:
         textWidget = TextEdit(proc)
         textWidget.emit(SIGNAL("puttext"), proc.streamOut)
         self.tabwidget.addTab(textWidget, self.outputname)
     if proc.error_result != '':
         #XXX FIX for swig problem with results, this should not work in console anymore
         textWidget = QTextEdit()
         textWidget.setReadOnly(1)
         textWidget.append(proc.error_result)
         self.tabwidget.addTab(textWidget, self.tr('Error'))
     if len(res) > 0:
         self.treeres = VariantTreeWidget(self)
         self.treeres.fillMap(self.treeres, res)
         self.tabwidget.addTab(self.treeres, self.resname)
         for i in [0, 1]:
             self.treeres.resizeColumnToContents(i)
     else:
         label = QLabel(self.noResult)
         label.setAlignment(Qt.AlignCenter)
         self.tabwidget.addTab(label, self.resname)
     self.box.addLayout(self.dialogButtonsLayout)