Ejemplo n.º 1
0
class MultiVolumeVisualizationMIP(MultiVolumeVisualization):
	"""
	MultiVolumeVisualizationMIP is a visualization that shows
	MIP visualizations of both datasets and adds them
	together. It uses complementary colors for the datasets
	so that the visualization is white in the spots where
	they are the same.
	"""
	def __init__(self):
		super(MultiVolumeVisualizationMIP, self).__init__()

		self.fixedHue = 0

	@overrides(MultiVolumeVisualization)
	def getParameterWidget(self):
		self.hueSlider = QSlider(Qt.Horizontal)
		self.hueSlider.setMaximum(360)
		self.hueSlider.setValue(self.fixedHue)
		self.hueSlider.valueChanged.connect(self.valueChanged)

		layout = QGridLayout()
		layout.setAlignment(Qt.AlignTop)
		layout.addWidget(QLabel("Base hue"), 0, 0)
		layout.addWidget(self.hueSlider, 0, 1)

		widget = QWidget()
		widget.setLayout(layout)
		return widget

	@overrides(MultiVolumeVisualization)
	def setImageData(self, fixedImageData, movingImageData):
		self.fixedImageData = fixedImageData
		self.movingImageData = movingImageData

	@overrides(MultiVolumeVisualization)
	def updateTransferFunctions(self):
		self.fixedVolProp = self._createVolPropFromImageData(self.fixedImageData)
		self.movingVolProp = self._createVolPropFromImageData(self.movingImageData)

		self.updatedTransferFunction.emit()

	@overrides(MultiVolumeVisualization)
	def valueChanged(self, value):
		self.fixedHue = self.hueSlider.value()
		self.updateTransferFunctions()

	@overrides(MultiVolumeVisualization)
	def setMapper(self, mapper):
		self.mapper = mapper

	def _createVolPropFromImageData(self, imageData):
		volProp = vtkVolumeProperty()
		if imageData is not None:
			color, opacityFunction = CreateRangeFunctions(imageData)
		else:
			color, opacityFunction = CreateEmptyFunctions()
		volProp.SetColor(color)
		volProp.SetScalarOpacity(opacityFunction)

		return volProp
Ejemplo n.º 2
0
    def drawSpan(self, painter, rect):
        opt = QStyleOptionSlider()
        QSlider.initStyleOption(self, opt)

        # area
        groove = self.style().subControlRect(QStyle.CC_Slider, opt,
                                             QStyle.SC_SliderGroove, self)
        if opt.orientation == QtCore.Qt.Horizontal:
            groove.adjust(0, 0, -1, 0)
        else:
            groove.adjust(0, 0, 0, -1)

        # pen & brush
        painter.setPen(QPen(self.gradientLeftColor, 0))
        if opt.orientation == QtCore.Qt.Horizontal:
            self.setupPainter(painter, opt.orientation,
                              groove.center().x(), groove.top(),
                              groove.center().x(), groove.bottom())
        else:
            self.setupPainter(painter, opt.orientation, groove.left(),
                              groove.center().y(), groove.right(),
                              groove.center().y())

        # draw groove
        intersected = QtCore.QRectF(rect.intersected(groove))
        gradient = QLinearGradient(intersected.topLeft(),
                                   intersected.topRight())
        gradient.setColorAt(0, self.gradientLeft)
        gradient.setColorAt(1, self.gradientRight)
        painter.fillRect(intersected, gradient)
Ejemplo n.º 3
0
    def __init__(self, callback=None):
        self.callback = callback

        self.app = QApplication(sys.argv)

        self.vlayout = QVBoxLayout()

        self.button = QPushButton('light')
        self.button.pressed.connect(self._button_callback)
        self.button.setCheckable(True)
        self.button.setChecked(True)
        self.button.setStyleSheet('background-color: white')
        self.vlayout.addWidget(self.button)

        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.vlayout.addWidget(self.slider)

        self.dial = QDial()
        self.dial.setNotchesVisible(True)
        self.dial.setWrapping(True)
        self.vlayout.addWidget(self.dial)

        self.quit = QPushButton('Quit')
        self.quit.clicked.connect(self.app.quit)
        self.vlayout.addWidget(self.quit)

        self.group = QGroupBox('Fake Actuator')
        self.group.setLayout(self.vlayout)
Ejemplo n.º 4
0
 def __init__(self, parent = None):
     QSlider.__init__(self, QtCore.Qt.Horizontal, parent)
     self.rangeChanged.connect(self.updateRange)
     self.sliderReleased.connect(self.movePressedHandle)
     
     self.setStyle(QStyleFactory.create('Plastique'))
     
     
     self.floatMin = 0
     self.floatMax = 0
     self.floatStep = 0
     
     self.lower = 0
     self.upper = 0
     self.lowerPos = 0
     self.upperPos = 0
     self.offset = 0
     self.position = 0
     self.lastPressed = QxtSpanSlider.NoHandle
     self.upperPressed = QStyle.SC_None
     self.lowerPressed = QStyle.SC_None
     self.movement = QxtSpanSlider.FreeMovement
     self.mainControl = QxtSpanSlider.LowerHandle
     self.firstMovement = False
     self.blockTracking = False
     p = self.palette()
     p.setColor(QPalette.Dark, QtGui.QColor('black'))
     self.setPalette(p)
     self.gradientLeft = self.palette().color(QPalette.Dark).lighter(100)
     self.gradientRight = self.palette().color(QPalette.Dark).darker(200)
Ejemplo n.º 5
0
 def test_qslider_intervention(self):
     parent = QHBoxLayout()
     slider = QSlider()  # Don't specify orientation.
     ChildAdder.add(slider, 'fred', parent)
     # We promise to give it horizontal (the non-default) orientation.
     orient = slider.orientation()
     self.assertEqual(orient, Qt.Orientation.Horizontal)
Ejemplo n.º 6
0
class ActualFakeActuator(object):
    def __init__(self, callback=None):
        self.callback = callback

        self.app = QApplication(sys.argv)

        self.vlayout = QVBoxLayout()

        self.button = QPushButton('light')
        self.button.pressed.connect(self._button_callback)
        self.button.setCheckable(True)
        self.button.setChecked(True)
        self.button.setStyleSheet('background-color: white')
        self.vlayout.addWidget(self.button)

        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.vlayout.addWidget(self.slider)

        self.dial = QDial()
        self.dial.setNotchesVisible(True)
        self.dial.setWrapping(True)
        self.vlayout.addWidget(self.dial)

        self.quit = QPushButton('Quit')
        self.quit.clicked.connect(self.app.quit)
        self.vlayout.addWidget(self.quit)

        self.group = QGroupBox('Fake Actuator')
        self.group.setLayout(self.vlayout)

    def _button_callback(self):
        if self.button.isChecked():
            self.button.setStyleSheet('background-color: red')
        else:
            self.button.setStyleSheet('background-color: white')

    def light_on(self):
        return self.button.isChecked()

    def toggle_light(self, on):
        self.button.setChecked(on)

    def volume(self):
        return self.slider.value()

    def set_volume(self, value):
        self.slider.setValue(value)

    def position(self):
        return self.dial.value()

    def set_position(self, value):
        self.dial.setValue(value)

    def run(self):
        self.group.show()
        self.app.exec_()
Ejemplo n.º 7
0
    def getParameterWidget(self):
        """
		Returns a widget with sliders / fields with which properties of this
		volume property can be adjusted.
		:rtype: QWidget
		"""
        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setAlignment(Qt.AlignTop)

        self.sliders = []
        for index in range(7):
            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(1000)
            slider.setValue(
                int(
                    math.pow(self.sectionsOpacity[index], 1.0 / 3.0) *
                    slider.maximum()))
            slider.valueChanged.connect(self.valueChanged)
            self.sliders.append(slider)
            label = QLabel(self.sectionNames[index])
            label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            layout.addWidget(label, index, 0)
            layout.addWidget(slider, index, 1)

        try:
            from ColumnResizer import ColumnResizer
            columnResizer = ColumnResizer()
            columnResizer.addWidgetsFromLayout(layout, 0)
        except Exception, e:
            print e
Ejemplo n.º 8
0
    def initUi(self):

        #slider
        slider = QSlider(PySide.QtCore.Qt.Orientation.Horizontal, self)
        slider.setRange(0,2)
        slider.setTickInterval(1)
        slider.setValue(2)
        self.slider = slider

        #.. and corresponding label element
        label = QLabel(self)
        label.setText(self.activation_states[slider.value()])
        self.label = label
        
        #connections
        #PySide.QtCore.QObject.connect(slider, slider.valueChanged, self, self.update_label)
        #self.connect(slider.valueChanged, self.update_label())
        slider.valueChanged[int].connect(self.update_label)
        
        # layout
        lo = QVBoxLayout() 
        lo.addWidget( slider )
        lo.addWidget( label )


        self.setLayout(lo)
Ejemplo n.º 9
0
	def getParameterWidget(self):
		self.hueSlider = QSlider(Qt.Horizontal)
		self.hueSlider.setMaximum(360)
		self.hueSlider.setValue(self.fixedHue)
		self.hueSlider.valueChanged.connect(self.valueChanged)

		layout = QGridLayout()
		layout.setAlignment(Qt.AlignTop)
		layout.addWidget(QLabel("Base hue"), 0, 0)
		layout.addWidget(self.hueSlider, 0, 1)

		widget = QWidget()
		widget.setLayout(layout)
		return widget
	def getParameterWidget(self):
		"""
		Returns a widget with sliders / fields with which properties of this
		volume property can be adjusted.
		:rtype: QWidget
		"""
		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setAlignment(Qt.AlignTop)

		self.sliders = []
		for index in range(7):
			slider = QSlider(Qt.Horizontal)
			slider.setMinimum(0)
			slider.setMaximum(1000)
			slider.setValue(int(math.pow(self.sectionsOpacity[index], 1.0/3.0) * slider.maximum()))
			slider.valueChanged.connect(self.valueChanged)
			self.sliders.append(slider)
			label = QLabel(self.sectionNames[index])
			label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
			layout.addWidget(label, index, 0)
			layout.addWidget(slider, index, 1)

		try:
			from ColumnResizer import ColumnResizer
			columnResizer = ColumnResizer()
			columnResizer.addWidgetsFromLayout(layout, 0)
		except Exception, e:
			print e
Ejemplo n.º 11
0
    def __init__(self, parent=None):
        super(NumericBox, self).__init__(parent)
        self.slider = QSlider(Qt.Horizontal)

        self.spinner = self.spinner()
        self.spinner.setSingleStep(self.step)

        self.slider.setTickInterval(self.step * 100)
        self.slider.setSingleStep(self.step * 100)

        self.slider.sliderMoved.connect(
            lambda x: self.spinner.setValue(x / 100))
        self.spinner.valueChanged.connect(self.applyValue)

        self.setLayout(line(self.slider, self.spinner))
        self.layout().setStretch(1, 0)
Ejemplo n.º 12
0
 def _buildSetupPanel(self):
     '''
     Creates the sub-panel containing control widgets for re-initializing 
     the world on demand.
     '''
     self._percentLbl = QLabel("%")
     self._setupBtn = QPushButton("Setup", self._window)
     self._setupBtn.clicked.connect(self._onSetup)
     
     self._percentObstacleSldr = QSlider(Qt.Horizontal, self._window)
     self._percentObstacleSldr.setTickPosition(QSlider.TickPosition.TicksBelow)
     self._percentObstacleSldr.setTickInterval(10)
     self._percentObstacleSldr.setMinimum(0)
     self._percentObstacleSldr.setMaximum(100)
     self._percentObstacleSldr.valueChanged.connect(self._onPercentSlideChange)
     self._percentObstacleSldr.setValue(33)
     
     layout = QGridLayout()
     layout.addWidget(self._setupBtn, 0, 0, 1, 2)
     layout.addWidget(QLabel("Percent Occupied:"), 1, 0)
     layout.addWidget(self._percentLbl, 1, 1)
     layout.addWidget(self._percentObstacleSldr, 2, 0, 1, 2)
     
     grpBx = QGroupBox("Setup Controls")
     grpBx.setLayout(layout)
     grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
     return grpBx        
Ejemplo n.º 13
0
    def createDisplayFields(self):
        display_widget = QFrame()
        display_widget.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
        self.left_layout.addWidget(display_widget)
        self.display_layout = QHBoxLayout()

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

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

        self.transcript_slider = QSlider(QtCore.Qt.Horizontal, self)
        self.display_layout.addWidget(self.transcript_slider)
        self.transcript_slider.setMaximum(100)
        self.connect(self.transcript_slider,
                     QtCore.SIGNAL("sliderMoved(int)"), self.position_transcript)
        self.left_layout.addWidget(self.transcript_slider)
Ejemplo n.º 14
0
    def right_dock_create(self):
        self.btnonoff = QPushButton("Reset")
        self.slidvol = QSlider(Qt.Vertical)
        self.slidvol.setMinimum(0)
        self.slidvol.setMaximum(100)
        self.slidvol.setValue(50)
        self.labspeaker = QLabel()
        self.labspeaker.setPixmap(
            QPixmap(os.path.join(script_path, "../assets/speaker.png")))
        self.sndvolumelabel = QLabel()

        self.rightlayout = QVBoxLayout()
        self.rightlayout.addWidget(self.btnonoff)
        self.rightlayout.addWidget(self.slidvol)
        self.rightlayout.addWidget(self.sndvolumelabel)
        self.rightlayout.addWidget(self.labspeaker)
Ejemplo n.º 15
0
    def __init__(self):
        super(SliderWidget, self).__init__()

        self.label = QLabel()
        self.slider = QSlider(Qt.Horizontal)
        self.spinbox = QSpinBox()

        self.slider.valueChanged.connect(self.changedValue)
        self.spinbox.valueChanged.connect(self.changedValue)

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setVerticalSpacing(0)
        layout.addWidget(self.label, 0, 0)
        layout.addWidget(self.slider, 0, 1)
        layout.addWidget(self.spinbox, 0, 2)
        self.setLayout(layout)
Ejemplo n.º 16
0
 def __init__(self, text, minValue, maxValue, defaultValue ):
     
     QWidget.__init__( self )
     
     validator = QDoubleValidator(minValue, maxValue, 2, self )
     mainLayout = QHBoxLayout( self )
     
     checkBox = QCheckBox()
     checkBox.setFixedWidth( 115 )
     checkBox.setText( text )
     
     lineEdit = QLineEdit()
     lineEdit.setValidator( validator )
     lineEdit.setText( str(defaultValue) )
     
     slider = QSlider( QtCore.Qt.Horizontal )
     slider.setMinimum( minValue*100 )
     slider.setMaximum( maxValue*100 )
     slider.setValue( defaultValue )
     
     mainLayout.addWidget( checkBox )
     mainLayout.addWidget( lineEdit )
     mainLayout.addWidget( slider )
     
     QtCore.QObject.connect( slider, QtCore.SIGNAL( 'valueChanged(int)' ), self.syncWidthLineEdit )
     QtCore.QObject.connect( lineEdit, QtCore.SIGNAL( 'textChanged(QString)' ), self.syncWidthSlider )
     QtCore.QObject.connect( checkBox, QtCore.SIGNAL( "clicked()" ), self.updateEnabled )
     
     self.checkBox = checkBox
     self.slider = slider
     self.lineEdit = lineEdit
     
     self.updateEnabled()
    def getParameterWidget(self):
        self.labelFixedOpacity = QLabel("Fixed:")
        self.labelFixedOpacity.setAlignment(Qt.AlignRight)
        self.labelMovingOpacity = QLabel("Moving:")
        self.labelMovingOpacity.setAlignment(Qt.AlignRight)

        self.sliderFixedOpacity = QSlider(Qt.Horizontal)
        self.sliderFixedOpacity.setValue(
            pow(self.fixedOpacity, 1.0 / 3.0) * 100.0)

        self.sliderMovingOpacity = QSlider(Qt.Horizontal)
        self.sliderMovingOpacity.setValue(
            pow(self.movingOpacity, 1.0 / 3.0) * 100.0)

        self.blendTypeComboBox = QComboBox()
        self.blendTypeComboBox.addItem("Default additive blend")
        self.blendTypeComboBox.addItem("Difference blend")
        self.blendTypeComboBox.currentIndexChanged.connect(self.valueChanged)

        # Be sure to connect after the values are set...
        self.sliderFixedOpacity.valueChanged.connect(self.valueChanged)
        self.sliderMovingOpacity.valueChanged.connect(self.valueChanged)

        groupLayout = QGridLayout()
        groupLayout.setAlignment(Qt.AlignTop)
        groupLayout.addWidget(self.labelFixedOpacity, 0, 0)
        groupLayout.addWidget(self.sliderFixedOpacity, 0, 1)
        groupLayout.addWidget(self.labelMovingOpacity, 1, 0)
        groupLayout.addWidget(self.sliderMovingOpacity, 1, 1)

        groupBox = QGroupBox()
        groupBox.setTitle("Opacity:")
        groupBox.setLayout(groupLayout)

        layout = QGridLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(groupBox)

        widget = QWidget()
        widget.setLayout(layout)
        return widget
Ejemplo n.º 18
0
 def __init__(self, *args, **kwargs ):
     
     self.minimum = 1
     self.maximum = 100
     self.lineEditMaximum = 10000
     
     QMainWindow.__init__( self, *args, **kwargs )
     self.installEventFilter( self )
     #self.setWindowFlags( QtCore.Qt.Drawer )
     self.setWindowTitle( Window_global.title )
     
     widgetMain = QWidget()
     layoutVertical = QVBoxLayout( widgetMain )
     self.setCentralWidget( widgetMain )
     
     layoutSlider = QHBoxLayout()
     lineEdit     = QLineEdit(); lineEdit.setFixedWidth( 100 )
     lineEdit.setText( str( 1 ) )
     validator    = QIntValidator(self.minimum, self.lineEditMaximum, self)
     lineEdit.setValidator( validator )
     slider       = QSlider(); slider.setOrientation( QtCore.Qt.Horizontal )
     slider.setMinimum( self.minimum )
     slider.setMaximum( self.maximum )
     layoutSlider.addWidget( lineEdit )
     layoutSlider.addWidget( slider )
     layoutAngle = QVBoxLayout()
     checkBox = QCheckBox( 'Connect Angle By Tangent' )
     layoutVector = QHBoxLayout()
     leVx = QLineEdit(); leVx.setText( str( 1.000 ) ); leVx.setEnabled( False )
     leVx.setValidator( QDoubleValidator( -100, 100, 5, self ) )
     leVy = QLineEdit(); leVy.setText( str( 0.000 ) ); leVy.setEnabled( False )
     leVy.setValidator( QDoubleValidator( -100, 100, 5, self ) )
     leVz = QLineEdit(); leVz.setText( str( 0.000 ) ); leVz.setEnabled( False )
     leVz.setValidator( QDoubleValidator( -100, 100, 5, self ) )
     layoutAngle.addWidget( checkBox )
     layoutAngle.addLayout( layoutVector )
     layoutVector.addWidget( leVx ); layoutVector.addWidget( leVy ); layoutVector.addWidget( leVz )
     button       = QPushButton( 'Create' )
     
     layoutVertical.addLayout( layoutSlider )
     layoutVertical.addLayout( layoutAngle )
     layoutVertical.addWidget( button )
     
     QtCore.QObject.connect( slider, QtCore.SIGNAL('valueChanged(int)'),   self.sliderValueChanged )
     QtCore.QObject.connect( lineEdit, QtCore.SIGNAL('textEdited(QString)'), self.lineEditValueChanged )
     QtCore.QObject.connect( button, QtCore.SIGNAL('clicked()'), Functions.createPointOnCurve )
     QtCore.QObject.connect( checkBox, QtCore.SIGNAL( 'clicked()'), Functions.setAngleEnabled )
     self.slider = slider
     self.lineEdit = lineEdit
     
     Window_global.slider = slider
     Window_global.button = button
     Window_global.checkBox = checkBox
     Window_global.leVx = leVx
     Window_global.leVy = leVy
     Window_global.leVz = leVz
Ejemplo n.º 19
0
class NumericBox(QFrame):
    """
    A box with a spinner and a slider to allow easier value manipulation by user
    """
    valueChanged = Signal(float)
    spinner = QDoubleSpinBox
    step = 0.1

    def __init__(self, parent=None):
        super(NumericBox, self).__init__(parent)
        self.slider = QSlider(Qt.Horizontal)

        self.spinner = self.spinner()
        self.spinner.setSingleStep(self.step)

        self.slider.setTickInterval(self.step * 100)
        self.slider.setSingleStep(self.step * 100)

        self.slider.sliderMoved.connect(
            lambda x: self.spinner.setValue(x / 100))
        self.spinner.valueChanged.connect(self.applyValue)

        self.setLayout(line(self.slider, self.spinner))
        self.layout().setStretch(1, 0)

    def applyValue(self, value):
        self.valueChanged.emit(value)
        self.slider.setValue(value * 100)

    def setValue(self, value):
        self.spinner.setValue(value)
        self.slider.setValue(value * 100)

    def setRange(self, mini, maxi):
        self.spinner.setRange(mini, maxi)
        self.slider.setRange(mini * 100, maxi * 100)

    def value(self):
        return self.spinner.value()
Ejemplo n.º 20
0
    def __init__(self):
        super(SliderFloatWidget, self).__init__()

        self.label = QLabel()
        self.slider = QSlider(Qt.Horizontal)
        self.spinbox = QDoubleSpinBox()

        self.slider.valueChanged.connect(self.changedValueFromSlider)
        self.spinbox.valueChanged.connect(self.changedValueFromSpinBox)

        # Keep track of whether one of the values was changed
        # By setting the value of the slider and the spinbox, valueChanged
        # events are fired. These events have to be ignored
        self._changed = False

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setVerticalSpacing(0)
        layout.addWidget(self.label, 0, 0)
        layout.addWidget(self.slider, 0, 1)
        layout.addWidget(self.spinbox, 0, 2)
        self.setLayout(layout)
class SliderWidget(QWidget):
	"""
	SliderWidget
	"""
	valueChanged = Signal(int)

	def __init__(self):
		super(SliderWidget, self).__init__()

		self.label = QLabel()
		self.slider = QSlider(Qt.Horizontal)
		self.spinbox = QSpinBox()

		self.slider.valueChanged.connect(self.changedValue)
		self.spinbox.valueChanged.connect(self.changedValue)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setVerticalSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.slider, 0, 1)
		layout.addWidget(self.spinbox, 0, 2)
		self.setLayout(layout)

	def setName(self, name):
		"""
		Set the name for the slider
		"""
		self.label.setText(name)

	def setRange(self, range):
		"""
		Set the range for the value
		"""
		self.slider.setMinimum(range[0])
		self.spinbox.setMinimum(range[0])
		self.slider.setMaximum(range[1])
		self.spinbox.setMaximum(range[1])

	def setValue(self, value):
		"""
		Set the value for the slider and the spinbox
		"""
		self.slider.setValue(value)
		self.spinbox.setValue(value)

	def value(self):
		return self.slider.value()

	@Slot(int)
	def changedValue(self, value):
		self.setValue(value)
		self.valueChanged.emit(value)
Ejemplo n.º 22
0
class NumericBox(QFrame):
    """
    A box with a spinner and a slider to allow easier value manipulation by user
    """
    valueChanged = Signal(float)
    spinner = QDoubleSpinBox
    step = 0.1

    def __init__(self, parent=None):
        super(NumericBox, self).__init__(parent)
        self.slider = QSlider(Qt.Horizontal)

        self.spinner = self.spinner()
        self.spinner.setSingleStep(self.step)

        self.slider.setTickInterval(self.step * 100)
        self.slider.setSingleStep(self.step * 100)

        self.slider.sliderMoved.connect(lambda x: self.spinner.setValue(x / 100))
        self.spinner.valueChanged.connect(self.applyValue)

        self.setLayout(line(self.slider, self.spinner))
        self.layout().setStretch(1, 0)

    def applyValue(self, value):
        self.valueChanged.emit(value)
        self.slider.setValue(value * 100)

    def setValue(self, value):
        self.spinner.setValue(value)
        self.slider.setValue(value * 100)

    def setRange(self, mini, maxi):
        self.spinner.setRange(mini, maxi)
        self.slider.setRange(mini * 100, maxi * 100)

    def value(self):
        return self.spinner.value()
Ejemplo n.º 23
0
class SliderWidget(QWidget):
    """
	SliderWidget
	"""
    valueChanged = Signal(int)

    def __init__(self):
        super(SliderWidget, self).__init__()

        self.label = QLabel()
        self.slider = QSlider(Qt.Horizontal)
        self.spinbox = QSpinBox()

        self.slider.valueChanged.connect(self.changedValue)
        self.spinbox.valueChanged.connect(self.changedValue)

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setVerticalSpacing(0)
        layout.addWidget(self.label, 0, 0)
        layout.addWidget(self.slider, 0, 1)
        layout.addWidget(self.spinbox, 0, 2)
        self.setLayout(layout)

    def setName(self, name):
        """
		Set the name for the slider
		"""
        self.label.setText(name)

    def setRange(self, range):
        """
		Set the range for the value
		"""
        self.slider.setMinimum(range[0])
        self.spinbox.setMinimum(range[0])
        self.slider.setMaximum(range[1])
        self.spinbox.setMaximum(range[1])

    def setValue(self, value):
        """
		Set the value for the slider and the spinbox
		"""
        self.slider.setValue(value)
        self.spinbox.setValue(value)

    def value(self):
        return self.slider.value()

    @Slot(int)
    def changedValue(self, value):
        self.setValue(value)
        self.valueChanged.emit(value)
Ejemplo n.º 24
0
    def set_dip_count(self, number):
        for i in range(number):
            dip = QSlider(self)
            dip.setMinimum(0)
            dip.setMaximum(1)
            dip.valueChanged.connect(self.__on_changed)
            self._layout.addWidget(dip)

            self._dips.append(dip)
Ejemplo n.º 25
0
    def __init__(self, parent=None):
        super(NumericBox, self).__init__(parent)
        self.slider = QSlider(Qt.Horizontal)

        self.spinner = self.spinner()
        self.spinner.setSingleStep(self.step)

        self.slider.setTickInterval(self.step * 100)
        self.slider.setSingleStep(self.step * 100)

        self.slider.sliderMoved.connect(lambda x: self.spinner.setValue(x / 100))
        self.spinner.valueChanged.connect(self.applyValue)

        self.setLayout(line(self.slider, self.spinner))
        self.layout().setStretch(1, 0)
Ejemplo n.º 26
0
    def createRotableGroupBox(self):
        self.rotableGroupBox = QGroupBox("Rotable Widgets")
        
        self.rotableWidgets.append(QSpinBox())
        self.rotableWidgets.append(QSlider())
        self.rotableWidgets.append(QDial())
        self.rotableWidgets.append(QProgressBar())
        count = len(self.rotableWidgets)
        for i in range(count):
            self.rotableWidgets[i].valueChanged[int].\
                connect(self.rotableWidgets[(i+1) % count].setValue)

        self.rotableLayout = QGridLayout()    
        self.rotableGroupBox.setLayout(self.rotableLayout)

        self.rotateWidgets()
	def __init__(self):
		super(SliderWidget, self).__init__()

		self.label = QLabel()
		self.slider = QSlider(Qt.Horizontal)
		self.spinbox = QSpinBox()

		self.slider.valueChanged.connect(self.changedValue)
		self.spinbox.valueChanged.connect(self.changedValue)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setVerticalSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.slider, 0, 1)
		layout.addWidget(self.spinbox, 0, 2)
		self.setLayout(layout)
Ejemplo n.º 28
0
    def __init__(self,
                 parent,
                 North="Up",
                 East="Right",
                 South="Down",
                 West="Left",
                 BoxLabel='Power',
                 valueName='Position'):
        QWidget.__init__(self)
        self.North = North
        self.East = East
        self.South = South
        self.West = West
        self.boxLabel = BoxLabel
        buttonLayout = QGridLayout(self)
        northButton = QPushButton(self.North, self)
        #        northbutton.click(actionscript)

        eastButton = QPushButton(self.East, self)

        southButton = QPushButton(self.South, self)

        westButton = QPushButton(self.West, self)

        speedSlider = QSlider()
        speedSlider.setTickPosition(QSlider.TicksRight)
        speedSlider.setTickInterval(10)
        speedSlider.TicksRight
        sliderPosition = QSpinBox()
        sliderPosition.setRange(0, 101)
        sliderLabel = QLabel(self.boxLabel)
        speedSlider.valueChanged.connect(sliderPosition.setValue)
        sliderPosition.valueChanged.connect(speedSlider.setValue)
        SliderValue = speedSlider.value()
        speedSlider.valueChanged.connect(self.printValue)

        #Needs work to fix the layout issues......
        buttonLayout.addWidget(northButton, 1, 1)
        buttonLayout.addWidget(eastButton, 2, 2)
        buttonLayout.addWidget(westButton, 2, 0)
        buttonLayout.addWidget(southButton, 3, 1)
        buttonLayout.addWidget(sliderPosition, 1, 3)
        buttonLayout.addWidget(sliderLabel, 0, 3)
        buttonLayout.addWidget(speedSlider, 2, 3, 3, 3)

        self.setLayout(buttonLayout)
Ejemplo n.º 29
0
    def __init__(self, parent=None, name=None):
        QWidget.__init__(self, parent)
        self.name = name
        self.set_format('.3f')

        # create widgets
        self.label = QLabel()
        self.slider = QSlider(QtCore.Qt.Orientation.Horizontal)        
        self.slider.valueChanged.connect(self._update_label)
        
        # set default values
        self.set_range(0, 100)
        self.set_value(50)        

        # create layout for the entire widget
        box = QVBoxLayout()
        box.addWidget(self.label)
        box.addWidget(self.slider)        
        self.setLayout(box)
	def __init__(self):
		super(SliderFloatWidget, self).__init__()

		self.label = QLabel()
		self.slider = QSlider(Qt.Horizontal)
		self.spinbox = QDoubleSpinBox()

		self.slider.valueChanged.connect(self.changedValueFromSlider)
		self.spinbox.valueChanged.connect(self.changedValueFromSpinBox)

		# Keep track of whether one of the values was changed
		# By setting the value of the slider and the spinbox, valueChanged
		# events are fired. These events have to be ignored
		self._changed = False

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setVerticalSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.slider, 0, 1)
		layout.addWidget(self.spinbox, 0, 2)
		self.setLayout(layout)
Ejemplo n.º 31
0
    def __init__(self, text, minValue, maxValue, defaultValue):

        QWidget.__init__(self)

        validator = QDoubleValidator(minValue, maxValue, 2, self)
        mainLayout = QHBoxLayout(self)

        checkBox = QCheckBox()
        checkBox.setFixedWidth(115)
        checkBox.setText(text)

        lineEdit = QLineEdit()
        lineEdit.setValidator(validator)
        lineEdit.setText(str(defaultValue))

        slider = QSlider(QtCore.Qt.Horizontal)
        slider.setMinimum(minValue * 100)
        slider.setMaximum(maxValue * 100)
        slider.setValue(defaultValue)

        mainLayout.addWidget(checkBox)
        mainLayout.addWidget(lineEdit)
        mainLayout.addWidget(slider)

        QtCore.QObject.connect(slider, QtCore.SIGNAL('valueChanged(int)'),
                               self.syncWidthLineEdit)
        QtCore.QObject.connect(lineEdit, QtCore.SIGNAL('textChanged(QString)'),
                               self.syncWidthSlider)
        QtCore.QObject.connect(checkBox, QtCore.SIGNAL("clicked()"),
                               self.updateEnabled)

        self.checkBox = checkBox
        self.slider = slider
        self.lineEdit = lineEdit

        self.updateEnabled()
Ejemplo n.º 32
0
 def __init__(self):
     super(Layer, self).__init__()
     self.orientation = Quaternion()
     self.picked = None
     self.show = QCheckBox()
     self.show.setChecked(True)
     self.alpha_slider = QSlider(QtCore.Qt.Orientation.Horizontal)
     self.alpha_slider.setRange(0, 1024)
     self.alpha_slider.setValue(1024)
     self.alpha_number = QDoubleSpinBox()
     self.alpha_number.setDecimals(3)
     self.alpha_number.setSingleStep(0.01)
     self.alpha_number.setRange(0, 1)
     self.alpha_number.setValue(1)
     self.alpha_slider.valueChanged.connect(self._alphaSliderChanged)
     self.alpha_number.valueChanged.connect(self._alphaNumberChanged)
     self.move = QCheckBox()
     self.move.setChecked(True)
     self.quat = QLineEdit()
     font = QFont('monospace')
     font.setStyleHint(QFont.TypeWriter)
     self.quat.setFont(font)
     default_quat = '+0.000, +1.000, +0.000, +0.000'
     margins = self.quat.textMargins()
     self.quat.setFixedWidth(
         # HACK -------------------------------------------v
         QFontMetrics(self.quat.font()).width(default_quat + '  ') +
         margins.left() + margins.right()
     )
     self.quat.setInputMask('#0.000, #0.000, #0.000, #0.000')
     self.quat.setMaxLength(30)
     self.quat.setText(default_quat)
     self.quat.editingFinished.connect(self._orientationChanged)
     self.nbytes = QLabel()
     self.nbytes.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
     self.nbytes.setText('0')
     self.label = QLabel()
     self.label.setText('<empty>')
Ejemplo n.º 33
0
    def __init__(self, parent=None):
        # This view is not visible
        super(SelectorView, self).__init__(None)

        self._updating_selection = False

        layout = QHBoxLayout()
        layout.addWidget(QLabel("Select by size"))

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setMinimum(-1)
        self.slider.setMaximum(1)
        self.slider.setTickInterval(1)
        self.slider.setSingleStep(1)
        self.slider.setEnabled(False)

        self.slider.valueChanged.connect(self._slider_changed)

        # Slider has stretch greater than zero to force left-alignment
        layout.addWidget(self.slider, stretch=1)

        self.widget = QWidget(parent)
        self.widget.setLayout(layout)
    def __init__(self, parent, North="Up", East="Right", South="Down", West="Left",BoxLabel='Power', valueName='Position'):
        QWidget.__init__(self)
        self.North = North
        self.East= East
        self.South = South
        self.West = West
        self.boxLabel = BoxLabel
        buttonLayout = QGridLayout(self)
        northButton = QPushButton(self.North, self)
#        northbutton.click(actionscript)
        
        eastButton = QPushButton(self.East, self)

        southButton = QPushButton(self.South, self)
        
        westButton = QPushButton(self.West, self)
        
        speedSlider = QSlider()
        speedSlider.setTickPosition(QSlider.TicksRight)
        speedSlider.setTickInterval(10)
        speedSlider.TicksRight
        sliderPosition = QSpinBox()
        sliderPosition.setRange(0,101)
        sliderLabel = QLabel(self.boxLabel)
        speedSlider.valueChanged.connect(sliderPosition.setValue)
        sliderPosition.valueChanged.connect(speedSlider.setValue)
        SliderValue = speedSlider.value()
        speedSlider.valueChanged.connect(self.printValue)
        
        #Needs work to fix the layout issues......
        buttonLayout.addWidget(northButton, 1, 1)
        buttonLayout.addWidget(eastButton, 2, 2)
        buttonLayout.addWidget(westButton, 2, 0)
        buttonLayout.addWidget(southButton, 3, 1)
        buttonLayout.addWidget(sliderPosition,1, 3)
        buttonLayout.addWidget(sliderLabel, 0, 3)
        buttonLayout.addWidget(speedSlider, 2, 3, 3,3)
        
        self.setLayout(buttonLayout)
Ejemplo n.º 35
0
    def __init__(self):
        QMainWindow.__init__(self)
        # filename = QFileDialog.getOpenFileName(self, "Open File")[0]
        # self.setWindowTitle(os.path.basename(filename))
        # self.transcript = StepperTranscript(filename)
        self.transcript = None
        self.outer_widget = QWidget()
        self.setCentralWidget(self.outer_widget)
        outer_layout = QHBoxLayout()
        self.outer_widget.setLayout(outer_layout)
        self.setLayout(outer_layout)
        left_layout = QVBoxLayout()
        outer_layout.addLayout(left_layout)

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

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

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

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

        button_widget = TranscriptButtons(self)

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

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

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

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

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

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

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

        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_0), self, self.play_or_pause)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_5), self, self.play_or_pause)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_7), self, self.go_to_previous_turn)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_9), self, self.go_to_next_turn)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_4), self, self.player.jump_video_backward)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_6), self, self.player.jump_video_forward)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_2), self, self.player.reset_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_1), self, self.player.decrease_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_3), self, self.player.increase_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_G), self, self.sync_video_and_play)
Ejemplo n.º 36
0
class StepperWindow(QMainWindow):


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

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

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

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

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

        button_widget = TranscriptButtons(self)

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

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

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

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

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

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

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

        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_0), self, self.play_or_pause)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_5), self, self.play_or_pause)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_7), self, self.go_to_previous_turn)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_9), self, self.go_to_next_turn)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_4), self, self.player.jump_video_backward)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_6), self, self.player.jump_video_forward)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_2), self, self.player.reset_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_1), self, self.player.decrease_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_3), self, self.player.increase_rate)
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_G), self, self.sync_video_and_play)

    def createKeypadButtons(self, stepperWindow):

        self.keypadWidget = QtGui.QWidget()
        self.keypadWidget.setGeometry(QtCore.QRect(0, 0, 191, 101))
        self.keypadWidget.setMinimumSize(QtCore.QSize(191, 101))
        self.keypadWidget.setMaximumSize(QtCore.QSize(191, 101))
        self.keypadWidget.setObjectName("gridLayoutWidget")
        self.keypadGridLayout = QtGui.QGridLayout(self.keypadWidget)
        self.keypadGridLayout.setContentsMargins(0, 0, 0, 0)
        self.keypadGridLayout.setObjectName("keypadGridLayout")
        self.fasterbutton = QtGui.QPushButton(self.keypadWidget)
        self.fasterbutton.setObjectName("fasterbutton")
        self.keypadGridLayout.addWidget(self.fasterbutton, 2, 2, 1, 1)
        self.jumpforwardbutton = QtGui.QPushButton(self.keypadWidget)
        self.jumpforwardbutton.setObjectName("jumpforwardbutton")
        self.keypadGridLayout.addWidget(self.jumpforwardbutton, 1, 2, 1, 1)
        self.normalbutton = QtGui.QPushButton(self.keypadWidget)
        self.normalbutton.setObjectName("normalbutton")
        self.keypadGridLayout.addWidget(self.normalbutton, 2, 1, 1, 1)
        self.NextButton = QtGui.QPushButton(self.keypadWidget)
        self.NextButton.setObjectName("NextButton")
        self.keypadGridLayout.addWidget(self.NextButton, 0, 2, 1, 1)
        self.jumpbackbutton = QtGui.QPushButton(self.keypadWidget)
        self.jumpbackbutton.setObjectName("jumpbackbutton")
        self.keypadGridLayout.addWidget(self.jumpbackbutton, 1, 0, 1, 1)
        self.playButton = QtGui.QPushButton(self.keypadWidget)
        self.playButton.setObjectName("playButton")
        self.keypadGridLayout.addWidget(self.playButton, 1, 1, 1, 1)
        self.PreviousButton = QtGui.QPushButton(self.keypadWidget)
        self.PreviousButton.setObjectName("PreviousButton")
        self.keypadGridLayout.addWidget(self.PreviousButton, 0, 0, 1, 1)
        self.slowerbutton = QtGui.QPushButton(self.keypadWidget)
        self.slowerbutton.setObjectName("slowerbutton")
        self.keypadGridLayout.addWidget(self.slowerbutton, 2, 0, 1, 1)
        self.gotobutton = QtGui.QPushButton(self.keypadWidget)
        self.gotobutton.setObjectName("gotobutton")
        self.keypadGridLayout.addWidget(self.gotobutton, 0, 1, 1, 1)

        self.retranslateKeypadUi(stepperWindow)
        QtCore.QObject.connect(self.NextButton, QtCore.SIGNAL("clicked()"), stepperWindow.go_to_next_turn)
        QtCore.QObject.connect(self.PreviousButton, QtCore.SIGNAL("clicked()"), stepperWindow.go_to_previous_turn)
        QtCore.QObject.connect(self.gotobutton, QtCore.SIGNAL("clicked()"), stepperWindow.sync_video_and_play)
        QtCore.QObject.connect(self.jumpbackbutton, QtCore.SIGNAL("clicked()"), stepperWindow.jump_back)
        QtCore.QObject.connect(self.jumpforwardbutton, QtCore.SIGNAL("clicked()"), stepperWindow.jump_forward)
        QtCore.QObject.connect(self.slowerbutton, QtCore.SIGNAL("clicked()"), stepperWindow.slower)
        QtCore.QObject.connect(self.normalbutton, QtCore.SIGNAL("clicked()"), stepperWindow.normal_speed)
        QtCore.QObject.connect(self.fasterbutton, QtCore.SIGNAL("clicked()"), stepperWindow.faster)
        QtCore.QObject.connect(self.playButton, QtCore.SIGNAL("clicked()"), stepperWindow.play_or_pause)
        QtCore.QMetaObject.connectSlotsByName(stepperWindow)

    def retranslateKeypadUi(self, stepperWindow):
        stepperWindow.setWindowTitle(QtGui.QApplication.translate("stepperWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.fasterbutton.setText(QtGui.QApplication.translate("stepperWindow", "Faster", None, QtGui.QApplication.UnicodeUTF8))
        self.jumpforwardbutton.setText(QtGui.QApplication.translate("stepperWindow", "Jump+", None, QtGui.QApplication.UnicodeUTF8))
        self.normalbutton.setText(QtGui.QApplication.translate("stepperWindow", "Normal", None, QtGui.QApplication.UnicodeUTF8))
        self.NextButton.setText(QtGui.QApplication.translate("stepperWindow", "Next", None, QtGui.QApplication.UnicodeUTF8))
        self.jumpbackbutton.setText(QtGui.QApplication.translate("stepperWindow", "Jump-", None, QtGui.QApplication.UnicodeUTF8))
        self.playButton.setText(QtGui.QApplication.translate("stepperWindow", "Play", None, QtGui.QApplication.UnicodeUTF8))
        self.PreviousButton.setText(QtGui.QApplication.translate("stepperWindow", "Prev", None, QtGui.QApplication.UnicodeUTF8))
        self.slowerbutton.setText(QtGui.QApplication.translate("stepperWindow", "Slower", None, QtGui.QApplication.UnicodeUTF8))
        self.gotobutton.setText(QtGui.QApplication.translate("stepperWindow", "GoTo", None, QtGui.QApplication.UnicodeUTF8))

    def open_transcript(self):
        filename = QFileDialog.getOpenFileName(self, "Open File")[0]
        self.setWindowTitle(os.path.basename(filename))
        self.transcript = StepperTranscript(filename)
        self.display_current_turn()


    def position_transcript(self, position):
        self.transcript.move_to_position(1.0 * position / 100)
        self.display_current_turn()

    def go_to_next_turn(self):
        self.transcript.go_to_next()
        self.display_current_turn()

    def update_time(self):
        self.turn["time"] = self.time_field.value

    def update_speaker(self):
        self.turn["speaker"] = self.speaker_field.value

    def update_utterance(self):
        self.turn["utterance"] = self.utt_field.value

    def go_to_previous_turn(self):
        self.transcript.go_to_previous()
        self.display_current_turn()

    def display_current_turn(self):
        self.turn = self.transcript.current_turn()
        self.time_field.value = self.turn["time"]
        self.speaker_field.value = self.turn["speaker"]
        self.utt_field.value = self.turn["utterance"]

    def delete_current_turn(self):
        self.transcript.delete_current()
        self.display_current_turn()

    def save_file_as(self):
        filename = QFileDialog.getSaveFileName(self, "File name for save")[0]
        self.save_file_name = filename
        self.transcript.commit_all()
        self.transcript.save_as_csv(filename)

    def save_file(self):
        if self.save_file_name is None:
            self.save_file_as()
        else:
            self.transcript.commit_all()
            self.transcript.save_as_csv(self.save_file_name)

    def revert_current_and_redisplay(self):
        self.transcript.revert_current()
        self.display_current_turn()

    def open_video(self):
        # self.player = Player()
        # self.player.show()
        # self.player.resize(640, 480)
        self.player.OpenFile()

    def play_or_pause(self):
        self.player.PlayPause()

    def slower(self):
        self.player.decrease_rate()

    def faster(self):
        self.player.increase_rate()

    def normal_speed(self):
        self.player.reset_rate()

    def fill_time_code(self):
        self.time_field.value = self.player.getCurrentTimeCode()

    def sync_video_and_play(self):
        self.sync_video()
        if not self.player.mediaplayer.is_playing():
            self.play_or_pause()

    def jump_back(self):
        self.player.jump_video_backward()

    def jump_forward(self):
        self.player.jump_video_forward()

    def sync_video(self):
        self.player.setTimeCode(self.time_field.value)

    def insert_before(self):
        new_uid = self.transcript.insert_new(self.transcript.current_uid)
        self.display_current_turn()

    def insert_after(self):
        new_uid = self.transcript.insert_new(self.transcript.current_uid, "after")
        self.display_current_turn()

    def closeEvent(self, event):
        msgBox = QMessageBox()
        msgBox.setText("Do you want to save before quitting?")
        msgBox.setInformativeText("Do you want to save your changes?")
        msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
        msgBox.setDefaultButton(QMessageBox.Save)
        ret = msgBox.exec_()
        if ret == QMessageBox.Save:
            self.save_file()
            event.accept()
        elif ret == QMessageBox.Discard:
            event.accept()
        else:
            event.ignore()

    def commit(self):
        self.transcript.commit_current()

    def commit_all(self):
        self.transcript.commit_all()
    def __init__(self):
        super(DataInspector, self).__init__()

        self.slider_width = +300

        self.main_widget = QWidget(self)
        self.setCentralWidget(self.main_widget)
        self.render_widget = RenderWidget()

        # Create interface actions
        self.action_load_data = QAction('Load data set',
                                        self,
                                        shortcut='Ctrl+O')
        self.action_load_data.setIcon(QIcon("images/AddButton.png"))
        self.action_load_data.triggered.connect(self.load_file)
        self.action_show_simple = QAction('Switch to simple rendering',
                                          self,
                                          shortcut='Ctrl+1')
        self.action_show_simple.setText("Simple")
        self.action_show_simple.triggered.connect(self.switch_to_simple)
        self.action_show_ct = QAction('Switch to CT rendering',
                                      self,
                                      shortcut='Ctrl+2')
        self.action_show_ct.setText("CT")
        self.action_show_ct.triggered.connect(self.switch_to_ct)
        self.action_show_mip = QAction('Switch to MIP rendering',
                                       self,
                                       shortcut='Ctrl+3')
        self.action_show_mip.setText("MIP")
        self.action_show_mip.triggered.connect(self.switch_to_mip)

        # Align the dock buttons to the right with a spacer widget
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # Add buttons to container on top
        self.toolbar = self.addToolBar('Main tools')
        self.toolbar.addAction(self.action_show_simple)
        self.toolbar.addAction(self.action_show_ct)
        self.toolbar.addAction(self.action_show_mip)

        self.toolbar.addWidget(spacer)
        self.toolbar.addAction(self.action_load_data)
        self.setUnifiedTitleAndToolBarOnMac(True)

        # Slider for simple visualization
        self.sliders_simple_widget = QSlider(Qt.Horizontal)
        self.sliders_simple_widget.setMinimumWidth(self.slider_width)
        self.sliders_simple_widget.setMaximumWidth(self.slider_width)
        self.sliders_simple_widget.setMinimum(0)
        self.sliders_simple_widget.setMaximum(1000)
        self.sliders_simple_widget.valueChanged.connect(
            self.simple_slider_value_changed)
        self.sliders_simple_widget.setHidden(True)

        # Create sliders for CT transfer function
        sliders_layout = QVBoxLayout()
        sliders_layout.setContentsMargins(0, 0, 0, 0)
        sliders_layout.setSpacing(0)
        self.sliders = []
        for _ in range(0, 7):
            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(1000)
            slider.valueChanged.connect(self.ct_slider_value_changed)
            self.sliders.append(slider)
            sliders_layout.addWidget(slider)

        self.sliders_ct_widget = QWidget()
        self.sliders_ct_widget.setMinimumWidth(self.slider_width)
        self.sliders_ct_widget.setMaximumWidth(self.slider_width)
        self.sliders_ct_widget.setLayout(sliders_layout)
        self.sliders_ct_widget.setHidden(True)

        self.min_slider = QSlider(Qt.Horizontal)
        self.min_slider.setMinimum(0)
        self.min_slider.setMaximum(1000)
        self.min_slider.valueChanged.connect(self.mip_slider_value_changed)

        self.max_slider = QSlider(Qt.Horizontal)
        self.max_slider.setMinimum(0)
        self.max_slider.setMaximum(1000)
        self.max_slider.setValue(1000)
        self.max_slider.valueChanged.connect(self.mip_slider_value_changed)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.min_slider)
        layout.addWidget(self.max_slider)

        self.sliders_mip_widget = QWidget()
        self.sliders_mip_widget.setMinimumWidth(self.slider_width)
        self.sliders_mip_widget.setMaximumWidth(self.slider_width)
        self.sliders_mip_widget.setLayout(layout)
        self.sliders_mip_widget.setHidden(True)

        layout = QHBoxLayout(self.main_widget)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.render_widget)
        layout.addWidget(self.sliders_mip_widget)
        layout.addWidget(self.sliders_ct_widget)
        layout.addWidget(self.sliders_simple_widget)
        self.main_widget.setLayout(layout)

        self.resize(800, 500)
Ejemplo n.º 38
0
        def __init__(self, grid, U):
            assert isinstance(U, Communicable)
            super(MainWindow, self).__init__()

            U = U.data

            layout = QVBoxLayout()

            plotBox = QHBoxLayout()
            plot = GlumpyPatchWidget(self, grid, vmin=np.min(U), vmax=np.max(U), bounding_box=bounding_box, codim=codim)
            bar = ColorBarWidget(self, vmin=np.min(U), vmax=np.max(U))
            plotBox.addWidget(plot)
            plotBox.addWidget(bar)
            layout.addLayout(plotBox)

            if len(U) == 1:
                plot.set(U.ravel())
            else:
                plot.set(U[0])

                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(len(U) - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(len(U))))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(self.style().standardIcon(QStyle.SP_MediaPlay), 'Play', self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(self.style().standardIcon(QStyle.SP_MediaSeekBackward), 'Rewind', self)
                self.a_toend = QAction(self.style().standardIcon(QStyle.SP_MediaSeekForward), 'End', self)
                self.a_step_backward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipBackward), 'Step Back', self)
                self.a_step_forward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipForward), 'Step', self)
                self.a_loop = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop', self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
Ejemplo n.º 39
0
class EegCarDashboardWindow(QWidget):

    def setSliderMaxThrottle(self, x):
        self.setMaxThrottle(x)
        # self.dashboard.set_throttle(x)
        # self.dashboard.wheel.forward(x)

    def setSteeringValue(self, x):
        # x range is 1-9 need to scale (10-90)
        x = x*10
        self.dashboard.set_steering(x)
        # self.dashboard.steering.turn_by_position(x)
        pot = 1.5
        self.dashboard.steering.turn_by_position(x, pot)

    def setSteeringTurnRangeValue(self, x):
        ticks = int(100000 * (x/10.0)) # max is 100000
        # print "STEERING TURN TICKS %d" % ticks
        self.dashboard.set_steering_eeg_turn_ticks(ticks)

    def steering_update_current_pos(self):
        # x = int(self.steering_current_pos.text()) + delta_x
        # while check busy
        ## read position
        ## print 'current pos %d' % x

        ticks = int(self.steering_move_ticks.text())
        seconds = int(ticks/(DEFAULT_STEERING_SPEED*7))
        seconds = seconds + 1 # at least one second
        ending_time = time.time() + seconds
        while time.time() < ending_time:
            # print "ENDNIG: %d" % ending_time
            # print "CURRENT: %d" % time.time()
            self.steering_set_current_pos(self.dashboard.steering.get_current_location())

    def steering_set_current_pos(self, x):
        self.steering_current_pos.setText(str(x))    

    def steering_move_left(self):
        ticks = int(self.steering_move_ticks.text())
        # Stepping Motor MOVE!
        self.dashboard.steering.stepping_driver.forward(ticks)
        self.setMessage('Steering left')
        self.steering_update_current_pos()

    def steering_move_right(self):
        ticks = int(self.steering_move_ticks.text())
        # Stepping Motor MOVE!
        self.dashboard.steering.stepping_driver.backward(ticks)
        self.setMessage('Steering right')
        self.steering_update_current_pos()

    def set_steering_move_ticks_value(self):
        self.steering_move_ticks.blockSignals(True) # update line edit
        ticks = int(self.steering_move_ticks.text())
        self.steering_move_ticks.setText(str(ticks)) 
        self.steering_move_ticks.blockSignals(False)
        self.steering_move_ticks.setModified(True)

        if self.steering_move_ticks.isModified():
            self.steering_move_ticks.clearFocus()
        self.maxThrottle.setModified(False)

    def steering_reset_position(self):
        # RESET
        self.setMessage('Steering Controller Reset')
        self.dashboard.steering.stepping_driver.reset() # reset
        self.dashboard.steering.stepping_driver.set_speed(DEFAULT_STEERING_SPEED) # set speed
        self.steering_update_current_pos()

    def setMessage(self, msg):
        self.statusBar.showMessage(msg, 2000)

    def remote_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_rc_mode(True)
            self.setMessage('SET RC MODE')
        else:
            self.dashboard.set_rc_mode(False)
            self.setMessage('CLEAR RC MODE')

    def keep_mode_control(self, state):
        if state == QtCore.Qt.Checked:
            self.keep_mode = True
            self.setMessage('Keep Mode (EEG)')
        else:
            self.keep_mode = False
            self.setMessage('Keyboard Mode')

    def power_handle_mode_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_power_handle_mode(True)
            self.setMessage('Power Handle (Auto Steering Middle)')
        else:
            self.dashboard.set_power_handle_mode(False)
            self.setMessage('Turn Off Power Handle')

    def ignore_eeg_input_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_ignore_eeg_input(True)
            self.setMessage('Ignore EEG Input')
        else:
            self.dashboard.set_ignore_eeg_input(False)
            self.setMessage('Access EEG Input')

    def stright_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_rc_stright_mode(True)
            self.setMessage('RC STRIGHT Mode')
        else:
            self.dashboard.set_rc_stright_mode(False)
            self.setMessage('RC FREE L/R Mode')

    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("EEG Pilot Dashboard")
        self.setGeometry(0, 0, 750, 800)
        # self.setGeometry(300, 300, 750, 800)
        self.dashboard = EegCarDashboard()
        self.dashboard.set_max_throttle(DEFAULT_MAX_THROTTLE)
        self.dashboard.set_backward_max_throttle(DEFAULT_MAX_BACK_THROTTLE)

        self.layout = QVBoxLayout(self)

        # Drive Setting
        self.rc_mode = QCheckBox('Remote Control', self)
        self.rc_mode.stateChanged.connect(self.remote_control)

        self.rc_stright_mode = QCheckBox('RC Stright', self)
        self.rc_stright_mode.stateChanged.connect(self.stright_control)

        self.keep_mode_checkbox = QCheckBox('Keep Mode', self)
        self.keep_mode_checkbox.stateChanged.connect(self.keep_mode_control)

        self.power_handle_mode_checkbox = QCheckBox('Power Handle', self)
        self.power_handle_mode_checkbox.stateChanged.connect(self.power_handle_mode_control)

        self.ignore_eeg_input = QCheckBox('Ignore Eeg Input', self)
        self.ignore_eeg_input.stateChanged.connect(self.ignore_eeg_input_control)

        drive_layout = QHBoxLayout(self)
        drive_layout.addWidget(self.rc_mode)
        drive_layout.addWidget(self.rc_stright_mode)
        drive_layout.addWidget(self.keep_mode_checkbox)
        drive_layout.addWidget(self.power_handle_mode_checkbox)
        drive_layout.addWidget(self.ignore_eeg_input)

        drive_groupbox = QtGui.QGroupBox("Drive Status & Setting")
        drive_groupbox.setLayout(drive_layout)

        # Throttle Setting
        self.throttle_slider = QSlider(Qt.Horizontal)
        self.throttle_slider.setFocusPolicy(Qt.StrongFocus)
        self.throttle_slider.setTickPosition(QSlider.TicksBothSides)
        self.throttle_slider.setTickInterval(10)
        self.throttle_slider.setSingleStep(10)
        self.throttle_slider.setValue(DEFAULT_MAX_THROTTLE)

        self.throttle_slider.valueChanged.connect(self.throttle_slider.setValue)
        self.connect(self.throttle_slider, SIGNAL("valueChanged(int)"), self.setSliderMaxThrottle)
        self.throttle_label = QLabel('Max Throttle (%): ', self)


        self.maxThrottle = QLineEdit(str(DEFAULT_MAX_THROTTLE))
        # self.maxThrottle.textChanged[str].connect(self.setMaxThrottle)
        self.maxThrottle.editingFinished.connect(self.setMaxThrottle)
        self.maxThrottle.setMaxLength(2)
        self.maxThrottle.setMaximumWidth(40)

        self.backwardMaxThrottle = QLineEdit(str(DEFAULT_MAX_BACK_THROTTLE))
        # self.maxThrottle.textChanged[str].connect(self.setMaxThrottle)
        self.backwardMaxThrottle.editingFinished.connect(self.setBackwardMaxThrottle)
        self.backwardMaxThrottle.setMaxLength(2)
        self.backwardMaxThrottle.setMaximumWidth(40)

        throttle_layout = QHBoxLayout(self)
        throttle_layout.addWidget(self.throttle_label)
        throttle_layout.addWidget(self.throttle_slider)
        throttle_layout.addWidget(QLabel("Forward Max:"))
        throttle_layout.addWidget(self.maxThrottle)

        throttle_layout.addWidget(QLabel("Backward Max:"))
        throttle_layout.addWidget(self.backwardMaxThrottle)

        throttle_groupbox = QtGui.QGroupBox("Max Throttle Setting (30-99)")
        throttle_groupbox.setLayout(throttle_layout)

        # Steering
        self.steering_label = QLabel('Turn Range', self)
        self.steering_turn_range_slider = QSlider(Qt.Horizontal)
        self.steering_turn_range_slider.setFocusPolicy(Qt.StrongFocus)
        self.steering_turn_range_slider.setTickPosition(QSlider.TicksBothSides)
        self.steering_turn_range_slider.setRange(1, 9)
        # self.steering_slider.setMinimum(2)
        # self.steering_slider.setMaximum(8)
        self.steering_turn_range_slider.setMinimum(4)
        self.steering_turn_range_slider.setMaximum(8)
        self.steering_turn_range_slider.setTickInterval(1)
        self.steering_turn_range_slider.setSingleStep(1)
        self.steering_turn_range_slider.setValue(6)
        self.steering_turn_range_slider.valueChanged.connect(self.steering_turn_range_slider.setValue)
        self.connect(self.steering_turn_range_slider, SIGNAL("valueChanged(int)"), self.setSteeringTurnRangeValue)

        self.steering_adjust_label = QLabel(' Home Adjust ', self)
        self.steering_move_left_button = QPushButton('<Left+', self)
        self.steering_current_pos = QLabel('0', self)
        self.steering_move_right_button = QPushButton('-Right>', self)

        self.steering_move_ticks = QLineEdit(str(5000))
        self.steering_move_ticks.editingFinished.connect(self.set_steering_move_ticks_value)
        self.steering_move_ticks.setMaxLength(5)
        self.steering_move_ticks.setMaximumWidth(50)

        self.steering_reset = QPushButton('Reset', self)

        self.steering_move_left_button.clicked.connect(self.steering_move_left)
        self.steering_move_right_button.clicked.connect(self.steering_move_right)
        self.steering_reset.clicked.connect(self.steering_reset_position)

        steering_layout = QHBoxLayout(self)
        steering_layout.addWidget(self.steering_label)
        # steering_layout.addWidget(self.steering_slider)
        steering_layout.addWidget(self.steering_turn_range_slider)
        steering_layout.addWidget(self.steering_adjust_label)
        steering_layout.addWidget(self.steering_move_left_button)


        steering_layout.addWidget(self.steering_current_pos)
        steering_layout.addWidget(self.steering_move_right_button)
        steering_layout.addWidget(self.steering_move_ticks)
        steering_layout.addWidget(self.steering_reset)

        steering_groupbox = QtGui.QGroupBox("Steering Setting")
        steering_groupbox.setLayout(steering_layout)

        self.layout.addWidget(self.dashboard, 2)
        self.layout.addWidget(drive_groupbox)
        self.layout.addWidget(throttle_groupbox)
        self.layout.addWidget(steering_groupbox)

        self.statusBar = QStatusBar()
        self.statusBar.showMessage('Ready', 2000)
        self.layout.addWidget(self.statusBar)

        self.setIcon()
        self.show()

        # save the state
        self.default_backgroundcolor = self.palette().color(QtGui.QPalette.Background)
        self.previos_steering = 50
        self.init_keep_mode()
        self.init_power_handle_mode()

        # Timer For reading current steering position
        # self.timer = QtCore.QTimer()
        # self.timer.timeout.connect(self.readSteeringPos)
        # # check every second
        # self.timer.start(1000)  

        # Timer For Powerhandle
        # self.power_handle_timer = QtCore.QTimer()
        # self.power_handle_timer.timeout.connect(self.update_power_handle)
        # # check every half second
        # self.power_handle_timer.start(500)

        # # Timer For Start Accel
        # self.start_accel_timer = QtCore.QTimer()
        # # self.start_accel_timer.singleShot(5000, self.end_start_accel_handle)
        # self.can_start_accel = True

    # def set_start_accel(self, value):
    #     self.can_start_accel = value

    # def get_start_accel(self):
    #     return self.can_start_accel

    # def end_start_accel_handle(self):
    #     self.dashboard.end_start_accel()

    # def update_power_handle(self):
    #     if self.power_handle_mode:
    #         self.dashboard.update_power_handle()

    def readSteeringPos(self):
        # self.setMessage(str(self.dashboard.steering.get_current_steering()))
        # TODO: is it thread safe?
        # self.steering_set_current_pos(self.dashboard.steering.get_current_location())
        return

    def getMaxThrottle(self):
        return int(self.maxThrottle.text())

    def getBackwardMaxThrottle(self):
        return int(self.backwardMaxThrottle.text())

    def setMaxThrottle(self, _throttle=None):
        if _throttle is None: # from line textbox
            throttle = self.getMaxThrottle()
            self.throttle_slider.blockSignals(True); # update slider
            self.throttle_slider.setValue(throttle);
            self.throttle_slider.blockSignals(False);
        else: # from slider 
            throttle = _throttle
            self.maxThrottle.blockSignals(True); # update line edit
            self.maxThrottle.setText(str(throttle)) 
            self.maxThrottle.blockSignals(False);
            self.maxThrottle.setModified(True)

        if self.maxThrottle.isModified():
            if throttle >= FORWARD_THROTTLE_THRESHOLD: # forward throttle threshold is 20
                self.dashboard.set_max_throttle(throttle)
                self.setMessage("Forward Max Throttle: %d" % throttle)
                self.maxThrottle.clearFocus()
        self.maxThrottle.setModified(False)

    def setBackwardMaxThrottle(self):
        throttle = self.getBackwardMaxThrottle()
        if self.backwardMaxThrottle.isModified():
            if throttle >= BACKWARD_THROTTLE_THRESHOLD: # backward throttle threshold is 20
                self.dashboard.set_backward_max_throttle(throttle)
                self.backwardMaxThrottle.clearFocus()
        self.backwardMaxThrottle.setModified(False)

    def setIcon(self):
        self.appIcon = QIcon('logo.png')
        self.setWindowIcon(self.appIcon)

    def init_keep_mode(self):
        self.w_keep_countdown = 0
        self.x_keep_countdown = 0
        self.a_keep_countdown = 0
        self.d_keep_countdown = 0
        self.default_keep_countdown = DEFAULT_KEEP_COUNT
        # self.default_keep_countdown = 28
        # self.default_keep_countdown = 38
        self.keep_mode = False

    def init_power_handle_mode(self):
        self.power_handle_mode = False

    def is_keep_mode(self, ignore_key):
        # if key is 'w' -> w_keep_countdown
        # if key is 'x' -> x_keep_countdown
        # ignore several 's' key while chountdown number to zero

        if self.keep_mode:
            if ignore_key == Qt.Key_S: 
                if self.dashboard.power_handle_mode == True:
                    self.dashboard.update_power_handle()
                if self.w_keep_countdown > 0:
                    self.w_keep_countdown = self.w_keep_countdown - 1
                    # print "w keep countdown %d" % self.w_keep_countdown
                    self.setMessage("w keep countdown %d" % self.w_keep_countdown)
                    self.x_keep_countdown = 0
                    return True
                if self.x_keep_countdown > 0:
                    self.x_keep_countdown = self.x_keep_countdown - 1
                    # print "x keep countdown %d" % self.x_keep_countdown
                    self.setMessage("x keep countdown %d" % self.x_keep_countdown)
                    self.w_keep_countdown = 0
                    return True
 
            if ignore_key == Qt.Key_X: 
                if self.w_keep_countdown > 0:
                    self.w_keep_countdown = self.w_keep_countdown - 1
                    self.setMessage("w keep countdown %d" % self.w_keep_countdown)
                    if self.w_keep_countdown < DEFAULT_KEEP_COUNT - 10:
                      # self.stop()
                      self.dashboard.set_key_input('s')
                      self.dashboard.stop()
                      self.dashboard.set_start_accel(True)
                    return True

            if ignore_key == Qt.Key_W: 
                if self.x_keep_countdown > 0:
                    self.x_keep_countdown = self.x_keep_countdown - 1
                    self.setMessage("x keep countdown %d" % self.x_keep_countdown)
                    if self.x_keep_countdown < DEFAULT_KEEP_COUNT - 10:
                      # self.stop()
                      self.dashboard.set_key_input('s')
                      self.dashboard.stop()
                      self.dashboard.set_start_accel(True)
                    return True
 
        return False

    def go_to_keep_mode(self, key):
        if key == Qt.Key_W:
            self.w_keep_countdown = self.default_keep_countdown

        if key == Qt.Key_X:
            self.x_keep_countdown = self.default_keep_countdown

        # A, D make a w_keep_countdown FOR powerhandle
        if key == Qt.Key_A:
            self.w_keep_countdown = self.default_keep_countdown

        if key == Qt.Key_D:
            self.w_keep_countdown = self.default_keep_countdown
                
    def keyPressEvent(self, event):
        if self.dashboard.rc_mode == True :
            if self.dashboard.ignore_eeg_input == True:
                self.ignore_eeg_input.setChecked(True)
                if event.key():
                    self.dashboard.set_key_input('Ignore')
                return
            else: 
                self.ignore_eeg_input.setChecked(False)

        # self.update_power_handle(event.key())

        if self.is_keep_mode(event.key()):
            return

        if event.key() == Qt.Key_S:
            self.dashboard.set_key_input('s')
            self.dashboard.stop()
            self.dashboard.set_start_accel(True)

        if event.key() == Qt.Key_W:
            self.dashboard.set_key_input('w')
            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_forward()
            else:
                self.dashboard.forward()

        if event.key() == Qt.Key_A:
            self.dashboard.set_key_input('a')
            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_turn_left()
            else:
                self.dashboard.turn_left()

        if event.key() == Qt.Key_X:
            self.dashboard.set_key_input('x')

            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_backward()
            else:
                self.dashboard.backward()

        if event.key() == Qt.Key_D:
            self.dashboard.set_key_input('d')
            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_turn_right()
            else:
                self.dashboard.turn_right()

        if event.key() == Qt.Key_B:
            self.dashboard.set_key_input('b')
            self.dashboard.brake()

        if event.key() == Qt.Key_R:
            self.dashboard.set_key_input('r')
            # TODO: Make Inspection Mode
            # self.dashboard.steering.position_clear()
            #pot = self.dashboard.wheel.get_steering_pot()
            #self.dashboard.steering.middle_position(pot)

        if event.key() == Qt.Key_F:
            if self.dashboard.isFullScreen():
                for i in range(self.layout.count()):
                    w = self.layout.itemAt(i).widget()
                    w.show()
                self.dashboard.showNormal()
                self.change_backgroundcolor(self.default_backgroundcolor);
                self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowTitleHint)
                self.showNormal()
            else:
                for i in range(self.layout.count()):
                    w = self.layout.itemAt(i).widget()
                    if w == self.dashboard:
                        continue
                    w.hide()
                self.change_backgroundcolor(Qt.black);
                self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint)
                self.showMaximized()
                self.dashboard.showFullScreen()

            self.dashboard.reset_label_position()

        if event.key() == Qt.Key_Escape:
            self.dashboard.close()
            self.close()

        self.go_to_keep_mode(event.key())

    def change_backgroundcolor(self, color):
        p = self.palette()
        p.setColor(self.backgroundRole(), color)
        self.setPalette(p)
Ejemplo n.º 40
0
        def __init__(self, U, plot, length=1, title=None):
            super().__init__()

            layout = QVBoxLayout()

            if title:
                title = QLabel('<b>' + title + '</b>')
                title.setAlignment(Qt.AlignHCenter)
                layout.addWidget(title)
            layout.addWidget(plot)

            plot.set(U, 0)

            if length > 1:
                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(length - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(length)))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(
                    self.style().standardIcon(QStyle.SP_MediaPlay), 'Play',
                    self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSeekBackward),
                    'Rewind', self)
                self.a_toend = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSeekForward),
                    'End', self)
                self.a_step_backward = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSkipBackward),
                    'Step Back', self)
                self.a_step_forward = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSkipForward),
                    'Step', self)
                self.a_loop = QAction(
                    self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop',
                    self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                if hasattr(self, 'save'):
                    self.a_save = QAction(
                        self.style().standardIcon(QStyle.SP_DialogSaveButton),
                        'Save', self)
                    toolbar.addAction(self.a_save)
                    self.a_save.triggered.connect(self.save)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            elif hasattr(self, 'save'):
                hlayout = QHBoxLayout()
                toolbar = QToolBar()
                self.a_save = QAction(
                    self.style().standardIcon(QStyle.SP_DialogSaveButton),
                    'Save', self)
                toolbar.addAction(self.a_save)
                hlayout.addWidget(toolbar)
                layout.addLayout(hlayout)
                self.a_save.triggered.connect(self.save)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
            self.length = length
Ejemplo n.º 41
0
class MainWindow(object):
    '''
    Contains the implementation for building and displaying the 
    application's main window.
    '''

    def __init__(self, model, alg):
        '''
        Constructs the GUI and initializes internal parameters.
        '''
        self._window = QMainWindow()
        self._window.setWindowTitle("Reverse A*")
        self._worldWidget = WorldWidget(model, alg)
        self._model = model
        self._alg = alg
        self._spdSetting = 0
        self._timer = QTimer()
        #Every time the timer times out, invoke the _onStep method.
        self._timer.timeout.connect(self._onStep)        
        self._buildGUI()
        self._window.show()

    def _buildGUI(self):
        '''
        Construct the GUI widgets and layouts.
        '''
        centerWidget = QWidget()
        self._window.setCentralWidget(centerWidget)
        
        worldLayout = QHBoxLayout()
        worldLayout.addWidget(self._worldWidget)
        grpBx = QGroupBox("2D World")
        grpBx.setLayout(worldLayout)
        grpBx.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        ctrlPan = self._buildControlPanel()
        layout = QHBoxLayout()
        layout.addWidget(ctrlPan)
        layout.addWidget(grpBx)
        layout.setAlignment(ctrlPan, Qt.AlignLeft | Qt.AlignTop)
        centerWidget.setLayout(layout)

        
    def _buildControlPanel(self):
        '''
        Create all buttons, labels, etc for the application control elements
        '''
        layout = QVBoxLayout()
        layout.addWidget(self._buildSetupPanel())
        layout.addWidget(self._buildSpeedPanel())
        layout.addWidget(self._buildResultsPanel())
        layout.addWidget(self._buildRenderingOptions())
        layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        
        ctrlWidget = QWidget(self._window)
        ctrlWidget.setLayout(layout)
        ctrlWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        return ctrlWidget        
    
    def _buildSetupPanel(self):
        '''
        Creates the sub-panel containing control widgets for re-initializing 
        the world on demand.
        '''
        self._percentLbl = QLabel("%")
        self._setupBtn = QPushButton("Setup", self._window)
        self._setupBtn.clicked.connect(self._onSetup)
        
        self._percentObstacleSldr = QSlider(Qt.Horizontal, self._window)
        self._percentObstacleSldr.setTickPosition(QSlider.TickPosition.TicksBelow)
        self._percentObstacleSldr.setTickInterval(10)
        self._percentObstacleSldr.setMinimum(0)
        self._percentObstacleSldr.setMaximum(100)
        self._percentObstacleSldr.valueChanged.connect(self._onPercentSlideChange)
        self._percentObstacleSldr.setValue(33)
        
        layout = QGridLayout()
        layout.addWidget(self._setupBtn, 0, 0, 1, 2)
        layout.addWidget(QLabel("Percent Occupied:"), 1, 0)
        layout.addWidget(self._percentLbl, 1, 1)
        layout.addWidget(self._percentObstacleSldr, 2, 0, 1, 2)
        
        grpBx = QGroupBox("Setup Controls")
        grpBx.setLayout(layout)
        grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        return grpBx        
        
    def _buildSpeedPanel(self):
        '''
        Creates the sub-panel containing control widgets for controlling the 
        speed of execution of the algorithm.
        '''
        self._runBtn = QPushButton("Run", self._window)
        self._stepBtn = QPushButton("Step Once", self._window)        
        self._runBtn.clicked.connect(self._onRun)
        self._stepBtn.clicked.connect(self._onStep)        
        
        slowRadio = QRadioButton('Slow', self._window)
        medRadio = QRadioButton('Medium', self._window)
        fastRadio = QRadioButton('Fast', self._window)
        notVisRadio = QRadioButton('Not visible', self._window)
        slowRadio.setChecked(True)        
        
        self._speedGroup = QButtonGroup(self._window)
        self._speedGroup.addButton(slowRadio, 0)
        self._speedGroup.addButton(medRadio, 1)
        self._speedGroup.addButton(fastRadio, 2)
        self._speedGroup.addButton(notVisRadio, 3)
        self._speedGroup.buttonClicked.connect(self._onSpeedChange)
          
        layout = QVBoxLayout()
        layout.addWidget(self._runBtn)
        layout.addWidget(self._stepBtn)
        layout.addWidget(slowRadio)
        layout.addWidget(medRadio)
        layout.addWidget(fastRadio)
        layout.addWidget(notVisRadio)
        
        grpBx = QGroupBox("Run Controls")
        grpBx.setLayout(layout)
        grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        return grpBx
    
    def _buildResultsPanel(self):
        '''
        Creates the sub-panel containing displays widgets for informing the 
        user on the results of running the algorithm.
        '''        
        self._doneLbl = QLabel("No", self._window)
        self._solvableLbl = QLabel("Yes", self._window)
        
        #_doneLbl is highlighted green upon successful algorithm completion
        pal = self._doneLbl.palette()
        pal.setColor(QPalette.Window, Qt.green)
        self._doneLbl.setPalette(pal)

        #_solvableLbl is highlighted red if the world model isn't solvable
        pal = self._solvableLbl.palette()
        pal.setColor(QPalette.Window, Qt.red)
        self._solvableLbl.setPalette(pal)          
        
        layout = QGridLayout()
        layout.addWidget(QLabel("Path Found:"), 0, 0)
        layout.addWidget(self._doneLbl, 0, 1)
        layout.addWidget(QLabel("Is Solvable:"), 1, 0)
        layout.addWidget(self._solvableLbl, 1, 1)
        
        grpBx = QGroupBox("Results")
        grpBx.setLayout(layout)
        grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        return grpBx
    
    def _buildRenderingOptions(self):
        '''
        Creates the sub-panel containing control widgets for setting options
        in how the world is rendered on the GUI.
        '''        
        self._openChk = QCheckBox("Active Cells")
        self._visitedChk = QCheckBox("Visited Cells")
        self._pathChk = QCheckBox("Draw Path")
        self._costChk = QCheckBox("Draw Estimated Costs")
        
        pal = self._openChk.palette()
        pal.setColor(QPalette.WindowText, Qt.green)
        self._openChk.setPalette(pal)
        
        pal = self._visitedChk.palette()
        pal.setColor(QPalette.WindowText, Qt.cyan)
        self._visitedChk.setPalette(pal)
        
        pal = self._pathChk.palette()
        pal.setColor(QPalette.WindowText, Qt.red)
        self._pathChk.setPalette(pal)
        
        self._visitedChk.setChecked(True)
        self._pathChk.setChecked(True)
        self._costChk.setChecked(True)
        
        self._openChk.stateChanged.connect(self._renderingOptionChanged)
        self._visitedChk.stateChanged.connect(self._renderingOptionChanged)
        self._pathChk.stateChanged.connect(self._renderingOptionChanged)
        self._costChk.stateChanged.connect(self._renderingOptionChanged)
        
        layout = QVBoxLayout()
        layout.addWidget(self._openChk)
        layout.addWidget(self._visitedChk)
        layout.addWidget(self._pathChk)
        layout.addWidget(self._costChk)
        
        grpBx = QGroupBox("Rendering Options")
        grpBx.setLayout(layout)
        grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        return grpBx        
    
    @Slot()
    def _renderingOptionChanged(self, value):
        '''
        When any rendering option is changed this method is invoked.  It polls
        the GUI for the selected setting values and passes them to the 2D
        world widget.
        '''
        self._worldWidget.setDrawActiveCells(self._openChk.isChecked())
        self._worldWidget.setDrawVisitedCells(self._visitedChk.isChecked())
        self._worldWidget.setDrawPath(self._pathChk.isChecked())
        self._worldWidget.setDrawCosts(self._costChk.isChecked())
        self._worldWidget.repaint()
    
    @Slot()
    def _onPercentSlideChange(self, value):
        '''
        Invoked every time the percent slider is changed.  Displays the percent
        value on the GUI.
        '''
        
        #Add extra padding to the front of the string to help prevent
        #gui layout resizing
        if value < 10:
            self._percentLbl.setText("  " + str(value) + "%")
        elif value < 100:
            self._percentLbl.setText(" " + str(value) + "%")
        else:
            self._percentLbl.setText(str(value) + "%")
    
    @Slot()
    def _onSpeedChange(self, value):
        '''
        Invoked every time one of the speed setting radio buttons are selected.
        Resets the algorithm iterating callback timer if it's currently running.
        '''
        self._spdSetting = self._speedGroup.checkedId()
        if self._timer.isActive():
            self._resetTimer()            
         
    @Slot()
    def _onSetup(self):
        '''
        Invoked when the setup button is pushed.  Re-initializes the world model
        and the algorithm.
        '''
        self._timer.stop()
        self._runBtn.setText('Run')
        self._model.reset(self._percentObstacleSldr.value() / 100.0)
        self._alg.reset()
        self._doneLbl.setText("No")
        self._solvableLbl.setText("Yes")
        self._doneLbl.setAutoFillBackground(False)
        self._solvableLbl.setAutoFillBackground(False)
        self._worldWidget.repaint()
    
    @Slot()
    def _onRun(self):
        '''
        Invoked when the run button is pushed.  Toggles the algorithm iterating
        timer on and off.
        '''
        if self._timer.isActive():
            self._timer.stop()
            self._runBtn.setText("Run")
        else:
            self._resetTimer()
            self._runBtn.setText("Stop")
    
    @Slot()
    def _onStep(self):
        '''
        Invoked on every 'step once' call and on every timer timeout.  Iterates
        one step of the algorithm and then checks for termination conditions
        such as the algorithm being done or solvable.
        '''
        self._alg.step()
        self._worldWidget.repaint()
        
        if self._alg.isDone() or not self._alg.isSolvable():
            self._timer.stop()
            self._runBtn.setText('Run')
        
        self._checkTerminalConditions()
            
    def _checkTerminalConditions(self):
        '''
        Sets the 'results' labels based on the algorithm results.
        '''
        if self._alg.isDone():
            self._doneLbl.setText("Yes")
            self._doneLbl.setAutoFillBackground(True)

        if not self._alg.isSolvable():
            self._solvableLbl.setAutoFillBackground(True)
            self._solvableLbl.setText("No")

    def _resetTimer(self):
        '''
        When the algorithm run speed is modified by the user this resets the
        algorithm timer.
        '''
        if self._spdSetting == 3:
            while not self._alg.isDone() and self._alg.isSolvable():
                self._alg.step()
                
            self._worldWidget.repaint()
            self._timer.stop()
            self._runBtn.setText("Run")
            
            self._checkTerminalConditions()            
        else:
            timeOut = 1
            if self._spdSetting == 0:
                timeOut = 500
            elif self._spdSetting == 1:
                timeOut = 250
            elif self._spdSetting == 2:
                timeOut = 1            
            self._timer.start(timeOut)
Ejemplo n.º 42
0
 def __init__(self, clipboard):
     super().__init__()
     self.clipboard = clipboard
     self.setWindowIcon(QIcon('Logo_rendered_edited.png'))
     self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
     self.generator = CtSesam()
     self.iterations = 4096
     # Master password
     self.master_password_label = QLabel("&Master-Passwort:")
     self.maser_password_edit = QLineEdit()
     self.maser_password_edit.setEchoMode(QLineEdit.EchoMode.Password)
     self.maser_password_edit.textChanged.connect(self.reset_iterations)
     self.maser_password_edit.returnPressed.connect(self.move_focus)
     self.maser_password_edit.setMaximumHeight(28)
     self.master_password_label.setBuddy(self.maser_password_edit)
     self.layout.addWidget(self.master_password_label)
     self.layout.addWidget(self.maser_password_edit)
     # Domain
     self.domain_label = QLabel("&Domain:")
     self.domain_edit = QLineEdit()
     self.domain_edit.textChanged.connect(self.reset_iterations)
     self.domain_edit.returnPressed.connect(self.move_focus)
     self.domain_edit.setMaximumHeight(28)
     self.domain_label.setBuddy(self.domain_edit)
     self.layout.addWidget(self.domain_label)
     self.layout.addWidget(self.domain_edit)
     # Username
     self.username_label = QLabel("&Username:"******"Sonderzeichen")
     self.special_characters_checkbox.setChecked(True)
     self.special_characters_checkbox.stateChanged.connect(self.reset_iterations)
     self.layout.addWidget(self.special_characters_checkbox)
     self.letters_checkbox = QCheckBox("Buchstaben")
     self.letters_checkbox.setChecked(True)
     self.letters_checkbox.stateChanged.connect(self.reset_iterations)
     self.layout.addWidget(self.letters_checkbox)
     self.digits_checkbox = QCheckBox("Zahlen")
     self.digits_checkbox.setChecked(True)
     self.digits_checkbox.stateChanged.connect(self.reset_iterations)
     self.layout.addWidget(self.digits_checkbox)
     # Length slider
     self.length_label = QLabel("&Länge:")
     self.length_display = QLabel()
     self.length_label_layout = QBoxLayout(QBoxLayout.LeftToRight)
     self.length_label_layout.addWidget(self.length_label)
     self.length_label_layout.addWidget(self.length_display)
     self.length_label_layout.addStretch()
     self.length_slider = QSlider(Qt.Horizontal)
     self.length_slider.setMinimum(4)
     self.length_slider.setMaximum(20)
     self.length_slider.setPageStep(1)
     self.length_slider.setValue(10)
     self.length_display.setText(str(self.length_slider.sliderPosition()))
     self.length_slider.valueChanged.connect(self.length_slider_changed)
     self.length_label.setBuddy(self.length_slider)
     self.layout.addLayout(self.length_label_layout)
     self.layout.addWidget(self.length_slider)
     # Button
     self.generate_button = QPushButton("Erzeugen")
     self.generate_button.clicked.connect(self.generate_password)
     self.generate_button.setAutoDefault(True)
     self.layout.addWidget(self.generate_button)
     # Password
     self.password_label = QLabel("&Passwort:")
     self.password = QLabel()
     self.password.setTextFormat(Qt.PlainText)
     self.password.setAlignment(Qt.AlignCenter)
     self.password.setFont(QFont("Helvetica", 18, QFont.Bold))
     self.password_label.setBuddy(self.password)
     self.layout.addWidget(self.password_label)
     self.layout.addWidget(self.password)
     # Iteration display
     self.message_label = QLabel()
     self.message_label.setTextFormat(Qt.RichText)
     self.message_label.setVisible(False)
     self.layout.addWidget(self.message_label)
     # Window layout
     self.layout.addStretch()
     self.setGeometry(0, 30, 300, 400)
     self.setWindowTitle("c't SESAM")
     self.maser_password_edit.setFocus()
     self.show()
Ejemplo n.º 43
0
class Layer(object):

    def __init__(self):
        super(Layer, self).__init__()
        self.orientation = Quaternion()
        self.picked = None
        self.show = QCheckBox()
        self.show.setChecked(True)
        self.alpha_slider = QSlider(QtCore.Qt.Orientation.Horizontal)
        self.alpha_slider.setRange(0, 1024)
        self.alpha_slider.setValue(1024)
        self.alpha_number = QDoubleSpinBox()
        self.alpha_number.setDecimals(3)
        self.alpha_number.setSingleStep(0.01)
        self.alpha_number.setRange(0, 1)
        self.alpha_number.setValue(1)
        self.alpha_slider.valueChanged.connect(self._alphaSliderChanged)
        self.alpha_number.valueChanged.connect(self._alphaNumberChanged)
        self.move = QCheckBox()
        self.move.setChecked(True)
        self.quat = QLineEdit()
        font = QFont('monospace')
        font.setStyleHint(QFont.TypeWriter)
        self.quat.setFont(font)
        default_quat = '+0.000, +1.000, +0.000, +0.000'
        margins = self.quat.textMargins()
        self.quat.setFixedWidth(
            # HACK -------------------------------------------v
            QFontMetrics(self.quat.font()).width(default_quat + '  ') +
            margins.left() + margins.right()
        )
        self.quat.setInputMask('#0.000, #0.000, #0.000, #0.000')
        self.quat.setMaxLength(30)
        self.quat.setText(default_quat)
        self.quat.editingFinished.connect(self._orientationChanged)
        self.nbytes = QLabel()
        self.nbytes.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.nbytes.setText('0')
        self.label = QLabel()
        self.label.setText('<empty>')

    def multiplyOrientation(self, quat):
        self.setOrientation(quat * self.orientation)

    def setOrientation(self, quat):
        self.orientation = quat
        self.quat.setText(
            '%+1.3f, %+1.3f, %+1.3f, %+1.3f' % (
                self.orientation.w,
                self.orientation.x,
                self.orientation.y,
                self.orientation.z,
            )
        )

    def _orientationChanged(self):
        text = self.quat.text()

    def alpha(self):
        return self.alpha_number.value() if self.show.isChecked() else 0.0

    def _alphaSliderChanged(self):
        self.alpha_number.setValue(self.alpha_slider.value() / 1024.0)

    def _alphaNumberChanged(self):
        self.alpha_slider.setValue(1024 * self.alpha_number.value())

    def setup_ui(self, table, row):
        widgets = [
            None,
            CenterH(self.show),
            self.alpha_slider,
            self.alpha_number,
            CenterH(self.move),
            self.quat,
            self.nbytes,
            self.label,
        ]
        for (column, widget) in enumerate(widgets):
            if widget is not None:
                table.setCellWidget(row, column, widget)

    def load_file(self, file_name, in_format):
        self.sphere = proj.load_sphere(file_name, projection=in_format)
        in_format = self.sphere.__class__
        print('Loaded input %s from %s.' % (in_format.__name__, file_name))
        self.texture_id = glGenTextures(1)
        self.sphere.to_gl(self.texture_id)
        self.shader = Shader(
            vert=VERTEX_SHADER,
            frag=FRAGMENT_SHADER + self.sphere.get_glsl_sampler(),
        )
        self.label.setText(file_name)
        self.nbytes.setText(read_bsize(self.sphere.array.nbytes))
Ejemplo n.º 44
0
class MainWindow(QWidget):
    # noinspection PyUnresolvedReferences
    def __init__(self, clipboard):
        super().__init__()
        self.clipboard = clipboard
        self.setWindowIcon(QIcon('Logo_rendered_edited.png'))
        self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.generator = CtSesam()
        self.iterations = 4096
        # Master password
        self.master_password_label = QLabel("&Master-Passwort:")
        self.maser_password_edit = QLineEdit()
        self.maser_password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        self.maser_password_edit.textChanged.connect(self.reset_iterations)
        self.maser_password_edit.returnPressed.connect(self.move_focus)
        self.maser_password_edit.setMaximumHeight(28)
        self.master_password_label.setBuddy(self.maser_password_edit)
        self.layout.addWidget(self.master_password_label)
        self.layout.addWidget(self.maser_password_edit)
        # Domain
        self.domain_label = QLabel("&Domain:")
        self.domain_edit = QLineEdit()
        self.domain_edit.textChanged.connect(self.reset_iterations)
        self.domain_edit.returnPressed.connect(self.move_focus)
        self.domain_edit.setMaximumHeight(28)
        self.domain_label.setBuddy(self.domain_edit)
        self.layout.addWidget(self.domain_label)
        self.layout.addWidget(self.domain_edit)
        # Username
        self.username_label = QLabel("&Username:"******"Sonderzeichen")
        self.special_characters_checkbox.setChecked(True)
        self.special_characters_checkbox.stateChanged.connect(self.reset_iterations)
        self.layout.addWidget(self.special_characters_checkbox)
        self.letters_checkbox = QCheckBox("Buchstaben")
        self.letters_checkbox.setChecked(True)
        self.letters_checkbox.stateChanged.connect(self.reset_iterations)
        self.layout.addWidget(self.letters_checkbox)
        self.digits_checkbox = QCheckBox("Zahlen")
        self.digits_checkbox.setChecked(True)
        self.digits_checkbox.stateChanged.connect(self.reset_iterations)
        self.layout.addWidget(self.digits_checkbox)
        # Length slider
        self.length_label = QLabel("&Länge:")
        self.length_display = QLabel()
        self.length_label_layout = QBoxLayout(QBoxLayout.LeftToRight)
        self.length_label_layout.addWidget(self.length_label)
        self.length_label_layout.addWidget(self.length_display)
        self.length_label_layout.addStretch()
        self.length_slider = QSlider(Qt.Horizontal)
        self.length_slider.setMinimum(4)
        self.length_slider.setMaximum(20)
        self.length_slider.setPageStep(1)
        self.length_slider.setValue(10)
        self.length_display.setText(str(self.length_slider.sliderPosition()))
        self.length_slider.valueChanged.connect(self.length_slider_changed)
        self.length_label.setBuddy(self.length_slider)
        self.layout.addLayout(self.length_label_layout)
        self.layout.addWidget(self.length_slider)
        # Button
        self.generate_button = QPushButton("Erzeugen")
        self.generate_button.clicked.connect(self.generate_password)
        self.generate_button.setAutoDefault(True)
        self.layout.addWidget(self.generate_button)
        # Password
        self.password_label = QLabel("&Passwort:")
        self.password = QLabel()
        self.password.setTextFormat(Qt.PlainText)
        self.password.setAlignment(Qt.AlignCenter)
        self.password.setFont(QFont("Helvetica", 18, QFont.Bold))
        self.password_label.setBuddy(self.password)
        self.layout.addWidget(self.password_label)
        self.layout.addWidget(self.password)
        # Iteration display
        self.message_label = QLabel()
        self.message_label.setTextFormat(Qt.RichText)
        self.message_label.setVisible(False)
        self.layout.addWidget(self.message_label)
        # Window layout
        self.layout.addStretch()
        self.setGeometry(0, 30, 300, 400)
        self.setWindowTitle("c't SESAM")
        self.maser_password_edit.setFocus()
        self.show()

    def length_slider_changed(self):
        self.length_display.setText(str(self.length_slider.sliderPosition()))
        self.reset_iterations()

    def reset_iterations(self):
        self.iterations = 4096
        self.message_label.setVisible(False)
        self.password.setText('')
        self.clipboard.setText('')

    def move_focus(self):
        line_edits = [self.maser_password_edit, self.domain_edit, self.username_edit]
        for i, edit in enumerate(line_edits):
            if edit.hasFocus() and i + 1 < len(line_edits):
                line_edits[i + 1].setFocus()
                return True
        self.generate_button.setFocus()

    def generate_password(self):
        if len(self.domain_edit.text()) <= 0:
            self.reset_iterations()
            self.message_label.setText(
                '<span style="font-size: 10px; color: #aa0000;">Bitte geben Sie eine Domain an.</span>')
            self.message_label.setVisible(True)
            return False
        if self.letters_checkbox.isChecked() or \
           self.digits_checkbox.isChecked() or \
           self.special_characters_checkbox.isChecked():
            self.generator.set_password_characters(
                use_letters=self.letters_checkbox.isChecked(),
                use_digits=self.digits_checkbox.isChecked(),
                use_special_characters=self.special_characters_checkbox.isChecked())
        else:
            self.reset_iterations()
            self.message_label.setText(
                '<span style="font-size: 10px; color: #aa0000;">Bei den aktuellen Einstellungen ' +
                'kann kein Passwort berechnet werden.</span>')
            self.message_label.setVisible(True)
            return False
        password = self.generator.generate(
            master_password=self.maser_password_edit.text(),
            domain=self.domain_edit.text(),
            username=self.username_edit.text(),
            length=self.length_slider.sliderPosition(),
            iterations=self.iterations
        )
        self.password.setText(password)
        self.password.setTextInteractionFlags(Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard)
        self.clipboard.setText(password)
        self.message_label.setText(
            '<span style="font-size: 10px; color: #888888;">Das Passwort wurde ' + str(self.iterations) +
            ' mal gehasht <br />und in die Zwischenablage kopiert.</span>')
        self.message_label.setVisible(True)
        self.iterations += 1
Ejemplo n.º 45
0
    class PlotMainWindow(QWidget):
        """Base class for plot main windows."""
        def __init__(self, U, plot, length=1, title=None):
            super().__init__()

            layout = QVBoxLayout()

            if title:
                title = QLabel('<b>' + title + '</b>')
                title.setAlignment(Qt.AlignHCenter)
                layout.addWidget(title)
            layout.addWidget(plot)

            plot.set(U, 0)

            if length > 1:
                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(length - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(length)))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(
                    self.style().standardIcon(QStyle.SP_MediaPlay), 'Play',
                    self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSeekBackward),
                    'Rewind', self)
                self.a_toend = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSeekForward),
                    'End', self)
                self.a_step_backward = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSkipBackward),
                    'Step Back', self)
                self.a_step_forward = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSkipForward),
                    'Step', self)
                self.a_loop = QAction(
                    self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop',
                    self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                if hasattr(self, 'save'):
                    self.a_save = QAction(
                        self.style().standardIcon(QStyle.SP_DialogSaveButton),
                        'Save', self)
                    toolbar.addAction(self.a_save)
                    self.a_save.triggered.connect(self.save)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            elif hasattr(self, 'save'):
                hlayout = QHBoxLayout()
                toolbar = QToolBar()
                self.a_save = QAction(
                    self.style().standardIcon(QStyle.SP_DialogSaveButton),
                    'Save', self)
                toolbar.addAction(self.a_save)
                hlayout.addWidget(toolbar)
                layout.addLayout(hlayout)
                self.a_save.triggered.connect(self.save)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
            self.length = length

        def slider_changed(self, ind):
            self.plot.set(self.U, ind)

        def speed_changed(self, val):
            self.timer.setInterval(val * 20)

        def update_solution(self):
            ind = self.slider.value() + 1
            if ind >= self.length:
                if self.a_loop.isChecked():
                    ind = 0
                else:
                    self.a_play.setChecked(False)
                    return
            self.slider.setValue(ind)

        def toggle_play(self, checked):
            if checked:
                if self.slider.value() + 1 == self.length:
                    self.slider.setValue(0)
                self.timer.start()
            else:
                self.timer.stop()

        def rewind(self):
            self.slider.setValue(0)

        def to_end(self):
            self.a_play.setChecked(False)
            self.slider.setValue(self.length - 1)

        def step_forward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() + 1
            if ind == self.length and self.a_loop.isChecked():
                ind = 0
            if ind < self.length:
                self.slider.setValue(ind)

        def step_backward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() - 1
            if ind == -1 and self.a_loop.isChecked():
                ind = self.length - 1
            if ind >= 0:
                self.slider.setValue(ind)
Ejemplo n.º 46
0
class ParameterSlider(QWidget):
    '''ParameterSlider is a QSlider combined with a QLabel to display the 
    current value of the slider
        
    Arguments
    ---------
    parent : QWidget
        parent widget
    name : str
        name of the parameter the slider represents. Will be used as 'name = ' 
        prefix for the label 
    '''
    
    valueChanged = Signal()
    
    def __init__(self, parent=None, name=None):
        QWidget.__init__(self, parent)
        self.name = name
        self.set_format('.3f')

        # create widgets
        self.label = QLabel()
        self.slider = QSlider(QtCore.Qt.Orientation.Horizontal)        
        self.slider.valueChanged.connect(self._update_label)
        
        # set default values
        self.set_range(0, 100)
        self.set_value(50)        

        # create layout for the entire widget
        box = QVBoxLayout()
        box.addWidget(self.label)
        box.addWidget(self.slider)        
        self.setLayout(box)

    def _convert(self, value, inverse=False):
        if inverse == True:
            # slider value -> true value                
            return self.offset + self.delta * float(value) / self.ticks
        else:
            # true value -> slider value
            return (value - self.offset) * self.ticks / self.delta

    @Slot()
    def _update_label(self, value):
        # convert value to external range
        value = self._convert(value, inverse=True)
        
        if self.name is None:
            # no name given -> show just 'value'
            text = self.format_str.format(value)
        else:
            # name given -> show 'name = value'
            text = self.format_str.format(self.name, value)
                        
        self.label.setText(text)
        self.valueChanged.emit()

    def set_format(self, format_str):
        if self.name is None:
            self.format_str = '{:' + format_str + '}'
        else:
            self.format_str = '{} = {:' + format_str + '}'

    def set_range(self, minimum, maximum, step=1):
        # calculate settings
        self.offset = float(minimum)
        self.delta = float(maximum - minimum)
        self.ticks = int(self.delta / step)

        # forward settings to widget
        self.slider.setMinimum(0.0)
        self.slider.setMaximum(self.ticks)
        self.slider.setSingleStep(1.0)

    def set_value(self, value):
        # convert value to internal range
        value = self._convert(float(value))
        
        # set value and emit signal        
        self.slider.setValue(value)
        self.slider.valueChanged.emit(value)
        
    def value(self):
        return self._convert(self.slider.value(), inverse=True)
Ejemplo n.º 47
0
class beso_gui(QDialog):
    def __init__(self):
        super().__init__()
        self.title = 'BESO Topology Optimization (experimental)'
        self.left = 250
        self.top = 30
        self.width = 550
        self.height = 730

        beso_gui.inp_file = ""
        beso_gui.beso_dir = os.path.dirname(__file__)

        self.initUI()

    # def closeEvent(self, event):
    #     self.close()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Select analysis file button
        button = QPushButton('Select analysis file', self)
        button.setToolTip('*.inp CalculiX analysis file.')
        button.move(10, 10)
        button.clicked.connect(self.on_click)

        # Text box - file path and name
        self.textbox_file_name = QLineEdit(self)
        self.textbox_file_name.move(120, 15)
        self.textbox_file_name.resize(420, 20)
        self.textbox_file_name.setText("None analysis file selected")
        self.textbox_file_name.setToolTip('Analysis file.')

        # Update button
        button1 = QPushButton('Update domains', self)
        button1.setToolTip(
            'Update naming inputs and material data from FreeCAD.')
        button1.move(10, 50)
        button1.clicked.connect(self.on_click1)

        # Domains definition

        # Label above domains definition
        label21 = QLabel('Domain 0', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(120, 50)

        label21 = QLabel('Domain 1', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(260, 50)

        label21 = QLabel('Domain 2', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(400, 50)

        label24 = QLabel('Material object', self)
        label24.move(20, 80)

        label25 = QLabel('Thickness object', self)
        label25.move(20, 110)

        label26 = QLabel('As design domain', self)
        label26.move(20, 140)

        label27 = QLabel('Stress limit [MPa]', self)
        label27.move(20, 170)

        # Combo box - select domain by material object
        self.combo = QComboBox(self)
        self.combo.setToolTip('Material object to define the domain.')
        self.combo.move(120, 80)
        self.combo.resize(140, 30)
        self.combo.currentIndexChanged.connect(self.on_change)

        self.combo1 = QComboBox(self)
        self.combo1.setToolTip('Material object to define the domain.')
        self.combo1.move(260, 80)
        self.combo1.resize(140, 30)
        self.combo1.currentIndexChanged.connect(self.on_change1)

        self.combo2 = QComboBox(self)
        self.combo2.setToolTip('Material object to define the domain.')
        self.combo2.move(400, 80)
        self.combo2.resize(140, 30)
        self.combo2.currentIndexChanged.connect(self.on_change2)

        # Combo box - select thickness object
        self.combo0t = QComboBox(self)
        self.combo0t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo0t.move(120, 110)
        self.combo0t.resize(140, 30)

        self.combo1t = QComboBox(self)
        self.combo1t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo1t.move(260, 110)
        self.combo1t.resize(140, 30)

        self.combo2t = QComboBox(self)
        self.combo2t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo2t.move(400, 110)
        self.combo2t.resize(140, 30)

        self.textbox3 = QLineEdit(self)
        self.textbox3.move(120, 170)
        self.textbox3.resize(40, 20)
        # self.textbox3.setText("")
        self.textbox3.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox4 = QLineEdit(self)
        self.textbox4.move(260, 170)
        self.textbox4.resize(40, 20)
        # self.textbox4.setText("")
        self.textbox4.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox5 = QLineEdit(self)
        self.textbox5.move(400, 170)
        self.textbox5.resize(40, 20)
        # self.textbox5.setText("")
        self.textbox5.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        # Check box - design or nondesign
        self.checkbox = QCheckBox('', self)
        self.checkbox.setChecked(True)
        self.checkbox.setToolTip('Check to be the design domain.')
        self.checkbox.move(120, 140)

        self.checkbox1 = QCheckBox('', self)
        self.checkbox1.setChecked(True)
        self.checkbox1.setToolTip('Check to be the design domain.')
        self.checkbox1.move(260, 140)

        self.checkbox2 = QCheckBox('', self)
        self.checkbox2.setChecked(True)
        self.checkbox2.setToolTip('Check to be the design domain.')
        self.checkbox2.move(400, 140)

        # Text box - stress limit
        self.textbox = QLineEdit(self)
        self.textbox.move(120, 170)
        self.textbox.resize(40, 20)
        # self.textbox.setText("")
        self.textbox.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox1 = QLineEdit(self)
        self.textbox1.move(260, 170)
        self.textbox1.resize(40, 20)
        # self.textbox1.setText("")
        self.textbox1.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox2 = QLineEdit(self)
        self.textbox2.move(400, 170)
        self.textbox2.resize(40, 20)
        # self.textbox2.setText("")
        self.textbox2.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        # Filters

        # Label above filter definition
        label31 = QLabel('Filter 0', self)
        label31.setStyleSheet("font-weight: bold")
        label31.move(120, 210)

        label32 = QLabel('Filter 1', self)
        label32.setStyleSheet("font-weight: bold")
        label32.move(260, 210)

        label33 = QLabel('Filter 2', self)
        label33.setStyleSheet("font-weight: bold")
        label33.move(400, 210)

        label34 = QLabel('Type', self)
        label34.move(20, 240)

        label35 = QLabel('Range [mm]', self)
        label35.move(20, 270)

        label36 = QLabel('Direction vector', self)
        label36.move(20, 300)

        label37 = QLabel('Apply to', self)
        label37.move(20, 330)

        # Combo box - select filter type
        self.combo6 = QComboBox(self)
        self.combo6.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo6.addItem("None")
        self.combo6.addItem("simple")
        self.combo6.addItem("casting")
        self.combo6.setCurrentIndex(1)
        self.combo6.move(120, 240)
        self.combo6.currentIndexChanged.connect(self.on_change6)

        self.combo7 = QComboBox(self)
        self.combo7.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo7.addItem("None")
        self.combo7.addItem("simple")
        self.combo7.addItem("casting")
        self.combo7.move(260, 240)
        self.combo7.currentIndexChanged.connect(self.on_change7)

        self.combo8 = QComboBox(self)
        self.combo8.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo8.addItem("None")
        self.combo8.addItem("simple")
        self.combo8.addItem("casting")
        self.combo8.move(400, 240)
        self.combo8.currentIndexChanged.connect(self.on_change8)

        # Text box - filter range
        self.textbox6 = QLineEdit(self)
        self.textbox6.move(120, 270)
        self.textbox6.resize(50, 20)
        # self.textbox6.setText("")
        self.textbox6.setToolTip(
            'Filter range [mm], recommended two times mesh size.')

        self.textbox7 = QLineEdit(self)
        self.textbox7.move(260, 270)
        self.textbox7.resize(50, 20)
        # self.textbox7.setText("")
        self.textbox7.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox7.setEnabled(False)

        self.textbox8 = QLineEdit(self)
        self.textbox8.move(400, 270)
        self.textbox8.resize(50, 20)
        # self.textbox8.setText("")
        self.textbox8.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox8.setEnabled(False)

        # Text box - casting direction
        self.textbox9 = QLineEdit(self)
        self.textbox9.move(120, 300)
        self.textbox9.resize(80, 20)
        self.textbox9.setText("0, 0, 1")
        self.textbox9.setEnabled(False)
        self.textbox9.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox10 = QLineEdit(self)
        self.textbox10.move(260, 300)
        self.textbox10.resize(80, 20)
        self.textbox10.resize(80, 20)
        self.textbox10.setText("0, 0, 1")
        self.textbox10.setEnabled(False)
        self.textbox10.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox11 = QLineEdit(self)
        self.textbox11.move(400, 300)
        self.textbox11.resize(80, 20)
        self.textbox11.setText("0, 0, 1")
        self.textbox11.setEnabled(False)
        self.textbox11.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        # list widget - select domains
        self.widget = QListWidget(self)
        self.widget.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget.move(120, 330)
        self.widget.resize(140, 120)
        self.widget.setSelectionMode(QAbstractItemView.MultiSelection)

        self.widget1 = QListWidget(self)
        self.widget1.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget1.move(260, 330)
        self.widget1.resize(140, 120)
        self.widget1.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget1.setEnabled(False)

        self.widget2 = QListWidget(self)
        self.widget2.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget2.move(400, 330)
        self.widget2.resize(140, 120)
        self.widget2.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget2.setEnabled(False)

        # Other settings
        label40 = QLabel('Other settings', self)
        label40.setStyleSheet("font-weight: bold")
        label40.move(10, 470)

        # AR, RR slider
        label41 = QLabel('Change per iteration:   low', self)
        label41.setFixedWidth(150)
        label41.move(10, 500)
        label42 = QLabel('high', self)
        label42.move(240, 500)

        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(1, 3)
        self.slider.setSingleStep(1)
        self.slider.setValue(2)
        self.slider.move(150, 500)
        self.slider.resize(80, 30)
        self.slider.setToolTip(
            'Sets mass change per iteration, which is controlled as\n'
            'slow:   mass_addition_ratio=0.01,  mass_removal_ratio=0.02\n'
            'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n'
            'fast:   mass_addition_ratio=0.03,  mass_removal_ratio=0.06')

        # optimization base combobox
        label51 = QLabel('Optimization base', self)
        label51.move(10, 530)
        self.combo51 = QComboBox(self)
        self.combo51.setToolTip(
            'Basic principle to determine if element should remain or be removed:\n'
            '"stiffness" to maximize stiffness (minimize compliance),\n'
            '"heat" to maximize heat flow.')
        self.combo51.addItem("stiffness")
        self.combo51.addItem("heat")
        self.combo51.move(120, 530)

        # mass goal ratio
        label52 = QLabel('Mass goal ratio', self)
        label52.move(10, 560)
        self.textbox52 = QLineEdit(self)
        self.textbox52.move(120, 560)
        self.textbox52.resize(50, 20)
        self.textbox52.setText("0.4")
        self.textbox52.setToolTip(
            'Fraction of all design domains masses to be achieved;\n'
            'between 0 and 1.')

        # generate conf. file button
        button21 = QPushButton('Generate conf. file', self)
        button21.setToolTip(
            'Writes configuration file with optimization parameters.')
        button21.move(10, 600)
        button21.clicked.connect(self.on_click21)

        # edit conf. file button
        button22 = QPushButton('Edit conf. file', self)
        button22.setToolTip('Opens configuration file for hand modifications.')
        button22.move(10, 630)
        button22.clicked.connect(self.on_click22)

        # run optimization button
        button23 = QPushButton('Run optimization', self)
        button23.setToolTip('Writes configuration file and runs optimization.')
        button23.move(10, 660)
        button23.clicked.connect(self.on_click23)

        # generate conf file and run optimization button
        button24 = QPushButton('Generate conf.\nfile and run\noptimization',
                               self)
        button24.setToolTip('Writes configuration file and runs optimization.')
        button24.move(120, 600)
        button24.resize(100, 90)
        button24.clicked.connect(self.on_click24)

        # help buttons
        label41 = QLabel('Help', self)
        label41.move(440, 560)

        button31 = QPushButton('Example', self)
        button31.setToolTip(
            'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD')
        button31.move(440, 590)
        # button31.resize(80, 50)
        button31.clicked.connect(self.on_click31)

        button32 = QPushButton('Conf. comments', self)
        button32.setToolTip(
            'https://github.com/fandaL/beso/blob/master/beso_conf.py')
        button32.move(440, 620)
        # button32.resize(80, 50)
        button32.clicked.connect(self.on_click32)

        button33 = QPushButton('Close', self)
        button33.move(440, 690)
        # button33.resize(80, 50)
        button33.clicked.connect(self.on_click33)

        # open log file
        button40 = QPushButton('Open log file', self)
        button40.setToolTip('Opens log file in your text editor.\n'
                            '(Does not refresh automatically.)')
        button40.move(10, 690)
        button40.clicked.connect(self.on_click40)

        self.on_click1()  # first update
        self.show()

    # @pyqtSlot()
    def on_click(self):
        ex2 = SelectFile()
        self.show()
        self.textbox_file_name.setText(self.inp_file)

    def on_click1(self):
        # get material objects
        self.materials = []
        self.thicknesses = []
        for obj in App.ActiveDocument.Objects:
            if obj.Name[:23] in ["MechanicalSolidMaterial", "SolidMaterial"]:
                self.materials.append(obj)
            elif obj.Name[:17] == "ElementGeometry2D":
                self.thicknesses.append(obj)
        # update materials combo boxes
        self.combo.clear()
        self.combo.addItem("None")
        self.combo1.clear()
        self.combo1.addItem("None")
        self.combo2.clear()
        self.combo2.addItem("None")
        self.combo0t.clear()
        self.combo0t.addItem("None")
        self.combo1t.clear()
        self.combo1t.addItem("None")
        self.combo2t.clear()
        self.combo2t.addItem("None")
        self.widget.clear()
        self.widget.addItem("All defined")
        self.widget.addItem("Domain 0")
        self.widget.addItem("Domain 1")
        self.widget.addItem("Domain 2")
        self.widget.setCurrentItem(self.widget.item(0))
        self.widget1.clear()
        self.widget1.addItem("All defined")
        self.widget1.addItem("Domain 0")
        self.widget1.addItem("Domain 1")
        self.widget1.addItem("Domain 2")
        self.widget1.setCurrentItem(self.widget1.item(0))
        self.widget2.clear()
        self.widget2.addItem("All defined")
        self.widget2.addItem("Domain 0")
        self.widget2.addItem("Domain 1")
        self.widget2.addItem("Domain 2")
        self.widget2.setCurrentItem(self.widget2.item(0))
        for mat in self.materials:
            self.combo.addItem(mat.Label)
            self.combo1.addItem(mat.Label)
            self.combo2.addItem(mat.Label)
        if self.materials:
            self.combo.setCurrentIndex(1)
        for th in self.thicknesses:
            self.combo0t.addItem(th.Label)
            self.combo1t.addItem(th.Label)
            self.combo2t.addItem(th.Label)

    def on_click21(self):
        """Overwrite beso_conf.py file in the macro directory"""

        file_name = os.path.split(self.textbox_file_name.text())[1]
        path = os.path.split(self.textbox_file_name.text())[0]

        fea = ccxtools.FemToolsCcx()
        fea.setup_ccx()
        path_calculix = fea.ccx_binary

        optimization_base = self.combo51.currentText()

        elset_id = self.combo.currentIndex() - 1
        thickness_id = self.combo0t.currentIndex() - 1
        if elset_id != -1:
            if thickness_id != -1:
                elset = self.materials[elset_id].Name + self.thicknesses[
                    thickness_id].Name
            else:  # 0 means None thickness selected
                elset = self.materials[elset_id].Name + "Solid"
            modulus = float(
                self.materials[elset_id].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id].Name)
            poisson = float(
                self.materials[elset_id].Material["PoissonRatio"].split()[0])
            try:
                density = float(self.materials[elset_id].Material["Density"].
                                split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                density = 0.
            try:
                conductivity = float(
                    self.materials[elset_id].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                conductivity = 0.
            try:
                if self.materials[elset_id].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion = float(self.materials[elset_id].
                                      Material["ThermalExpansionCoefficient"].
                                      split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion = float(
                        self.materials[elset_id].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                expansion = 0.
            try:
                specific_heat = float(
                    self.materials[elset_id].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                specific_heat = 0.
            if thickness_id != -1:
                thickness = str(
                    self.thicknesses[thickness_id].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id].Name)
            else:
                thickness = 0.
            optimized = self.checkbox.isChecked()
            if self.textbox.text():
                von_mises = float(self.textbox.text())
            else:
                von_mises = 0.

        elset_id1 = self.combo1.currentIndex() - 1
        thickness_id1 = self.combo0t.currentIndex() - 1
        if elset_id1 != -1:
            if thickness_id1 != -1:
                elset1 = self.materials[elset_id1].Name + self.thicknesses[
                    thickness_id1].Name
            else:  # 0 means None thickness selected
                elset1 = self.materials[elset_id1].Name + "Solid"
            modulus1 = float(
                self.materials[elset_id1].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id1].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id1].Name)
            poisson1 = float(
                self.materials[elset_id1].Material["PoissonRatio"].split()[0])
            try:
                density1 = float(self.materials[elset_id1].Material["Density"].
                                 split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id1].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                density1 = 0.
            try:
                conductivity1 = float(
                    self.materials[elset_id1].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id1].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                conductivity1 = 0.
            try:
                if self.materials[elset_id1].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion1 = float(self.materials[elset_id1].
                                       Material["ThermalExpansionCoefficient"].
                                       split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id1].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion1 = float(
                        self.materials[elset_id1].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                expansion1 = 0.
            try:
                specific_heat1 = float(
                    self.materials[elset_id1].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id1].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                specific_heat1 = 0.
            if thickness_id1 != -1:
                thickness1 = str(
                    self.thicknesses[thickness_id1].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id1].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id1].Name)
            else:
                thickness1 = 0.
            optimized1 = self.checkbox1.isChecked()
            if self.textbox1.text():
                von_mises1 = float(self.textbox1.text())
            else:
                von_mises1 = 0.

        elset_id2 = self.combo2.currentIndex() - 1
        thickness_id2 = self.combo0t.currentIndex() - 1
        if elset_id2 != -1:
            if thickness_id2 != -1:
                elset2 = self.materials[elset_id2].Name + self.thicknesses[
                    thickness_id2].Name
            else:  # 0 means None thickness selected
                else2t = self.materials[elset_id2].Name + "Solid"
            modulus2 = float(
                self.materials[elset_id2].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id2].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id2].Name)
            poisson2 = float(
                self.materials[elset_id2].Material["PoissonRatio"].split()[0])
            try:
                density2 = float(self.materials[elset_id2].Material["Density"].
                                 split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id2].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                density2 = 0.
            try:
                conductivity2 = float(
                    self.materials[elset_id2].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id2].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                conductivity2 = 0.
            try:
                if self.materials[elset_id2].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion2 = float(self.materials[elset_id2].
                                       Material["ThermalExpansionCoefficient"].
                                       split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id2].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion2 = float(
                        self.materials[elset_id2].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                expansion2 = 0.
            try:
                specific_heat2 = float(
                    self.materials[elset_id2].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id2].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                specific_heat2 = 0.
            if thickness_id2 != -1:
                thickness2 = str(
                    self.thicknesses[thickness_id2].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id2].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id2].Name)
            else:
                thickness2 = 0.
            optimized2 = self.checkbox2.isChecked()
            if self.textbox2.text():
                von_mises2 = float(self.textbox2.text())
            else:
                von_mises2 = 0.

        with open(os.path.join(self.beso_dir, "beso_conf.py"), "w") as f:
            f.write(
                "# This is the configuration file with input parameters. It will be executed as python commands\n"
            )
            f.write("# Written by beso_fc_gui.py at {}\n".format(
                datetime.datetime.now()))
            f.write("\n")
            f.write("path_calculix = '{}'\n".format(path_calculix))
            f.write("path = '{}'\n".format(path))
            f.write("file_name = '{}'\n".format(file_name))
            f.write("\n")

            if elset_id != -1:
                f.write("elset_name = '{}'\n".format(elset))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density * 1e-6, density))
                if thickness:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness, thickness))
                if von_mises:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus * 1e-6, poisson, density * 1e-6,
                            conductivity * 1e-6, expansion * 1e-6,
                            specific_heat * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n"
                    .format(modulus, poisson, density, conductivity, expansion,
                            specific_heat))
                f.write("\n")
            if elset_id1 != -1:
                f.write("elset_name = '{}'\n".format(elset1))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized1))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density1 * 1e-6, density1))
                if thickness1:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness1, thickness1))
                if von_mises1:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises1 * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises1))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY"
                    "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus1 * 1e-6, poisson1, density1 * 1e-6,
                            conductivity1 * 1e-6, expansion1 * 1e-6,
                            specific_heat1 * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n"
                    "*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n".
                    format(modulus1, poisson1, density1, conductivity1,
                           expansion1, specific_heat1))
                f.write("\n")
            if elset_id2 != -1:
                f.write("elset_name = '{}'\n".format(elset2))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized2))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density2 * 1e-6, density2))
                if thickness2:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness2, thickness2))
                if von_mises2:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises2 * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises2))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY"
                    "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus2 * 1e-6, poisson2, density2 * 1e-6,
                            conductivity2 * 1e-6, expansion2 * 1e-6,
                            specific_heat2 * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n"
                    .format(modulus2, poisson2, density2, conductivity2,
                            expansion2, specific_heat2))
                f.write("\n")
            f.write("mass_goal_ratio = " + self.textbox52.text())
            f.write("\n")

            f.write("filter_list = [")
            filter = self.combo6.currentText()
            range = self.textbox6.text()
            direction = self.textbox9.text()
            selection = [item.text() for item in self.widget.selectedItems()]
            filter_domains = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains.append(elset)
                if "Domain 1" in selection:
                    filter_domains.append(elset1)
                if "Domain 2" in selection:
                    filter_domains.append(elset2)
            if filter == "simple":
                f.write("['simple', {}".format(range))
                for dn in filter_domains:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter == "casting":
                f.write("['casting', {}, ({})".format(range, direction))
                for dn in filter_domains:
                    f.write(", '{}'".format(dn))
                f.write("],\n")

            filter1 = self.combo7.currentText()
            range1 = self.textbox7.text()
            direction1 = self.textbox10.text()
            selection = [item.text() for item in self.widget1.selectedItems()]
            filter_domains1 = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains1.append(elset)
                if "Domain 1" in selection:
                    filter_domains1.append(elset1)
                if "Domain 2" in selection:
                    filter_domains1.append(elset2)
            if filter1 == "simple":
                f.write("               ['simple', {}".format(range1))
                for dn in filter_domains1:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter1 == "casting":
                f.write("               ['casting', {}, ({})".format(
                    range1, direction1))
                for dn in filter_domains1:
                    f.write(", '{}'".format(dn))
                f.write("],\n")

            filter2 = self.combo8.currentText()
            range2 = self.textbox8.text()
            direction2 = self.textbox11.text()
            selection = [item.text() for item in self.widget2.selectedItems()]
            filter_domains2 = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains2.append(elset)
                if "Domain 1" in selection:
                    filter_domains2.append(elset1)
                if "Domain 2" in selection:
                    filter_domains2.append(elset2)
            if filter2 == "simple":
                f.write("               ['simple', {}".format(range2))
                for dn in filter_domains2:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter2 == "casting":
                f.write("               ['casting', {}, ({})".format(
                    range2, direction2))
                for dn in filter_domains2:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            f.write("               ]\n")
            f.write("\n")

            f.write("optimization_base = '{}'\n".format(optimization_base))
            f.write("\n")

            slider_position = self.slider.value()
            if slider_position == 1:
                f.write("mass_addition_ratio = 0.01\n")
                f.write("mass_removal_ratio = 0.02\n")
            if slider_position == 2:
                f.write("mass_addition_ratio = 0.015\n")
                f.write("mass_removal_ratio = 0.03\n")
            if slider_position == 3:
                f.write("mass_addition_ratio = 0.03\n")
                f.write("mass_removal_ratio = 0.06\n")
            f.write("ratio_type = 'relative'\n")
            f.write("\n")

    def on_click22(self):
        """Open beso_conf.py in FreeCAD editor"""
        FreeCADGui.insert(os.path.join(self.beso_dir, "beso_conf.py"))

    def on_click23(self):
        """"Run optimization"""
        # run in own thread (not freezing FreeCAD):      needs also to comment "plt.show()" on the end of beso_main.py
        # self.optimization_thread = RunOptimization("beso_main")
        # self.optimization_thread.start()

        # run in foreground (freeze FreeCAD)
        exec(open(os.path.join(beso_gui.beso_dir, "beso_main.py")).read())

    def on_click24(self):
        self.on_click21()  # generate beso_conf.py
        self.on_click23()  # run optimization

    def on_click31(self):
        webbrowser.open_new_tab(
            "https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD")

    def on_click32(self):
        webbrowser.open_new_tab(
            "https://github.com/fandaL/beso/blob/master/beso_conf.py")

    def on_click33(self):
        self.close()

    def on_click40(self):
        """Open log file"""
        if self.textbox_file_name.text() in [
                "None analysis file selected", ""
        ]:
            print("None analysis file selected")
        else:
            log_file = os.path.normpath(self.textbox_file_name.text()[:-4] +
                                        ".log")
            webbrowser.open(log_file)

    def on_change(self):
        if self.combo.currentText() == "None":
            self.combo0t.setEnabled(False)
            self.checkbox.setEnabled(False)
            self.textbox.setEnabled(False)
        else:
            self.combo0t.setEnabled(True)
            self.checkbox.setEnabled(True)
            self.textbox.setEnabled(True)

    def on_change1(self):
        if self.combo1.currentText() == "None":
            self.combo1t.setEnabled(False)
            self.checkbox1.setEnabled(False)
            self.textbox1.setEnabled(False)
        else:
            self.combo1t.setEnabled(True)
            self.checkbox1.setEnabled(True)
            self.textbox1.setEnabled(True)

    def on_change2(self):
        if self.combo2.currentText() == "None":
            self.combo2t.setEnabled(False)
            self.checkbox2.setEnabled(False)
            self.textbox2.setEnabled(False)
        else:
            self.combo2t.setEnabled(True)
            self.checkbox2.setEnabled(True)
            self.textbox2.setEnabled(True)

    def on_change6(self):
        if self.combo6.currentText() == "None":
            self.textbox6.setEnabled(False)
            self.textbox9.setEnabled(False)
            self.widget.setEnabled(False)
        elif self.combo6.currentText() == "casting":
            self.textbox6.setEnabled(True)
            self.textbox9.setEnabled(True)
            self.widget.setEnabled(True)
        else:
            self.textbox6.setEnabled(True)
            self.textbox9.setEnabled(False)
            self.widget.setEnabled(True)

    def on_change7(self):
        if self.combo7.currentText() == "None":
            self.textbox7.setEnabled(False)
            self.textbox10.setEnabled(False)
            self.widget1.setEnabled(False)
        elif self.combo7.currentText() == "casting":
            self.textbox7.setEnabled(True)
            self.textbox10.setEnabled(True)
            self.widget1.setEnabled(True)
        else:
            self.textbox7.setEnabled(True)
            self.textbox10.setEnabled(False)
            self.widget1.setEnabled(True)

    def on_change8(self):
        if self.combo8.currentText() == "None":
            self.textbox8.setEnabled(False)
            self.textbox11.setEnabled(False)
            self.widget2.setEnabled(False)
        elif self.combo8.currentText() == "casting":
            self.textbox8.setEnabled(True)
            self.textbox11.setEnabled(True)
            self.widget2.setEnabled(True)
        else:
            self.textbox8.setEnabled(True)
            self.textbox11.setEnabled(False)
            self.widget2.setEnabled(True)
Ejemplo n.º 48
0
 def mouseReleaseEvent(self, event):
     QSlider.mouseReleaseEvent(self, event)
     self.setSliderDown(False)
     self.lowerPressed = QStyle.SC_None
     self.upperPressed = QStyle.SC_None
     self.update()
Ejemplo n.º 49
0
        def __init__(self, U, plot, length=1, title=None):
            super(PlotMainWindow, self).__init__()

            layout = QVBoxLayout()

            if title:
                title = QLabel('<b>' + title + '</b>')
                title.setAlignment(Qt.AlignHCenter)
                layout.addWidget(title)
            layout.addWidget(plot)

            plot.set(U, 0)

            if length > 1:
                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(length - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(length)))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(self.style().standardIcon(QStyle.SP_MediaPlay), 'Play', self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(self.style().standardIcon(QStyle.SP_MediaSeekBackward), 'Rewind', self)
                self.a_toend = QAction(self.style().standardIcon(QStyle.SP_MediaSeekForward), 'End', self)
                self.a_step_backward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipBackward),
                                               'Step Back', self)
                self.a_step_forward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipForward), 'Step', self)
                self.a_loop = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop', self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                if hasattr(self, 'save'):
                    self.a_save = QAction(self.style().standardIcon(QStyle.SP_DialogSaveButton), 'Save', self)
                    toolbar.addAction(self.a_save)
                    self.a_save.triggered.connect(self.save)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            elif hasattr(self, 'save'):
                hlayout = QHBoxLayout()
                toolbar = QToolBar()
                self.a_save = QAction(self.style().standardIcon(QStyle.SP_DialogSaveButton), 'Save', self)
                toolbar.addAction(self.a_save)
                hlayout.addWidget(toolbar)
                layout.addLayout(hlayout)
                self.a_save.triggered.connect(self.save)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
            self.length = length
Ejemplo n.º 50
0
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Select analysis file button
        button = QPushButton('Select analysis file', self)
        button.setToolTip('*.inp CalculiX analysis file.')
        button.move(10, 10)
        button.clicked.connect(self.on_click)

        # Text box - file path and name
        self.textbox_file_name = QLineEdit(self)
        self.textbox_file_name.move(120, 15)
        self.textbox_file_name.resize(420, 20)
        self.textbox_file_name.setText("None analysis file selected")
        self.textbox_file_name.setToolTip('Analysis file.')

        # Update button
        button1 = QPushButton('Update domains', self)
        button1.setToolTip(
            'Update naming inputs and material data from FreeCAD.')
        button1.move(10, 50)
        button1.clicked.connect(self.on_click1)

        # Domains definition

        # Label above domains definition
        label21 = QLabel('Domain 0', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(120, 50)

        label21 = QLabel('Domain 1', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(260, 50)

        label21 = QLabel('Domain 2', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(400, 50)

        label24 = QLabel('Material object', self)
        label24.move(20, 80)

        label25 = QLabel('Thickness object', self)
        label25.move(20, 110)

        label26 = QLabel('As design domain', self)
        label26.move(20, 140)

        label27 = QLabel('Stress limit [MPa]', self)
        label27.move(20, 170)

        # Combo box - select domain by material object
        self.combo = QComboBox(self)
        self.combo.setToolTip('Material object to define the domain.')
        self.combo.move(120, 80)
        self.combo.resize(140, 30)
        self.combo.currentIndexChanged.connect(self.on_change)

        self.combo1 = QComboBox(self)
        self.combo1.setToolTip('Material object to define the domain.')
        self.combo1.move(260, 80)
        self.combo1.resize(140, 30)
        self.combo1.currentIndexChanged.connect(self.on_change1)

        self.combo2 = QComboBox(self)
        self.combo2.setToolTip('Material object to define the domain.')
        self.combo2.move(400, 80)
        self.combo2.resize(140, 30)
        self.combo2.currentIndexChanged.connect(self.on_change2)

        # Combo box - select thickness object
        self.combo0t = QComboBox(self)
        self.combo0t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo0t.move(120, 110)
        self.combo0t.resize(140, 30)

        self.combo1t = QComboBox(self)
        self.combo1t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo1t.move(260, 110)
        self.combo1t.resize(140, 30)

        self.combo2t = QComboBox(self)
        self.combo2t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo2t.move(400, 110)
        self.combo2t.resize(140, 30)

        self.textbox3 = QLineEdit(self)
        self.textbox3.move(120, 170)
        self.textbox3.resize(40, 20)
        # self.textbox3.setText("")
        self.textbox3.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox4 = QLineEdit(self)
        self.textbox4.move(260, 170)
        self.textbox4.resize(40, 20)
        # self.textbox4.setText("")
        self.textbox4.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox5 = QLineEdit(self)
        self.textbox5.move(400, 170)
        self.textbox5.resize(40, 20)
        # self.textbox5.setText("")
        self.textbox5.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        # Check box - design or nondesign
        self.checkbox = QCheckBox('', self)
        self.checkbox.setChecked(True)
        self.checkbox.setToolTip('Check to be the design domain.')
        self.checkbox.move(120, 140)

        self.checkbox1 = QCheckBox('', self)
        self.checkbox1.setChecked(True)
        self.checkbox1.setToolTip('Check to be the design domain.')
        self.checkbox1.move(260, 140)

        self.checkbox2 = QCheckBox('', self)
        self.checkbox2.setChecked(True)
        self.checkbox2.setToolTip('Check to be the design domain.')
        self.checkbox2.move(400, 140)

        # Text box - stress limit
        self.textbox = QLineEdit(self)
        self.textbox.move(120, 170)
        self.textbox.resize(40, 20)
        # self.textbox.setText("")
        self.textbox.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox1 = QLineEdit(self)
        self.textbox1.move(260, 170)
        self.textbox1.resize(40, 20)
        # self.textbox1.setText("")
        self.textbox1.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox2 = QLineEdit(self)
        self.textbox2.move(400, 170)
        self.textbox2.resize(40, 20)
        # self.textbox2.setText("")
        self.textbox2.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        # Filters

        # Label above filter definition
        label31 = QLabel('Filter 0', self)
        label31.setStyleSheet("font-weight: bold")
        label31.move(120, 210)

        label32 = QLabel('Filter 1', self)
        label32.setStyleSheet("font-weight: bold")
        label32.move(260, 210)

        label33 = QLabel('Filter 2', self)
        label33.setStyleSheet("font-weight: bold")
        label33.move(400, 210)

        label34 = QLabel('Type', self)
        label34.move(20, 240)

        label35 = QLabel('Range [mm]', self)
        label35.move(20, 270)

        label36 = QLabel('Direction vector', self)
        label36.move(20, 300)

        label37 = QLabel('Apply to', self)
        label37.move(20, 330)

        # Combo box - select filter type
        self.combo6 = QComboBox(self)
        self.combo6.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo6.addItem("None")
        self.combo6.addItem("simple")
        self.combo6.addItem("casting")
        self.combo6.setCurrentIndex(1)
        self.combo6.move(120, 240)
        self.combo6.currentIndexChanged.connect(self.on_change6)

        self.combo7 = QComboBox(self)
        self.combo7.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo7.addItem("None")
        self.combo7.addItem("simple")
        self.combo7.addItem("casting")
        self.combo7.move(260, 240)
        self.combo7.currentIndexChanged.connect(self.on_change7)

        self.combo8 = QComboBox(self)
        self.combo8.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo8.addItem("None")
        self.combo8.addItem("simple")
        self.combo8.addItem("casting")
        self.combo8.move(400, 240)
        self.combo8.currentIndexChanged.connect(self.on_change8)

        # Text box - filter range
        self.textbox6 = QLineEdit(self)
        self.textbox6.move(120, 270)
        self.textbox6.resize(50, 20)
        # self.textbox6.setText("")
        self.textbox6.setToolTip(
            'Filter range [mm], recommended two times mesh size.')

        self.textbox7 = QLineEdit(self)
        self.textbox7.move(260, 270)
        self.textbox7.resize(50, 20)
        # self.textbox7.setText("")
        self.textbox7.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox7.setEnabled(False)

        self.textbox8 = QLineEdit(self)
        self.textbox8.move(400, 270)
        self.textbox8.resize(50, 20)
        # self.textbox8.setText("")
        self.textbox8.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox8.setEnabled(False)

        # Text box - casting direction
        self.textbox9 = QLineEdit(self)
        self.textbox9.move(120, 300)
        self.textbox9.resize(80, 20)
        self.textbox9.setText("0, 0, 1")
        self.textbox9.setEnabled(False)
        self.textbox9.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox10 = QLineEdit(self)
        self.textbox10.move(260, 300)
        self.textbox10.resize(80, 20)
        self.textbox10.resize(80, 20)
        self.textbox10.setText("0, 0, 1")
        self.textbox10.setEnabled(False)
        self.textbox10.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox11 = QLineEdit(self)
        self.textbox11.move(400, 300)
        self.textbox11.resize(80, 20)
        self.textbox11.setText("0, 0, 1")
        self.textbox11.setEnabled(False)
        self.textbox11.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        # list widget - select domains
        self.widget = QListWidget(self)
        self.widget.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget.move(120, 330)
        self.widget.resize(140, 120)
        self.widget.setSelectionMode(QAbstractItemView.MultiSelection)

        self.widget1 = QListWidget(self)
        self.widget1.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget1.move(260, 330)
        self.widget1.resize(140, 120)
        self.widget1.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget1.setEnabled(False)

        self.widget2 = QListWidget(self)
        self.widget2.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget2.move(400, 330)
        self.widget2.resize(140, 120)
        self.widget2.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget2.setEnabled(False)

        # Other settings
        label40 = QLabel('Other settings', self)
        label40.setStyleSheet("font-weight: bold")
        label40.move(10, 470)

        # AR, RR slider
        label41 = QLabel('Change per iteration:   low', self)
        label41.setFixedWidth(150)
        label41.move(10, 500)
        label42 = QLabel('high', self)
        label42.move(240, 500)

        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(1, 3)
        self.slider.setSingleStep(1)
        self.slider.setValue(2)
        self.slider.move(150, 500)
        self.slider.resize(80, 30)
        self.slider.setToolTip(
            'Sets mass change per iteration, which is controlled as\n'
            'slow:   mass_addition_ratio=0.01,  mass_removal_ratio=0.02\n'
            'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n'
            'fast:   mass_addition_ratio=0.03,  mass_removal_ratio=0.06')

        # optimization base combobox
        label51 = QLabel('Optimization base', self)
        label51.move(10, 530)
        self.combo51 = QComboBox(self)
        self.combo51.setToolTip(
            'Basic principle to determine if element should remain or be removed:\n'
            '"stiffness" to maximize stiffness (minimize compliance),\n'
            '"heat" to maximize heat flow.')
        self.combo51.addItem("stiffness")
        self.combo51.addItem("heat")
        self.combo51.move(120, 530)

        # mass goal ratio
        label52 = QLabel('Mass goal ratio', self)
        label52.move(10, 560)
        self.textbox52 = QLineEdit(self)
        self.textbox52.move(120, 560)
        self.textbox52.resize(50, 20)
        self.textbox52.setText("0.4")
        self.textbox52.setToolTip(
            'Fraction of all design domains masses to be achieved;\n'
            'between 0 and 1.')

        # generate conf. file button
        button21 = QPushButton('Generate conf. file', self)
        button21.setToolTip(
            'Writes configuration file with optimization parameters.')
        button21.move(10, 600)
        button21.clicked.connect(self.on_click21)

        # edit conf. file button
        button22 = QPushButton('Edit conf. file', self)
        button22.setToolTip('Opens configuration file for hand modifications.')
        button22.move(10, 630)
        button22.clicked.connect(self.on_click22)

        # run optimization button
        button23 = QPushButton('Run optimization', self)
        button23.setToolTip('Writes configuration file and runs optimization.')
        button23.move(10, 660)
        button23.clicked.connect(self.on_click23)

        # generate conf file and run optimization button
        button24 = QPushButton('Generate conf.\nfile and run\noptimization',
                               self)
        button24.setToolTip('Writes configuration file and runs optimization.')
        button24.move(120, 600)
        button24.resize(100, 90)
        button24.clicked.connect(self.on_click24)

        # help buttons
        label41 = QLabel('Help', self)
        label41.move(440, 560)

        button31 = QPushButton('Example', self)
        button31.setToolTip(
            'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD')
        button31.move(440, 590)
        # button31.resize(80, 50)
        button31.clicked.connect(self.on_click31)

        button32 = QPushButton('Conf. comments', self)
        button32.setToolTip(
            'https://github.com/fandaL/beso/blob/master/beso_conf.py')
        button32.move(440, 620)
        # button32.resize(80, 50)
        button32.clicked.connect(self.on_click32)

        button33 = QPushButton('Close', self)
        button33.move(440, 690)
        # button33.resize(80, 50)
        button33.clicked.connect(self.on_click33)

        # open log file
        button40 = QPushButton('Open log file', self)
        button40.setToolTip('Opens log file in your text editor.\n'
                            '(Does not refresh automatically.)')
        button40.move(10, 690)
        button40.clicked.connect(self.on_click40)

        self.on_click1()  # first update
        self.show()
Ejemplo n.º 51
0
class MainWindow(QMainWindow):
    """docstring for MainWindow"""
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.serviceProvider = 0
        self.popupMenu = None
        self.mapControlButtons = []
        self.mapControlTypes = []
        self.markerObjects = []
        self.setWindowTitle(self.tr('Map Viewer Demo'))

        self.routingManager = None
        self.mapManager = None
        self.mapWidget = None
        self.markerIcon = None
        self.slider = None

        manager = QNetworkConfigurationManager()

        canStartIAP = manager.capabilities() & QNetworkConfigurationManager.CanStartAndStopInterfaces

        configuration = manager.defaultConfiguration()

        if not configuration.isValid or (not canStartIAP and configuration.starte() != QNetworkConfiguration.Active):
            QMessageBox.information(self, self.tr('Map Viewer Demo'),
                                    self.tr('Available Access Points not found.'))
            return

        self.session = QNetworkSession(configuration, self)
        self.session.opened.connect(self.networkSessionOpened)
        self.session.error.connect(self.error)

        self.session.open()
        self.session.waitForOpened()

        self.setProvider('nokia')
        self.setupUi()

    def networkSessionOpened(self):
        pass

    def sliderValueChanged(self, value):
        self.mapWidget.setZoomLevel(value)

    def mapZoomLevelChanged(self, level):
        self.slider.setSliderPosition(int(level))

    def mapTypeChanged(self, newType):
        index = self.mapControlTypes.index(newType)
        if index != -1:
            self.mapControButtons[index].setChecked(True)

    def mapTypeToggled(self, checked):
        if checked:
            button = self.sender()
            index = self.mapControlButtons.index(button)
            if index != -1:
                print index, self.mapControlTypes[index]
                self.mapWidget.setMapType(self.mapControlTypes[index])

    def updateCoords(self, coords):
        if not coords.isValid():
            return

        self.latitudeEdit.setText('%f' % coords.latitude())
        self.longitudeEdit.setText('%f' % coords.longitude())

    def setCoordsClicked(self):
        lat = float(self.latitudeEdit.text())
        lon = float(self.longitudeEdit.text())
        self.mapWidget.setCenter(QGeoCoordinate(lat, lon))

    def setProvider(self, providerId):
        self.serviceProvider = QGeoServiceProvider(providerId)
        if self.serviceProvider.error() != QGeoServiceProvider.NoError:
            QMessageBox.information(self, self.tr('MapViewer Example'),
                                    self.tr('Unable to dinf the %s geoservices plugin.' % providerId))

            qApp.quit()
            return

        self.mapManager = self.serviceProvider.mappingManager()
        self.routingManager = self.serviceProvider.routingManager()

    def error(self, error):
        if error == QNetworkSession.UnknownSessionError:
            msgBox = QMessageBox(self.parent())
            msgBox.setText('This application requires network access to function.')
            msgBox.setInformativeText('Press Cancel to quit the application.')
            msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel)
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setDefaultButton(QMessageBox.Retry)
            ret = msgBox.exec_()
            if ret == QMessageBox.Retry:
                QTimer.singleShot(0, self.session.open)
            elif ret == QMessageBox.Cancel:
                self.close()
        elif error == QNetworkSession.SessionAbortedError:
            msgBox = QMessageBox(self.parent())
            msgBox.setText('Out of range of network')
            msgBox.setInformativeText('Move back into range and press Retry, or press Cancel to quit the application')
            msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel)
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setDefaultButton(QMessageBox.Retry)
            ret = msgBox.exec_()
            if ret == QMessageBox.Retry:
                QTimer.singleShot(0, self.session.open)
            elif ret == QMessageBox.Cancel:
                self.close()


    def setupUi(self):

        scene = QGraphicsScene(self)
        self.view = QGraphicsView(scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVisible(True)
        self.view.setInteractive(True)

        self.createPixmapIcon()

        self.mapWidget = MapWidget(self.mapManager)
        scene.addItem(self.mapWidget)
        self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95))
        self.mapWidget.setZoomLevel(5)

        #...
        self.slider = QSlider(Qt.Vertical, self)
        self.slider.setTickInterval(1)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setMaximum(self.mapManager.maximumZoomLevel())
        self.slider.setMinimum(self.mapManager.minimumZoomLevel())

        self.slider.valueChanged[int].connect(self.sliderValueChanged)
        self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged)

        mapControlLayout = QVBoxLayout()

        self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged)

        for mapType in self.mapWidget.supportedMapTypes():
            radio = QRadioButton(self)
            if mapType == QGraphicsGeoMap.StreetMap:
                radio.setText('Street')
            elif mapType == QGraphicsGeoMap.SatelliteMapDay:
                radio.setText('Sattelite')
            elif mapType == QGraphicsGeoMap.SatelliteMapNight:
                radio.setText('Sattelite - Night')
            elif mapType == QGraphicsGeoMap.TerrainMap:
                radio.setText('Terrain')

            if mapType == self.mapWidget.mapType():
                radio.setChecked(True)

            radio.toggled[bool].connect(self.mapTypeToggled)

            self.mapControlButtons.append(radio)
            self.mapControlTypes.append(mapType)
            mapControlLayout.addWidget(radio)

        self.latitudeEdit = QLineEdit()
        self.longitudeEdit = QLineEdit()

        formLayout = QFormLayout()
        formLayout.addRow('Latitude', self.latitudeEdit)
        formLayout.addRow('Longitude', self.longitudeEdit)

        self.captureCoordsButton = QToolButton()
        self.captureCoordsButton.setText('Capture coordinates')
        self.captureCoordsButton.setCheckable(True)

        self.captureCoordsButton.toggled[bool].connect(
                self.mapWidget.setMouseClickCoordQuery)
        self.mapWidget.coordQueryResult.connect(self.updateCoords)

        self.setCoordsButton = QPushButton()
        self.setCoordsButton.setText('Set coordinates')
        self.setCoordsButton.clicked.connect(self.setCoordsClicked)

        buttonLayout = QHBoxLayout()

        buttonLayout.addWidget(self.captureCoordsButton)
        buttonLayout.addWidget(self.setCoordsButton)

        coordControlLayout = QVBoxLayout()
        coordControlLayout.addLayout(formLayout)
        coordControlLayout.addLayout(buttonLayout)

        widget = QWidget(self)
        layout = QGridLayout()
        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, 0)

        topLayout = QGridLayout()
        bottomLayout = QGridLayout()

        topLayout.setColumnStretch(0, 0)
        topLayout.setColumnStretch(1, 1)

        bottomLayout.setColumnStretch(0, 0)
        bottomLayout.setColumnStretch(1, 1)

        topLayout.addWidget(self.slider, 0, 0)
        topLayout.addWidget(self.view, 0, 1)

        bottomLayout.addLayout(mapControlLayout, 0, 0)
        bottomLayout.addLayout(coordControlLayout, 0, 1)

        layout.addLayout(topLayout, 0, 0)
        layout.addLayout(bottomLayout, 1, 0)

        self.layout = layout
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)

        self.view.customContextMenuRequested.connect(self.customContextMenuRequest)

    def createPixmapIcon(self):
        self.markerIcon = QPixmap(MARKER_WIDTH, MARKER_HEIGHT)
        self.markerIcon.fill(Qt.transparent)

        painter = QPainter(self.markerIcon)

        p1 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1)
        p2 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1 - MARKER_PIN_LEN)
        pen = QPen(Qt.black)
        pen.setWidth(2)
        pen.setCosmetic(True)
        painter.setPen(pen)
        painter.drawLine(p1, p2)
        ellipse = QRect(0, 0, MARKER_WIDTH - 1, MARKER_HEIGHT - 1)
        pen.setWidth(1)
        painter.setPen(pen)
        color = QColor(Qt.green)
        color.setAlpha(127)
        brush = QBrush(color)
        painter.setBrush(brush)
        painter.drawEllipse(ellipse)

    def resizeEvent(self, event):
        self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size()))
        self.mapWidget.resize(self.view.size())

    def showEvent(self, event):
        self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size()))
        self.mapWidget.resize(self.view.size())

    def createMenus(self):
        self.popupMenu = QMenu(self)

        # Markers
        subMenuItem = QMenu(self.tr('Marker'), self)
        self.popupMenu.addMenu(subMenuItem)

        menuItem = QAction(self.tr('Set marker'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.drawPixmap)

        menuItem = QAction(self.tr('Remove marker'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.removePixmaps)

        menuItem = QAction(self.tr('Select objects'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.selectObjects)

        # Draw
        subMenuItem = QMenu(self.tr('Draw'), self)
        self.popupMenu.addMenu(subMenuItem)

        menuItem = QAction(self.tr('Rectangle'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.drawRect)

        menuItem = QAction(self.tr('Polyline'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.drawPolyline)

        menuItem = QAction(self.tr('Polygon'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.drawPolygon)

        menuItem = QAction(self.tr('Circle'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.drawCircle)

        menuItem = QAction(self.tr('Text'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.drawText)

        # Routing
        subMenuItem = QMenu(self.tr('Route'), self)
        self.popupMenu.addMenu(subMenuItem)

        menuItem = QAction(self.tr('Calculate route'), self)
        subMenuItem.addAction(menuItem)
        menuItem.triggered[bool].connect(self.calculateRoute)

    def selectObjects(self):
        for obj in self.mapWidget.mapObjects():
            obj.setSelected(False)

        if len(self.markerObjects) < 2:
            return

        bottomRight = self.markerObjects.pop()
        topLeft = self.markerObjects.pop()

        self.mapWidget.removeMapObject(topLeft)
        self.mapWidget.removeMapObject(bottomRight)

        selectedObjects = self.mapWidget.mapObjectsInScreenRect(
                    QRectF(self.mapWidget.coordinateToScreenPosition(topLeft.coordinate()),
                           self.mapWidget.coordinateToScreenPosition(bottomRight.coordinate()))
                )

        for obj in selectedObjects:
            obj.setSelected(True)

    def drawRect(self):
        if len(self.markerObjects) < 2:
            return

        p1, p2 = self.markerObjects[:2]

        pen = QPen(Qt.white)
        pen.setWidth(2)
        pen.setCosmetic(True)
        fill = QColor(Qt.black)
        fill.setAlpha(65)
        rectangle = QGeoMapRectangleObject(p1.coordinate(), p2.coordinate())
        rectangle.setPen(pen)
        rectangle.setBrush(QBrush(fill))
        self.mapWidget.addMapObject(rectangle)

    def drawPolyline(self):
        path = [mark.coordinate() for mark in self.markerObjects]

        pen = QPen(Qt.white)
        pen.setWidth(2)
        pen.setCosmetic(True)
        polyline = QGeoMapPolylineObject()
        polyline.setPen(pen)
        polyline.setPath(path)

        self.mapWidget.addMapObject(polyline)

    def drawPolygon(self):
        path = [mark.coordinate() for mark in self.markerObjects]

        pen = QPen(Qt.white)
        pen.setWidth(2)
        pen.setCosmetic(True)
        polygon = QGeoMapPolygonObject()
        polygon.setPen(pen)
        fill = QColor(Qt.black)
        fill.setAlpha(65)
        polygon.setBrush(QBrush(fill))
        polygon.setPath(path)

        self.mapWidget.addMapObject(polygon)

    def drawCircle(self):

        if not len(self.markerObjects):
            return

        p1 = self.markerObjects[0]
        center = p1.coordinate()

        radius = 3000 # Meters

        if len(self.markerObjects) >= 2:
            radius = center.distanceTo(self.markerObjects[1].coordinate())

        pen = QPen(Qt.white)
        pen.setWidth(2)
        pen.setCosmetic(True)
        circle = QGeoMapCircleObject(center, radius)
        circle.setPen(pen)
        fill = QColor(Qt.black)
        fill.setAlpha(65)
        circle.setBrush(QBrush(fill))

        self.mapWidget.addMapObject(circle)

    def drawText(self):

        if not len(self.markerObjects):
            return

        start = self.markerObjects[0].coordinate()

        text = QGeoMapTextObject(start, 'Text')

        fill = QColor(Qt.black)
        text.setBrush(fill)
        self.mapWidget.addMapObject(text)

    def calculateRoute(self):
        if len(self.markerObjects) < 2:
            return

        waypoints = [x.coordinate() for x in self.markerObjects[:2]]

        request = QGeoRouteRequest(waypoints)
        self.routeReply = self.routingManager.calculateRoute(request)
        self.routeReply.finished.connect(self.routeFinished)

    def routeFinished(self):

        if not self.routeReply.routes():
            return

        route = QGeoMapRouteObject(self.routeReply.routes()[0])
        routeColor = QColor(Qt.blue)
        routeColor.setAlpha(127)
        pen = QPen(routeColor)
        pen.setWidth(7)
        pen.setCosmetic(True)
        pen.setCapStyle(Qt.RoundCap)
        route.setPen(pen)
        self.mapWidget.addMapObject(route)

    def drawPixmap(self):
        marker = QGeoMapPixmapObject(self.mapWidget.screenPositionToCoordinate(self.lastClicked),
                                    QPoint(-(MARKER_WIDTH / 2), -MARKER_HEIGHT), self.markerIcon)
        self.mapWidget.addMapObject(marker)
        self.markerObjects.append(marker)

    def removePixmaps(self):
        for i in range(len(self.markerObjects)):
            marker = self.markerObjects.pop()

            self.mapWidget.removeMapObject(marker)
            marker.deleteLater()

    def customContextMenuRequest(self, point):
        self.lastClicked = point
        if self.focusWidget() == self.view:
            if not self.popupMenu:
                self.createMenus()

            self.popupMenu.popup(self.view.mapToGlobal(self.lastClicked))
Ejemplo n.º 52
0
    class PlotMainWindow(QWidget):
        """Base class for plot main windows."""

        def __init__(self, U, plot, length=1, title=None):
            super().__init__()

            layout = QVBoxLayout()

            if title:
                title = QLabel('<b>' + title + '</b>')
                title.setAlignment(Qt.AlignHCenter)
                layout.addWidget(title)
            layout.addWidget(plot)

            plot.set(U, 0)

            if length > 1:
                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(length - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(length)))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(self.style().standardIcon(QStyle.SP_MediaPlay), 'Play', self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(self.style().standardIcon(QStyle.SP_MediaSeekBackward), 'Rewind', self)
                self.a_toend = QAction(self.style().standardIcon(QStyle.SP_MediaSeekForward), 'End', self)
                self.a_step_backward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipBackward),
                                               'Step Back', self)
                self.a_step_forward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipForward), 'Step', self)
                self.a_loop = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop', self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                if hasattr(self, 'save'):
                    self.a_save = QAction(self.style().standardIcon(QStyle.SP_DialogSaveButton), 'Save', self)
                    toolbar.addAction(self.a_save)
                    self.a_save.triggered.connect(self.save)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            elif hasattr(self, 'save'):
                hlayout = QHBoxLayout()
                toolbar = QToolBar()
                self.a_save = QAction(self.style().standardIcon(QStyle.SP_DialogSaveButton), 'Save', self)
                toolbar.addAction(self.a_save)
                hlayout.addWidget(toolbar)
                layout.addLayout(hlayout)
                self.a_save.triggered.connect(self.save)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
            self.length = length

        def slider_changed(self, ind):
            self.plot.set(self.U, ind)

        def speed_changed(self, val):
            self.timer.setInterval(val * 20)

        def update_solution(self):
            ind = self.slider.value() + 1
            if ind >= self.length:
                if self.a_loop.isChecked():
                    ind = 0
                else:
                    self.a_play.setChecked(False)
                    return
            self.slider.setValue(ind)

        def toggle_play(self, checked):
            if checked:
                if self.slider.value() + 1 == self.length:
                    self.slider.setValue(0)
                self.timer.start()
            else:
                self.timer.stop()

        def rewind(self):
            self.slider.setValue(0)

        def to_end(self):
            self.a_play.setChecked(False)
            self.slider.setValue(self.length - 1)

        def step_forward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() + 1
            if ind == self.length and self.a_loop.isChecked():
                ind = 0
            if ind < self.length:
                self.slider.setValue(ind)

        def step_backward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() - 1
            if ind == -1 and self.a_loop.isChecked():
                ind = self.length - 1
            if ind >= 0:
                self.slider.setValue(ind)
Ejemplo n.º 53
0
    def __init__(self, *args, **kwargs):

        self.minimum = 1
        self.maximum = 100
        self.lineEditMaximum = 10000

        QMainWindow.__init__(self, *args, **kwargs)
        self.installEventFilter(self)
        #self.setWindowFlags( QtCore.Qt.Drawer )
        self.setWindowTitle(Window_global.title)

        widgetMain = QWidget()
        layoutVertical = QVBoxLayout(widgetMain)
        self.setCentralWidget(widgetMain)

        layoutSlider = QHBoxLayout()
        lineEdit = QLineEdit()
        lineEdit.setFixedWidth(100)
        lineEdit.setText(str(1))
        validator = QIntValidator(self.minimum, self.lineEditMaximum, self)
        lineEdit.setValidator(validator)
        slider = QSlider()
        slider.setOrientation(QtCore.Qt.Horizontal)
        slider.setMinimum(self.minimum)
        slider.setMaximum(self.maximum)
        layoutSlider.addWidget(lineEdit)
        layoutSlider.addWidget(slider)
        layoutAngle = QVBoxLayout()
        checkBox = QCheckBox('Connect Angle By Tangent')
        layoutVector = QHBoxLayout()
        leVx = QLineEdit()
        leVx.setText(str(1.000))
        leVx.setEnabled(False)
        leVx.setValidator(QDoubleValidator(-100, 100, 5, self))
        leVy = QLineEdit()
        leVy.setText(str(0.000))
        leVy.setEnabled(False)
        leVy.setValidator(QDoubleValidator(-100, 100, 5, self))
        leVz = QLineEdit()
        leVz.setText(str(0.000))
        leVz.setEnabled(False)
        leVz.setValidator(QDoubleValidator(-100, 100, 5, self))
        layoutAngle.addWidget(checkBox)
        layoutAngle.addLayout(layoutVector)
        layoutVector.addWidget(leVx)
        layoutVector.addWidget(leVy)
        layoutVector.addWidget(leVz)
        button = QPushButton('Create')

        layoutVertical.addLayout(layoutSlider)
        layoutVertical.addLayout(layoutAngle)
        layoutVertical.addWidget(button)

        QtCore.QObject.connect(slider, QtCore.SIGNAL('valueChanged(int)'),
                               self.sliderValueChanged)
        QtCore.QObject.connect(lineEdit, QtCore.SIGNAL('textEdited(QString)'),
                               self.lineEditValueChanged)
        QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'),
                               Functions.createPointOnCurve)
        QtCore.QObject.connect(checkBox, QtCore.SIGNAL('clicked()'),
                               Functions.setAngleEnabled)
        self.slider = slider
        self.lineEdit = lineEdit

        Window_global.slider = slider
        Window_global.button = button
        Window_global.checkBox = checkBox
        Window_global.leVx = leVx
        Window_global.leVy = leVy
        Window_global.leVz = leVz
Ejemplo n.º 54
0
class RadioApp(QWidget):
    def __init__(self):
        super().__init__()
        self.edit = False

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def rds_tmshow(self, hodiny, minuty):
        print("{}:{}".format(hodiny, minuty))
Ejemplo n.º 55
0
    def setupUi(self):

        scene = QGraphicsScene(self)
        self.view = QGraphicsView(scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVisible(True)
        self.view.setInteractive(True)

        self.createPixmapIcon()

        self.mapWidget = MapWidget(self.mapManager)
        scene.addItem(self.mapWidget)
        self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95))
        self.mapWidget.setZoomLevel(5)

        #...
        self.slider = QSlider(Qt.Vertical, self)
        self.slider.setTickInterval(1)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setMaximum(self.mapManager.maximumZoomLevel())
        self.slider.setMinimum(self.mapManager.minimumZoomLevel())

        self.slider.valueChanged[int].connect(self.sliderValueChanged)
        self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged)

        mapControlLayout = QVBoxLayout()

        self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged)

        for mapType in self.mapWidget.supportedMapTypes():
            radio = QRadioButton(self)
            if mapType == QGraphicsGeoMap.StreetMap:
                radio.setText('Street')
            elif mapType == QGraphicsGeoMap.SatelliteMapDay:
                radio.setText('Sattelite')
            elif mapType == QGraphicsGeoMap.SatelliteMapNight:
                radio.setText('Sattelite - Night')
            elif mapType == QGraphicsGeoMap.TerrainMap:
                radio.setText('Terrain')

            if mapType == self.mapWidget.mapType():
                radio.setChecked(True)

            radio.toggled[bool].connect(self.mapTypeToggled)

            self.mapControlButtons.append(radio)
            self.mapControlTypes.append(mapType)
            mapControlLayout.addWidget(radio)

        self.latitudeEdit = QLineEdit()
        self.longitudeEdit = QLineEdit()

        formLayout = QFormLayout()
        formLayout.addRow('Latitude', self.latitudeEdit)
        formLayout.addRow('Longitude', self.longitudeEdit)

        self.captureCoordsButton = QToolButton()
        self.captureCoordsButton.setText('Capture coordinates')
        self.captureCoordsButton.setCheckable(True)

        self.captureCoordsButton.toggled[bool].connect(
                self.mapWidget.setMouseClickCoordQuery)
        self.mapWidget.coordQueryResult.connect(self.updateCoords)

        self.setCoordsButton = QPushButton()
        self.setCoordsButton.setText('Set coordinates')
        self.setCoordsButton.clicked.connect(self.setCoordsClicked)

        buttonLayout = QHBoxLayout()

        buttonLayout.addWidget(self.captureCoordsButton)
        buttonLayout.addWidget(self.setCoordsButton)

        coordControlLayout = QVBoxLayout()
        coordControlLayout.addLayout(formLayout)
        coordControlLayout.addLayout(buttonLayout)

        widget = QWidget(self)
        layout = QGridLayout()
        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, 0)

        topLayout = QGridLayout()
        bottomLayout = QGridLayout()

        topLayout.setColumnStretch(0, 0)
        topLayout.setColumnStretch(1, 1)

        bottomLayout.setColumnStretch(0, 0)
        bottomLayout.setColumnStretch(1, 1)

        topLayout.addWidget(self.slider, 0, 0)
        topLayout.addWidget(self.view, 0, 1)

        bottomLayout.addLayout(mapControlLayout, 0, 0)
        bottomLayout.addLayout(coordControlLayout, 0, 1)

        layout.addLayout(topLayout, 0, 0)
        layout.addLayout(bottomLayout, 1, 0)

        self.layout = layout
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)

        self.view.customContextMenuRequested.connect(self.customContextMenuRequest)
class DataInspector(QMainWindow):
    """
    DataInspector main class
    """
    def __init__(self):
        super(DataInspector, self).__init__()

        self.slider_width = +300

        self.main_widget = QWidget(self)
        self.setCentralWidget(self.main_widget)
        self.render_widget = RenderWidget()

        # Create interface actions
        self.action_load_data = QAction('Load data set',
                                        self,
                                        shortcut='Ctrl+O')
        self.action_load_data.setIcon(QIcon("images/AddButton.png"))
        self.action_load_data.triggered.connect(self.load_file)
        self.action_show_simple = QAction('Switch to simple rendering',
                                          self,
                                          shortcut='Ctrl+1')
        self.action_show_simple.setText("Simple")
        self.action_show_simple.triggered.connect(self.switch_to_simple)
        self.action_show_ct = QAction('Switch to CT rendering',
                                      self,
                                      shortcut='Ctrl+2')
        self.action_show_ct.setText("CT")
        self.action_show_ct.triggered.connect(self.switch_to_ct)
        self.action_show_mip = QAction('Switch to MIP rendering',
                                       self,
                                       shortcut='Ctrl+3')
        self.action_show_mip.setText("MIP")
        self.action_show_mip.triggered.connect(self.switch_to_mip)

        # Align the dock buttons to the right with a spacer widget
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # Add buttons to container on top
        self.toolbar = self.addToolBar('Main tools')
        self.toolbar.addAction(self.action_show_simple)
        self.toolbar.addAction(self.action_show_ct)
        self.toolbar.addAction(self.action_show_mip)

        self.toolbar.addWidget(spacer)
        self.toolbar.addAction(self.action_load_data)
        self.setUnifiedTitleAndToolBarOnMac(True)

        # Slider for simple visualization
        self.sliders_simple_widget = QSlider(Qt.Horizontal)
        self.sliders_simple_widget.setMinimumWidth(self.slider_width)
        self.sliders_simple_widget.setMaximumWidth(self.slider_width)
        self.sliders_simple_widget.setMinimum(0)
        self.sliders_simple_widget.setMaximum(1000)
        self.sliders_simple_widget.valueChanged.connect(
            self.simple_slider_value_changed)
        self.sliders_simple_widget.setHidden(True)

        # Create sliders for CT transfer function
        sliders_layout = QVBoxLayout()
        sliders_layout.setContentsMargins(0, 0, 0, 0)
        sliders_layout.setSpacing(0)
        self.sliders = []
        for _ in range(0, 7):
            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(1000)
            slider.valueChanged.connect(self.ct_slider_value_changed)
            self.sliders.append(slider)
            sliders_layout.addWidget(slider)

        self.sliders_ct_widget = QWidget()
        self.sliders_ct_widget.setMinimumWidth(self.slider_width)
        self.sliders_ct_widget.setMaximumWidth(self.slider_width)
        self.sliders_ct_widget.setLayout(sliders_layout)
        self.sliders_ct_widget.setHidden(True)

        self.min_slider = QSlider(Qt.Horizontal)
        self.min_slider.setMinimum(0)
        self.min_slider.setMaximum(1000)
        self.min_slider.valueChanged.connect(self.mip_slider_value_changed)

        self.max_slider = QSlider(Qt.Horizontal)
        self.max_slider.setMinimum(0)
        self.max_slider.setMaximum(1000)
        self.max_slider.setValue(1000)
        self.max_slider.valueChanged.connect(self.mip_slider_value_changed)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.min_slider)
        layout.addWidget(self.max_slider)

        self.sliders_mip_widget = QWidget()
        self.sliders_mip_widget.setMinimumWidth(self.slider_width)
        self.sliders_mip_widget.setMaximumWidth(self.slider_width)
        self.sliders_mip_widget.setLayout(layout)
        self.sliders_mip_widget.setHidden(True)

        layout = QHBoxLayout(self.main_widget)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.render_widget)
        layout.addWidget(self.sliders_mip_widget)
        layout.addWidget(self.sliders_ct_widget)
        layout.addWidget(self.sliders_simple_widget)
        self.main_widget.setLayout(layout)

        self.resize(800, 500)

    def switch_to_simple(self):
        """
        Switch the visualization style to a simple transfer function
        """
        self.render_widget.set_render_type(RenderTypeSimple)

        self.sliders_simple_widget.setDisabled(False)
        self.sliders_ct_widget.setDisabled(True)
        self.sliders_mip_widget.setDisabled(True)

        self.sliders_simple_widget.setHidden(False)
        self.sliders_ct_widget.setHidden(True)
        self.sliders_mip_widget.setHidden(True)

    def switch_to_ct(self):
        """
        Switch to a visualization style that should work pretty ok
        for CT datasets
        """
        self.render_widget.set_render_type(RenderTypeCT)

        self.sliders_simple_widget.setDisabled(True)
        self.sliders_ct_widget.setDisabled(False)
        self.sliders_mip_widget.setDisabled(True)

        self.sliders_simple_widget.setHidden(True)
        self.sliders_ct_widget.setHidden(False)
        self.sliders_mip_widget.setHidden(True)

    def switch_to_mip(self):
        """
        Switch to Maximum intensity projection visualization type
        """
        self.render_widget.set_render_type(RenderTypeMIP)

        self.sliders_simple_widget.setDisabled(True)
        self.sliders_ct_widget.setDisabled(True)
        self.sliders_mip_widget.setDisabled(False)

        self.sliders_simple_widget.setHidden(True)
        self.sliders_ct_widget.setHidden(True)
        self.sliders_mip_widget.setHidden(False)

    def simple_slider_value_changed(self):
        """
        Callback for slider of simple visualization type
        """
        slider_value = float(self.sliders_simple_widget.value()) \
            / float(self.sliders_simple_widget.maximum())
        self.render_widget.lowerBound = self.render_widget.minimum \
            + (self.render_widget.maximum - self.render_widget.minimum) * slider_value
        self.render_widget.update()

    def mip_slider_value_changed(self):
        """
        Callback for sliders of MIP visualization
        """
        min_value = float(self.min_slider.value()) / float(
            self.min_slider.maximum())
        max_value = float(self.max_slider.value()) / float(
            self.max_slider.maximum())

        self.render_widget.mipMin = self.render_widget.minimum \
            + (self.render_widget.maximum - self.render_widget.minimum) * min_value
        self.render_widget.mipMax = self.render_widget.minimum \
            + (self.render_widget.maximum - self.render_widget.minimum) * max_value

        self.render_widget.update()

    def ct_slider_value_changed(self):
        """
        Callback for sliders of CT visualization
        """
        for (x, slider) in enumerate(self.sliders):
            # for x in range(0, len(self.sliders)):
            # slider = self.sliders[x]
            slider_value = float(slider.value()) / float(slider.maximum())
            # Use an square function for easier opacity adjustments
            converted_value = slider_value * slider_value * slider_value
            self.render_widget.sectionsOpacity[x] = converted_value

        self.render_widget.update()

    def load_file(self):
        """
        Loads a file from disk
        """
        extensions = DataReader().get_supported_extensions_as_string()
        file_name, _ = QFileDialog.getOpenFileName(
            self, "Open data set", "", "Images (" + extensions + ")")
        if not file_name:
            return

        self.render_widget.load_file(file_name)
        self.switch_to_simple()