class TableWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.model = CustomTableModel()

        self.table_view = QTableView()
        self.table_view.setModel(self.model)
        self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table_view.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.chart = QtCharts.QChart()
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)

        self.series = QtCharts.QLineSeries()
        self.series.setName("Line 1")
        self.mapper = QtCharts.QVXYModelMapper(self)
        self.mapper.setXColumn(0)
        self.mapper.setYColumn(1)
        self.mapper.setSeries(self.series)
        self.mapper.setModel(self.model)
        self.chart.addSeries(self.series)

        # for storing color hex from the series
        seriesColorHex = "#000000"

        # get the color of the series and use it for showing the mapped area
        seriesColorHex = "{}".format(self.series.pen().color().name())
        self.model.add_mapping(seriesColorHex, QRect(0, 0, 2, self.model.rowCount()))

        # series 2
        self.series = QtCharts.QLineSeries()
        self.series.setName("Line 2")

        self.mapper = QtCharts.QVXYModelMapper(self)
        self.mapper.setXColumn(2)
        self.mapper.setYColumn(3)
        self.mapper.setSeries(self.series)
        self.mapper.setModel(self.model)
        self.chart.addSeries(self.series)

        # get the color of the series and use it for showing the mapped area
        seriesColorHex = "{}".format(self.series.pen().color().name())
        self.model.add_mapping(seriesColorHex, QRect(2, 0, 2, self.model.rowCount()));

        self.chart.createDefaultAxes()
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setMinimumSize(640, 480)

        # create main layout
        self.main_layout = QGridLayout()
        self.main_layout.addWidget(self.table_view, 1, 0)
        self.main_layout.addWidget(self.chart_view, 1, 1)
        self.main_layout.setColumnStretch(1, 1)
        self.main_layout.setColumnStretch(0, 0)
        self.setLayout(self.main_layout)
Beispiel #2
0
    def initUI(self):
        self.setWindowTitle(self.tr("Minesweeper"))
        layout = QGridLayout()
        layout.setSpacing(5)
        self.setLayout(layout)

        for tile in self.mineSweeper:
            qTile = QMineSweeper.QTile(self, tile)
            layout.addWidget(qTile, tile.row, tile.column)
            qTile.clicked.connect(qTile.leftClick)
            qTile.customContextMenuRequested.connect(qTile.rightClick)
            tile.delegate = qTile
    def __init__(self):
        QWidget.__init__(self)
        self.setMinimumSize(800, 600)
        self.donuts = []
        self.chart_view = QtCharts.QChartView()
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart = self.chart_view.chart()
        self.chart.legend().setVisible(False)
        self.chart.setTitle("Nested donuts demo")
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)

        self.min_size = 0.1
        self.max_size = 0.9
        self.donut_count = 5

        self.setup_donuts()

        # create main layout
        self.main_layout = QGridLayout(self)
        self.main_layout.addWidget(self.chart_view, 1, 1)
        self.setLayout(self.main_layout)

        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.update_rotation)
        self.update_timer.start(1250)
Beispiel #4
0
    def initUI(self):
        self.setWindowTitle(self.tr("Tic-Tac-Toe"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        gridLayout = QGridLayout()
        gridLayout.setSpacing(3)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(self.selectAI)
        layout.addWidget(aiComboBox)
        layout.addLayout(gridLayout)

        for tile in self.ticTacToe:
            button = QTicTacToe.QTileButton(self, tile)
            gridLayout.addWidget(button, tile.row, tile.column)
            button.clicked.connect(button.clickEvent)
            tile.delegate = button
Beispiel #5
0
    def initUI(self):
        self.setWindowTitle(self.tr("Fourplay"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        discGridLayout = QGridLayout()
        discGridLayout.setSpacing(4)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(lambda: self.selectAI())
        layout.addWidget(aiComboBox)
        layout.addLayout(discGridLayout)

        for disc in self.fourPlay:
            qDisc = QFourPlay.QDiscButton(self)
            discGridLayout.addWidget(qDisc, disc.row, disc.column)
            qDisc.clicked.connect(lambda qDisc=qDisc, disc=disc: qDisc.clickEvent(disc))
            qDisc.marked(disc)
            disc.delegate = qDisc
    def createOptionsGroupBox(self):
        self.optionsGroupBox = QGroupBox("Options")

        buttonsOrientationLabel = QLabel("Orientation of buttons:")

        buttonsOrientationComboBox = QComboBox()
        buttonsOrientationComboBox.addItem("Horizontal", Qt.Horizontal)
        buttonsOrientationComboBox.addItem("Vertical", Qt.Vertical)
        buttonsOrientationComboBox.currentIndexChanged[int].connect(self.buttonsOrientationChanged)

        self.buttonsOrientationComboBox = buttonsOrientationComboBox

        optionsLayout = QGridLayout()
        optionsLayout.addWidget(buttonsOrientationLabel, 0, 0)
        optionsLayout.addWidget(self.buttonsOrientationComboBox, 0, 1)
        optionsLayout.setColumnStretch(2, 1)
        self.optionsGroupBox.setLayout(optionsLayout)
    def __init__(self):
        super(Dialog, self).__init__()

        self.rotableWidgets = []

        self.createRotableGroupBox()
        self.createOptionsGroupBox()
        self.createButtonBox()

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.rotableGroupBox, 0, 0)
        mainLayout.addWidget(self.optionsGroupBox, 1, 0)
        mainLayout.addWidget(self.buttonBox, 2, 0)
        mainLayout.setSizeConstraint(QLayout.SetMinimumSize)

        self.mainLayout = mainLayout
        self.setLayout(self.mainLayout)

        self.setWindowTitle("Dynamic Layouts")
    def testInternalRef(self):
        mw = QWidget()
        w = QWidget()
        ow = QWidget()

        topLayout = QGridLayout()

        # unique reference
        self.assertEqual(getrefcount(w), 2)
        self.assertEqual(getrefcount(ow), 2)

        topLayout.addWidget(w, 0, 0)
        topLayout.addWidget(ow, 1, 0)

        # layout keep the referemce
        self.assertEqual(getrefcount(w), 3)
        self.assertEqual(getrefcount(ow), 3)

        mainLayout = QGridLayout()

        mainLayout.addLayout(topLayout, 1, 0, 1, 4)

        # the same reference
        self.assertEqual(getrefcount(w), 3)
        self.assertEqual(getrefcount(ow), 3)

        mw.setLayout(mainLayout)

        # now trasfer the ownership to mw
        self.assertEqual(getrefcount(w), 3)
        self.assertEqual(getrefcount(ow), 3)

        del mw

        # remove the ref and invalidate the widget
        self.assertEqual(getrefcount(w), 2)
        self.assertEqual(getrefcount(ow), 2)
Beispiel #9
0
class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('Commander V 0.1')
        self.resize(1600, 1200)

        #Functions
        self.commands = {

            # GUI commands
            'CLEARALL': self.clear_all_results,
            # Basic Text Commands
            'transform': TextFunctions().transform,
            '-tf': TextFunctions().transform,
            # Translation Commands
            'translate': TextFunctions().translate,
            '-tr': TextFunctions().translate,
            # Information Commands
            'extract': ExtractFunctions().extract,
            '-ext': ExtractFunctions().extract,
            'regex': ExtractFunctions().regex,
            '-re': ExtractFunctions().regex,
            # Image Functions
            'grayscale': ImageFunctions().grayscale,
            'bw': ImageFunctions().bw,
            'flip': ImageFunctions().flip,
            'invert': ImageFunctions().invert
        }

        # Fonts
        self.text_font = QFont('monospace', 16)
        self.button_font = QFont('monospace', 18)
        self.console_font = QFont('monospace', 14)

        # Create widgets

        self.input_area = QTabWidget()
        self.input_area.setFont(self.text_font)

        self.text_area = QTextEdit()
        self.text_area.setFont(self.text_font)

        self.file_area = FileArea()

        self.image_area = ImageArea()

        self.result_scroll_area = QScrollArea()

        self.result_area = QWidget()
        self.result_area.layout = QVBoxLayout()
        self.result_area.setLayout(self.result_area.layout)

        self.result_scroll_area.setWidget(self.result_area)
        self.result_scroll_area.setWidgetResizable(True)

        self.console = QTextEdit()
        self.console.setMaximumHeight(300)
        self.console.setReadOnly(True)
        self.console.setStyleSheet(
            'background-color: #0F0E0D; color: white; border: 0;')
        self.console.setFont(self.console_font)

        def set_command_line_focus(event):
            self.command_line.setFocus()

        self.console.mousePressEvent = set_command_line_focus

        self.command_line = QLineEdit()
        # self.command_line.setStyleSheet('background-color: #0F0E0D; color: white; border: 0;')
        self.command_line.setFont(self.console_font)
        self.command_line.setPlaceholderText('Enter command')
        self.command_line.setTextMargins(5, 0, 0, 0)

        self.execute_button = QPushButton("Execute")
        self.execute_button.setFont(self.button_font)
        self.execute_button.setStyleSheet(
            'background-color: red; color: white;')
        self.command_line.returnPressed.connect(self.execute_button.click)
        self.execute_button.setVisible(False)

        # Create layout and add widgets
        self.layout = QGridLayout()

        self.top_layout = QGridLayout()

        # Tabbed input area
        self.top_layout.addWidget(self.input_area, 0, 0)
        self.input_area.insertTab(0, self.text_area, 'Text')
        self.input_area.insertTab(1, self.file_area, 'File')
        self.input_area.insertTab(2, self.image_area, 'Image')

        self.top_layout.addWidget(self.result_scroll_area, 0, 2)

        self.bottom_layout = QGridLayout()
        self.bottom_layout.setSpacing(0)

        self.bottom_layout.addWidget(self.console, 0, 0)
        self.bottom_layout.addWidget(self.command_line, 1, 0)
        self.bottom_layout.addWidget(self.execute_button, 2, 0)

        # Set layout
        self.setLayout(self.layout)
        self.layout.addLayout(self.top_layout, 0, 0)
        self.layout.addLayout(self.bottom_layout, 1, 0)

        # Add button signal to execution function
        self.execute_button.clicked.connect(self.execute_command)

        # Set focus to command line
        self.command_line.setFocus()

    def clear_all_results(self, *args, **kwargs):
        for i in reversed(range(self.result_area.layout.count())):
            self.result_area.layout.itemAt(i).widget().setParent(None)

    # Executes command
    def execute_command(self):

        command = self.command_line.text().split(' ')
        command_action = command[0]

        if len(command) == 1:
            command_arguments = []
        else:
            command_arguments = ' '.join(command[1:])

        if self.input_area.currentIndex() == 0:
            data_input = self.text_area
        elif self.input_area.currentIndex() == 1:
            data_input = self.file_area.file_preview
        elif self.input_area.currentIndex() == 2:
            data_input = self.image_area.selected_file_name.text()

        # Data Types:
        if self.input_area.currentIndex() == 0 or self.input_area.currentIndex(
        ) == 1:
            plain_data = data_input.toPlainText()
            html_data = data_input.toHtml()
            markdown_data = data_input.toMarkdown()

            data = {
                'plain': plain_data,
                'html': html_data,
                'markdown': markdown_data
            }

        elif self.input_area.currentIndex() == 2:
            image_data = data_input

            data = {'image': image_data}

        if command_action in self.commands:

            function = self.commands[command_action]
            result = function(data, command_arguments)

            # Check to see if function returns a result, then sets variables
            if result:
                result_output = result['output']
                result_data_type = result['type']
                result_console_message = result['console_message']

            command_print = QLineEdit(self.command_line.text())
            command_print.setFont(self.console_font)
            command_print.setReadOnly(True)

            # Clears command line
            self.command_line.clear()

            # Inserts the command and the result as widgets
            if result_output:
                self.result_area.layout.addWidget(command_print)
                result_block = ResultBlock(result_output, result_data_type)
                self.result_area.layout.addWidget(result_block)

            # Make sure scrollbar is always at the bottom
            scroll_bar = self.result_scroll_area.verticalScrollBar()
            scroll_bar.rangeChanged.connect(
                lambda x, y: scroll_bar.setValue(y))

            # Inserts console_message to console
            if result_console_message:
                self.console.append(result['console_message'])
Beispiel #10
0
 def init_ui(self):
     layout = QGridLayout()
     layout.addWidget(QArmorRecruitmentMenu(self.cp, self.game), 0, 0)
     layout.addWidget(QGroundForcesStrategy(self.cp, self.game), 0, 1)
     self.setLayout(layout)
Beispiel #11
0
    def __init__(self, image, parent=None):
        super(AdjustWidget, self).__init__(parent)

        self.bright_slider = ParamSlider([-255, +255], 16, 0)
        self.sat_slider = ParamSlider([-255, +255], 16, 0)
        self.hue_slider = ParamSlider([0, 180], 10, 0, '°')
        self.gamma_slider = ParamSlider([1, 50], 10, 10)
        self.shadow_slider = ParamSlider([-100, +100], 10, 0, '%')
        self.high_slider = ParamSlider([-100, +100], 10, 0, '%')
        self.sweep_slider = ParamSlider([0, 255], 8, 127)
        self.width_slider = ParamSlider([0, 255], 8, 255)
        self.sharpen_slider = ParamSlider([0, 100], 10, 0, '%')
        self.thr_slider = ParamSlider([0, 255],
                                      16,
                                      255,
                                      special=self.tr('Auto'))
        self.equalize_combo = QComboBox()
        self.equalize_combo.addItems([
            self.tr('No EQ'),
            self.tr('Hist EQ'),
            self.tr('CLAHE L1'),
            self.tr('CLAHE L2'),
            self.tr('CLAHE L3'),
            self.tr('CLAHE L4')
        ])
        self.equalize_combo.setToolTip(self.tr('Histogram equalization mode'))
        self.invert_check = QCheckBox(self.tr('Invert values'))
        self.invert_check.setToolTip(self.tr('Apply bitwise complement'))
        self.reset_button = QPushButton(self.tr('Reset'))

        self.image = image
        self.viewer = ImageViewer(self.image, self.image)
        self.reset()

        self.bright_slider.valueChanged.connect(self.process)
        self.sat_slider.valueChanged.connect(self.process)
        self.hue_slider.valueChanged.connect(self.process)
        self.gamma_slider.valueChanged.connect(self.process)
        self.shadow_slider.valueChanged.connect(self.process)
        self.high_slider.valueChanged.connect(self.process)
        self.sweep_slider.valueChanged.connect(self.process)
        self.width_slider.valueChanged.connect(self.process)
        self.thr_slider.valueChanged.connect(self.process)
        self.sharpen_slider.valueChanged.connect(self.process)
        self.equalize_combo.currentIndexChanged.connect(self.process)
        self.invert_check.stateChanged.connect(self.process)
        self.reset_button.clicked.connect(self.reset)

        params_layout = QGridLayout()
        params_layout.addWidget(QLabel(self.tr('Brightness')), 0, 0)
        params_layout.addWidget(QLabel(self.tr('Saturation')), 1, 0)
        params_layout.addWidget(QLabel(self.tr('Hue')), 2, 0)
        params_layout.addWidget(QLabel(self.tr('Gamma')), 3, 0)
        params_layout.addWidget(self.bright_slider, 0, 1)
        params_layout.addWidget(self.sat_slider, 1, 1)
        params_layout.addWidget(self.hue_slider, 2, 1)
        params_layout.addWidget(self.gamma_slider, 3, 1)
        params_layout.addWidget(QLabel(self.tr('Shadows')), 0, 2)
        params_layout.addWidget(QLabel(self.tr('Highlights')), 1, 2)
        params_layout.addWidget(QLabel(self.tr('Sweep')), 2, 2)
        params_layout.addWidget(QLabel(self.tr('Width')), 3, 2)
        params_layout.addWidget(self.shadow_slider, 0, 3)
        params_layout.addWidget(self.high_slider, 1, 3)
        params_layout.addWidget(self.sweep_slider, 2, 3)
        params_layout.addWidget(self.width_slider, 3, 3)
        params_layout.addWidget(QLabel(self.tr('Sharpen')), 0, 4)
        params_layout.addWidget(self.sharpen_slider, 0, 5)
        params_layout.addWidget(QLabel(self.tr('Threshold')), 1, 4)
        params_layout.addWidget(self.thr_slider, 1, 5)
        params_layout.addWidget(self.equalize_combo, 2, 4)
        params_layout.addWidget(self.invert_check, 2, 5)
        params_layout.addWidget(self.reset_button, 3, 4, 1, 2)

        main_layout = QVBoxLayout()
        main_layout.addLayout(params_layout)
        main_layout.addWidget(self.viewer)
        self.setLayout(main_layout)
Beispiel #12
0
    def __init__(self, settings):
        QWidget.__init__(self)
        self.settings = settings

        self.setWindowTitle('PARAMETERS')
        self.setFixedSize(360, 500)

        self.main_layout = QGridLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.setLayout(self.main_layout)

        calculous_parameters_label = QLabel('CALCULOUS PARAMETERS')
        calculous_parameters_label.setAlignment(Qt.AlignCenter)
        calculous_parameters_label.setFixedHeight(58)
        calculous_parameters_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(calculous_parameters_label, 0, 0, 1, 2)

        object_mass_label = QLabel('Object mass (kg)')
        object_mass_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        object_mass_label.setFixedHeight(32)
        self.main_layout.addWidget(object_mass_label, 1, 0, 1, 1)

        self.object_mass_input = QLineEdit()
        self.object_mass_input.setAlignment(Qt.AlignRight)
        self.object_mass_input.setText(str(self.settings.object_mass))
        self.object_mass_input.textChanged.connect(self.updateObjectMass)
        self.main_layout.addWidget(self.object_mass_input, 1, 1, 1, 1)

        dichotomy_precision_label = QLabel('Dichotomy precision')
        dichotomy_precision_label.setFixedHeight(32)
        dichotomy_precision_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(dichotomy_precision_label, 2, 0, 1, 1)

        self.dichotomy_precision_input = QLineEdit()
        self.dichotomy_precision_input.setAlignment(Qt.AlignRight)
        self.dichotomy_precision_input.setText(
            str(self.settings.dichotomy_precision))
        self.dichotomy_precision_input.textChanged.connect(
            self.updateDichotomyPrecision)
        self.main_layout.addWidget(self.dichotomy_precision_input, 2, 1, 1, 1)

        fluid_density_label = QLabel('Fluid density (kg/m3)')
        fluid_density_label.setFixedHeight(32)
        fluid_density_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(fluid_density_label, 3, 0, 1, 1)

        self.fluid_density_options = QComboBox()
        if self.settings.fluid_density == SALTWATER_DENSITY:
            self.fluid_density_options.addItem('saltwater (' +
                                               str(SALTWATER_DENSITY) +
                                               ' kg/m3)')
            self.fluid_density_options.addItem('freshwater (' +
                                               str(FRESHWATER_DENSITY) +
                                               ' kg/m3)')
        else:
            self.fluid_density_options.addItem('freshwater (' +
                                               str(FRESHWATER_DENSITY) +
                                               ' kg/m3)')
            self.fluid_density_options.addItem('saltwater (' +
                                               str(SALTWATER_DENSITY) +
                                               ' kg/m3)')
        self.fluid_density_options.addItem('Other')
        self.fluid_density_options.activated.connect(
            self.updateFluidDensityWithOption)
        self.main_layout.addWidget(self.fluid_density_options, 3, 1, 1, 1)

        self.fluid_density_input = QLineEdit()
        self.fluid_density_input.setAlignment(Qt.AlignRight)
        self.fluid_density_input.textChanged.connect(
            self.updateFluidDensityWithInput)
        if self.settings.fluid_density in [
                FRESHWATER_DENSITY, SALTWATER_DENSITY
        ]:
            self.fluid_density_input.hide()
        else:
            self.fluid_density_input.setText(str(self.settings.fluid_density))
        self.main_layout.addWidget(self.fluid_density_input, 4, 1, 1, 1)

        display_parameters_label = QLabel('DISPLAY PARAMETERS')
        display_parameters_label.setAlignment(Qt.AlignCenter)
        display_parameters_label.setFixedHeight(58)
        display_parameters_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(display_parameters_label, 5, 0, 1, 2)

        show_draught_label = QLabel('Show draught')
        show_draught_label.setFixedHeight(32)
        show_draught_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(show_draught_label, 6, 0, 1, 1)
        self.show_draught_checkbox = QCheckBox()
        self.show_draught_checkbox.stateChanged.connect(self.updateShowDraught)
        self.show_draught_checkbox.setCheckState(
            Qt.CheckState.Checked if self.settings.show_draught else Qt.
            CheckState.Unchecked)
        self.main_layout.addWidget(self.show_draught_checkbox, 6, 1, 1, 1)

        self.show()
Beispiel #13
0
class CommandWidget(TabWidgetExtension, QWidget):
    """Output for running queue"""

    # log state
    __log = False
    insertTextSignal = Signal(str, dict)
    updateCommandSignal = Signal(str)
    cliButtonsSateSignal = Signal(bool)
    cliValidateSignal = Signal(bool)
    resetSignal = Signal()

    def __init__(self, parent=None, proxyModel=None, controlQueue=None, log=None):
        super(CommandWidget, self).__init__(parent=parent, tabWidgetChild=self)

        self.__log = log
        self.__output = None
        self.__rename = None
        self.__tab = None

        # self.oCommand = MKVCommand()
        self.algorithm = None
        self.oCommand = MKVCommandParser()
        self.controlQueue = controlQueue
        self.parent = parent
        self.proxyModel = proxyModel
        self.model = proxyModel.sourceModel()
        self.outputWindow = QOutputTextWidget(self)
        self.log = log

        self._initControls()
        self._initUI()
        self._initHelper()

    def _initControls(self):
        #
        # command line
        #
        self.frmCmdLine = QFormLayout()
        btnPasteClipboard = QPushButtonWidget(
            Text.txt0164,
            function=lambda: qtRunFunctionInThread(self.pasteClipboard),
            margins="  ",
            toolTip=Text.txt0165,
        )
        self.cmdLine = QLineEdit()
        self.cmdLine.setValidator(
            ValidateCommand(self, self.cliValidateSignal, log=self.log)
        )
        self.frmCmdLine.addRow(btnPasteClipboard, self.cmdLine)
        self.frmCmdLine.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        self.command = QWidget()
        self.command.setLayout(self.frmCmdLine)

        #
        # Button group definition
        #
        self.btnGroup = QGroupBox()
        self.btnGrid = QGridLayout()

        btnAddCommand = QPushButtonWidget(
            Text.txt0160,
            function=lambda: self.addCommand(JobStatus.Waiting),
            margins="  ",
            toolTip=Text.txt0161,
        )
        btnRename = QPushButtonWidget(
            Text.txt0182,
            function=self.parent.renameWidget.setAsCurrentTab,
            margins="  ",
            toolTip=Text.txt0183,
        )
        btnAddQueue = QPushButtonWidget(
            Text.txt0166,
            function=lambda: self.addCommand(JobStatus.AddToQueue),
            margins="  ",
            toolTip=Text.txt0167,
        )
        btnStartQueue = QPushButtonWidget(
            Text.txt0126,
            function=self.parent.jobsQueue.run,
            margins="  ",
            toolTip=Text.txt0169,
        )
        btnAnalysis = QPushButtonWidget(
            Text.txt0170,
            function=lambda: qtRunFunctionInThread(
                runAnalysis,
                command=self.cmdLine.text(),
                output=self.output,
                log=self.log,
            ),
            margins="  ",
            toolTip=Text.txt0171,
        )
        btnShowCommands = QPushButtonWidget(
            Text.txt0172,
            function=lambda: qtRunFunctionInThread(
                showCommands,
                output=self.output,
                command=self.cmdLine.text(),
                oCommand=self.oCommand,
                log=self.log,
            ),
            margins="  ",
            toolTip=Text.txt0173,
        )
        btnCheckFiles = QPushButtonWidget(
            Text.txt0174,
            function=lambda: qtRunFunctionInThread(
                checkFiles,
                output=self.output,
                command=self.cmdLine.text(),
                oCommand=self.oCommand,
                log=self.log,
            ),
            margins="  ",
            toolTip=Text.txt0175,
        )
        btnClear = QPushButtonWidget(
            Text.txt0176,
            function=self.clearOutputWindow,
            margins="  ",
            toolTip=Text.txt0177,
        )
        btnReset = QPushButtonWidget(
            Text.txt0178,
            function=self.reset,
            margins="  ",
            toolTip=Text.txt0179,
        )

        self.btnGrid.addWidget(btnAddCommand, 0, 0)
        self.btnGrid.addWidget(btnRename, 0, 1)
        self.btnGrid.addWidget(btnAddQueue, 1, 0)
        self.btnGrid.addWidget(btnStartQueue, 1, 1)
        self.btnGrid.addWidget(HorizontalLine(), 2, 0, 1, 2)
        self.btnGrid.addWidget(btnAnalysis, 3, 0)
        self.btnGrid.addWidget(btnShowCommands, 3, 1)
        self.btnGrid.addWidget(btnCheckFiles, 4, 0)
        self.btnGrid.addWidget(HorizontalLine(), 5, 0, 1, 2)
        self.btnGrid.addWidget(btnClear, 6, 0)
        self.btnGrid.addWidget(btnReset, 6, 1)
        self.btnGroup.setLayout(self.btnGrid)

        self.btnGroupBox = QGroupBox()
        self.btnHBox = QHBoxLayout()

        self.lblAlgorithm = QLabelWidget(
            Text.txt0094,
            textSuffix=":  ",
        )
        self.rbZero = QRadioButton("0", self)
        self.rbOne = QRadioButton("1", self)
        self.rbTwo = QRadioButton("2", self)

        btnDefaultAlgorithm = QPushButtonWidget(
            Text.txt0092,
            function=self.setDefaultAlgorithm,
            margins="  ",
            toolTip=Text.txt0093,
        )

        self.radioButtons = [self.rbZero, self.rbOne, self.rbTwo]

        self.btnHBox.addWidget(self.lblAlgorithm)
        self.btnHBox.addWidget(self.rbZero)
        self.btnHBox.addWidget(self.rbOne)
        self.btnHBox.addWidget(self.rbTwo)
        self.btnHBox.addWidget(btnDefaultAlgorithm)
        self.btnGroupBox.setLayout(self.btnHBox)

    def _initUI(self):

        grid = QGridLayout()
        grid.addWidget(self.command, 0, 0, 1, 2)
        grid.addWidget(self.btnGroupBox, 1, 0)
        grid.addWidget(self.btnGroup, 2, 0)
        grid.addWidget(self.outputWindow, 2, 1, 10, 1)

        self.setLayout(grid)

    def _initHelper(self):
        #
        # Signal interconnections
        #

        # local button state connect to related state
        self.parent.jobsQueue.addQueueItemSignal.connect(
            lambda: self.jobStartQueueState(True)
        )
        self.parent.jobsQueue.queueEmptiedSignal.connect(
            lambda: self.jobStartQueueState(False)
        )

        # job related
        self.parent.jobsQueue.runJobs.startSignal.connect(lambda: self.jobStatus(True))
        self.parent.jobsQueue.runJobs.finishedSignal.connect(
            lambda: self.jobStatus(False)
        )

        # map insertText signal to outputWidget one
        self.insertText = self.outputWindow.insertTextSignal

        # command
        self.updateCommandSignal.connect(self.updateCommand)
        self.cliButtonsSateSignal.connect(self.cliButtonsState)
        self.cliValidateSignal.connect(self.cliValidate)

        #
        # button state
        #

        # Command related
        # self.frmCmdLine.itemAt(0, QFormLayout.LabelRole).widget().setEnabled(False)
        self.cliButtonsState(False)
        self.btnGrid.itemAt(_Button.ANALYSIS).widget().setEnabled(False)

        # Clear buttons related
        self.btnGrid.itemAt(_Button.CLEAR).widget().setEnabled(False)
        self.btnGrid.itemAt(_Button.RESET).widget().setEnabled(False)

        # connect text windows textChanged to clearButtonState function
        self.outputWindow.textChanged.connect(self.clearButtonState)

        # connect command line textChanged to analysisButtonState function
        self.cmdLine.textChanged.connect(self.analysisButtonState)

        # Job Queue related
        self.btnGrid.itemAt(_Button.STARTQUEUE).widget().setEnabled(False)

        # Job Added to Queue
        self.parent.jobsQueue.addQueueItemSignal.connect(self.printJobIDAdded)

        #
        # Misc
        #
        self.cmdLine.setClearButtonEnabled(True)  # button at end of line to clear it

        # Algorithm radio buttons
        self.rbZero.toggled.connect(lambda: self.toggledRadioButton(self.rbZero))
        self.rbOne.toggled.connect(lambda: self.toggledRadioButton(self.rbOne))
        self.rbTwo.toggled.connect(lambda: self.toggledRadioButton(self.rbTwo))

        self.setDefaultAlgorithm()

    @classmethod
    def classLog(cls, setLogging=None):
        """
        get/set logging at class level
        every class instance will log
        unless overwritten

        Args:
            setLogging (bool):
                - True class will log
                - False turn off logging
                - None returns current Value

        Returns:
            bool:

            returns the current value set
        """

        if setLogging is not None:
            if isinstance(setLogging, bool):
                cls.__log = setLogging

        return cls.__log

    @property
    def log(self):
        """
        class property can be used to override the class global
        logging setting

        Returns:
            bool:

            True if logging is enable False otherwise
        """
        if self.__log is not None:
            return self.__log

        return CommandWidget.classLog()

    @log.setter
    def log(self, value):
        """set instance log variable"""

        if isinstance(value, bool) or value is None:
            self.__log = value
            # No variable used so for now use class log
            ValidateCommand.classLog(value)
            self.outputWindow.log = value

    @property
    def output(self):
        return self.__output

    @output.setter
    def output(self, value):
        self.__output = value

    @property
    def rename(self):
        return self.__rename

    @rename.setter
    def rename(self, value):
        if isinstance(value, object):
            self.__rename = value

    @Slot(list)
    def applyRename(self, renameFiles):

        if self.oCommand:
            self.oCommand.renameOutputFiles(renameFiles)

    @Slot(bool)
    def cliButtonsState(self, validateOK):
        """
        cliButtonsState change enabled status for buttons related with command line

        Args:
            validateOK (bool): True to enable, False to disable
        """

        for b in [
            _Button.ADDCOMMAND,
            _Button.RENAME,
            _Button.ADDQUEUE,
            _Button.SHOWCOMMANDS,
            _Button.CHECKFILES,
        ]:
            button = self.btnGrid.itemAt(b).widget()
            button.setEnabled(validateOK)

    @Slot(bool)
    def cliValidate(self, validateOK):
        """
        cliValidate Slot used by ValidateCommnad

        Args:
            validateOK (bool): True if command line is Ok.  False otherwise.
        """

        if validateOK:
            self.output.command.emit(
                "Command looks ok.\n", {LineOutput.AppendEnd: True}
            )
        else:
            if self.cmdLine.text() != "":
                self.output.command.emit("Bad command.\n", {LineOutput.AppendEnd: True})

        self.cliButtonsState(validateOK)
        self.updateObjCommnad(validateOK)

    @Slot(bool)
    def jobStartQueueState(self, state):

        if state and not isThreadRunning(config.WORKERTHREADNAME):
            self.btnGrid.itemAt(_Button.STARTQUEUE).widget().setEnabled(True)
        else:
            self.btnGrid.itemAt(_Button.STARTQUEUE).widget().setEnabled(False)

    @Slot(bool)
    def updateObjCommnad(self, valid):
        """Update the command object"""

        if valid:
            self.oCommand.command = self.cmdLine.text()
            if self.rename is not None:
                self.rename.setFilesSignal.emit(self.oCommand)
                self.rename.applyFileRenameSignal.connect(self.applyRename)
        else:
            self.oCommand.command = ""
            if self.rename is not None:
                self.rename.clear()

    @Slot(str)
    def updateCommand(self, command):
        """Update command input widget"""

        self.cmdLine.clear()
        self.cmdLine.setText(command)
        self.cmdLine.setCursorPosition(0)

    @Slot(int)
    def updateAlgorithm(self, algorithm):

        if 0 <= algorithm < len(self.radioButtons):
            self.radioButtons[algorithm].setChecked(True)

    @Slot(bool)
    def jobStatus(self, running):
        """
        jobStatus receive Signals for job start/end

        Args:
            running (bool): True if job started. False if ended.
        """

        if running:
            self.jobStartQueueState(False)
            palette = QPalette()
            color = checkColor(
                QColor(42, 130, 218), config.data.get(config.ConfigKey.DarkMode)
            )
            palette.setColor(QPalette.WindowText, color)
            self.parent.jobsLabel.setPalette(palette)
        else:
            palette = QPalette()
            color = checkColor(None, config.data.get(config.ConfigKey.DarkMode))
            palette.setColor(QPalette.WindowText, color)
            self.parent.jobsLabel.setPalette(palette)

    def addCommand(self, status):
        """
        addCommand add command row in jobs table

        Args:
            status (JobStatus): Status for job to be added should be either
                                JobStatus.Waiting or JobStatus.AddToQueue
        """

        totalJobs = self.model.rowCount()
        command = self.cmdLine.text()
        # [cell value, tooltip, obj]
        data = [
            ["", "", self.algorithm],
            [status, "Status code", None],
            [command, command, self.oCommand],
        ]
        self.model.insertRows(totalJobs, 1, data=data)
        self.cmdLine.clear()

    def analysisButtonState(self):
        """Set clear button state"""

        if self.cmdLine.text() != "":
            self.btnGrid.itemAt(_Button.ANALYSIS).widget().setEnabled(True)
        else:
            self.btnGrid.itemAt(_Button.ANALYSIS).widget().setEnabled(False)

    def clearButtonState(self):
        """Set clear button state"""

        if self.outputWindow.toPlainText() != "":
            self.btnGrid.itemAt(_Button.CLEAR).widget().setEnabled(True)
        else:
            self.btnGrid.itemAt(_Button.CLEAR).widget().setEnabled(False)

    def clearOutputWindow(self):
        """
        clearOutputWindow clear the command output window
        """

        language = config.data.get(config.ConfigKey.Language)
        bAnswer = False

        # Clear output window?
        title = "Clear output"
        msg = "¿" if language == "es" else ""
        msg += "Clear output window" + "?"
        bAnswer = yesNoDialog(self, msg, title)

        if bAnswer:
            self.outputWindow.clear()

    def printJobIDAdded(self, index):

        jobID = self.model.dataset[index.row(), index.column()]

        self.output.command.emit(
            f"Job: {jobID} added to Queue...\n", {LineOutput.AppendEnd: True}
        )

    def pasteClipboard(self):
        """Paste clipboard to command QLineEdit"""

        clip = QApplication.clipboard().text()

        if clip:
            self.output.command.emit(
                "Checking command...\n", {LineOutput.AppendEnd: True}
            )
            self.update()
            self.updateCommandSignal.emit(clip)

    def reset(self):
        """
        reset program status
        """

        language = config.data.get(config.ConfigKey.Language)

        if not isThreadRunning(config.WORKERTHREADNAME):

            language = config.data.get(config.ConfigKey.Language)
            bAnswer = False

            # Clear output window?
            title = "Reset"
            msg = "¿" if language == "es" else ""
            msg += "Reset Application" + "?"
            bAnswer = yesNoDialog(self, msg, title)

            if bAnswer:
                self.cmdLine.clear()
                self.outputWindow.clear()
                self.output.jobOutput.clear()
                self.output.errorOutput.clear()
                self.resetSignal.emit()

        else:
            messageBox(self, "Reset", "Jobs are running..")

    def resetButtonState(self):
        """Set clear button state"""

        if self.output.jobOutput.toPlainText() != "":
            self.btnGrid.itemAt(_Button.RESET).widget().setEnabled(True)
        else:
            self.btnGrid.itemAt(_Button.RESET).widget().setEnabled(False)

    def setDefaultAlgorithm(self):
        #
        # Algorithm
        #
        if config.data.get(config.ConfigKey.Algorithm) is not None:
            currentAlgorithm = config.data.get(config.ConfigKey.Algorithm)
            self.radioButtons[currentAlgorithm].setChecked(True)

    def setLanguage(self):
        """
        setLanguage language use in buttons/labels to be called by MainWindow
        """

        for index in range(self.frmCmdLine.rowCount()):
            widget = self.frmCmdLine.itemAt(index, QFormLayout.LabelRole).widget()
            if isinstance(widget, QPushButtonWidget):
                widget.setLanguage()
                # widget.setText("  " + _(widget.originalText) + "  ")
                # widget.setToolTip(_(widget.toolTip))

        for index in range(self.btnHBox.count()):
            widget = self.btnHBox.itemAt(index).widget()
            if isinstance(
                widget,
                (
                    QLabelWidget,
                    QPushButtonWidget,
                ),
            ):
                widget.setLanguage()

        for index in range(self.btnGrid.count()):
            widget = self.btnGrid.itemAt(index).widget()
            if isinstance(widget, QPushButtonWidget):
                widget.setLanguage()
                # widget.setText("  " + _(widget.originalText) + "  ")
                # widget.setToolTip(_(widget.toolTip))

    def toggledRadioButton(self, rButton):
        for index, rb in enumerate(self.radioButtons):
            if rb.isChecked():
                self.algorithm = index
    def _layoutscrapeTab(self) -> None:
        layout = QGridLayout(self)

        nameLabel = QLabel('Movie Name')
        nameLineEdit = QLineEdit()
        nameLineEdit.setPlaceholderText('Enter name of the movie')

        # Adding rows to the form layout
        layout.addWidget(nameLabel, 0, 0)
        layout.addWidget(nameLineEdit, 0, 1)

        nameLabel2 = QLabel('Movie Link')
        nameLineEdit2 = QLineEdit()
        nameLineEdit2.setPlaceholderText('Enter the link of the movie reviews')

        # Adding rows to the form layout
        layout.addWidget(nameLabel2, 1, 0)
        layout.addWidget(nameLineEdit2, 1, 1)

        # Create a button to that will take the name and pass it on to
        # another program to create dataset
        scrapeButton = QPushButton('Scrape Reviews')
        # Set a target method for `scrapeButton` when clicked
        scrapeButton.clicked.connect(
            partial(self._transferToScraping, scrapeButton, nameLineEdit,
                    nameLineEdit2))
        # Add `scrapeButton` to the layout
        layout.addWidget(scrapeButton, 2, 0, 2, 2)

        # Reset button to clear the name field
        resetButton = QPushButton('Reset')
        # Set a target to clear the field when clicked
        resetButton.clicked.connect(
            partial(self._clearField, resetButton, nameLineEdit,
                    nameLineEdit2))
        # Add `resetButton` to the layout
        layout.addWidget(resetButton, 4, 0, 2, 2)

        # Set this as the layout of the 'Training' tab
        self.scrapeTab.setLayout(layout)
Beispiel #15
0
class UI_Generator(QtWidgets.QDialog):
    """
    Initialize the required widget needed by DPC Explorer tab.

    Parameters
    ----------
    application_window : QApplication
        The parent in which the tab should be rendered
    fnct : function
        The function object for which we want to create the input box
            Parameters
    items_per_column : int, optional
        Number of widgets per colum, by default 10
    key_ignore : list, optional
        List of variable names to be removed from the GUI, by default None
    key_add : dict, optional
        Dict with variable name as a key and a list composed of type, default value and description,
        by default None

    """
    def __init__(self,
                 application_window,
                 fnct,
                 items_per_column=10,
                 key_ignore=None,
                 key_add=None):
        super(UI_Generator, self).__init__()
        self.application_window = application_window
        self.key_ignore = key_ignore
        self.key_add = key_add
        self.items_per_column = items_per_column
        self.default = {}
        # This must always be last and in that order
        if fnct is not None:
            self.fnct = fnct.__name__
            self.setWindowTitle("FPD-Explorer : " + self.fnct)
            self.config_val = config.get_dict(self.fnct)
            self.param = self._get_param(fnct)
        else:
            self.fnct = None
            self.setWindowTitle("FPD-Explorer : Parameters")
            self.config_val = {}
            self.param = self.handle_key_edits({})
        self._setup_ui()
        self.setWindowFlags((self.windowFlags()
                             | Qt.MSWindowsFixedSizeDialogHint)
                            & ~Qt.WindowContextHelpButtonHint)

    def _get_param(self, fnct) -> dict:
        """
        Get the paramaters based of a given function.

        Uses the docstring and parses it. Must respect numpy style docstring to parse correctly.
        Also uses the function signature to get default.

        Parameters
        ----------
        fnct : fnct
            The function you want to get the parameter of

        Returns
        ----------
        result : dict
            A dict with the variable name as a key and the default value and description as item
        """
        sig = signature(fnct)
        doc = fnct.__doc__
        result = {}
        if doc:
            # Result is a dict with the variable name as key and a list composed of type, default value, description
            param = doc.split('Parameters')[1].replace(',', '').replace(
                '-', '').split("Return")[0].split("Attributes")[0].split(
                    "Notes")[0].split('\n')
            current_name = ""
            global_space = -1
            for idx, el in enumerate(param):
                if not el.isspace() and el:
                    nb_space = len(el) - len(el.lstrip())
                    if global_space == -1 and el.find(':') != -1:
                        global_space = nb_space
                    if nb_space == global_space:
                        current_name, type = el.replace(' ', '').split(':')
                        default = sig.parameters[current_name]
                        if default is not None:
                            default = default.default
                            if default is inspect.Parameter.empty:
                                default = None
                        result[current_name] = [type, default]
                    else:
                        result[current_name].append(param[idx].strip())
                        if len(result[current_name]) > 2:
                            result[current_name][2] = " ".join(
                                result[current_name][2:])
                            del result[current_name][3:]
        return self.handle_key_edits(result)

    def handle_key_edits(self, result):
        if self.key_ignore is not None:
            [result.pop(x, None) for x in self.key_ignore]
        if self.key_add is not None:
            for key, el in self.key_add.items():
                # Remove all key already present in the dict so no key gets processed twice
                if result.get(key, None) is not None:
                    result.pop(key)
            result.update(self.key_add)
        return result

    def _setup_ui(self):
        """
        Creates the UI. Assumes the parameter list has already been defined.
        self.widgets is a dictionary with the type as key and a list of widgets as values

        the list of widgets is composed of a list compossed of key, widget, None value possible
        {
            type:[
                [key, widget, bool],
            ],
        }
        """
        self.result = {}
        self.widgets = defaultdict(list)
        self.toggle_widget = defaultdict(list)
        for key, val in self.param.items():
            widget = None
            param_type = None
            if "array" in val[0] or "QtWidget" in val[0]:
                # skip input that could be an array because it is too hard to find a way to handle them
                continue
            if "cmap" in val[0] or "colormap" in val[0].lower():
                param_type = "multipleinput"
                widget = QComboBox()
                for el in self.application_window.cmaps.values():
                    for cmaps in el:
                        widget.addItem(cmaps)

            elif "str" in val[0]:
                widget = QLineEdit()
                if val[1] is None:
                    widget.setPlaceholderText(self._set_default(widget, key))
                else:
                    widget.setText(self._set_default(widget, val[1]))
                tmp_val = self.config_val.get(key, None)
                if tmp_val is not None:
                    widget.setText(tmp_val)
                param_type = "str"
            elif "tuple" in val[0]:
                param_type, widget = self._handle_iterable(val, key)
            elif "scalar" in val[0] or "float" in val[0]:
                widget = self._create_int_float(val, is_float=True, key=key)
                param_type = "int"
            elif "int" in val[0]:
                widget = self._create_int_float(val, key=key)
                param_type = "int"
            elif "bool" in val[0]:
                default_val = val[1] if val[1] is not None else False
                widget = QCheckBox()
                widget.setChecked(self._set_default(widget, default_val))
                tmp_val = self.config_val.get(key, None)
                if tmp_val is not None:
                    widget.setChecked(tmp_val)
                param_type = "bool"
            elif "iterable" in val[0]:
                # Repetition needed because int should be prioritized over iterable and tuple over scalar
                param_type, widget = self._handle_iterable(val, key)
            elif "multipleinput" in val[0]:
                param_type = "multipleinput"
                widget = QComboBox()
                for idx, el in enumerate(val[1]):
                    widget.addItem(el[0])
                    widget.setItemData(idx, el[1])
                tmp_val = self.config_val.get(key, None)
                if tmp_val is not None:
                    # Float needed because otherwise Python throws a fit
                    widget.setCurrentIndex(int(float(tmp_val)))
                else:
                    widget.setCurrentIndex(0)
            elif "togglevalue" in val[0]:
                param_type = "togglevalue"
                widget = QCheckBox()
                widget.setChecked(False)
                widget.stateChanged.connect(self._handle_togglevalue)
                sub_param_type, new_widget = self._handle_iterable(val[1], key)
                self.toggle_widget[key].extend([sub_param_type, new_widget])
                if val[1][1] is None:
                    val[0] += "None"
            else:
                continue
            none_possible = False
            if "None" in val[0]:
                none_possible = True
            widget.setToolTip(val[2])
            self.widgets[param_type].append([key, widget, none_possible])
        self._format_layout()

    def _handle_iterable(self, val, key):
        iter_ran = int(''.join(x for x in val[0] if x.isdigit()))
        widget = QWidget()
        lay = QVBoxLayout()
        unpack = False
        if isinstance(val[1], tuple) or isinstance(val[1], list):
            # Expect to have as many values in the tuple as it is required by the iterable
            unpack = True
        for el in range(iter_ran):
            new_val = list(val)
            if unpack:
                new_val[1] = val[1][el]
            lay.addWidget(
                self._create_int_float(new_val,
                                       key=key + '_' + str(el),
                                       is_float=True))
        widget.setLayout(lay)
        param_type = "iterable_" + str(iter_ran)
        return param_type, widget

    def _create_int_float(self,
                          val,
                          is_float: bool = False,
                          key: str = None) -> QWidget:
        """
        Creates the widget for integer or float.

        Parameters
        ----------
        val : list
            list of type, default value, description
        is_float : bool, optional
            is the value suposed to be a float, by default False
        key : str, optional
            The variable name, by default None

        Returns
        -------
        QWidget
            The given widget correctly set up
        """
        default_val = val[1] if val[1] is not None else 0
        if is_float:
            widget = QDoubleSpinBox()
        else:
            widget = QSpinBox()
        widget.setMinimum(-1000)
        widget.setMaximum(1000)
        # Needed to return to default if it is ever needed
        widget.setMinimum(-1000)
        widget.setMaximum(1000)
        widget.setValue(self._set_default(widget, default_val))
        tmp_val = self.config_val.get(key, None)
        if isinstance(tmp_val, str):
            if 'None' not in tmp_val:
                widget.setValue(float(tmp_val))
        elif tmp_val is not None:
            widget.setValue(float(tmp_val))
        widget.setToolTip(val[2])
        return widget

    @Slot(int)
    def _handle_togglevalue(self, state: int):
        """
        Handles adding new items to the layout when a togle value is clicked.

        Parameters
        ----------
        state : int
            State of the button clicked
            2 is on
            0 is off
        """
        caller = self.sender()
        if state == 2:
            flatten_widget = []
            already_placed = 0
            correct_key = None
            for key, widget, none_possible in self.widgets["togglevalue"]:
                if widget == caller:
                    correct_key = key
                    out = self.toggle_widget[key]
                    # Handle unpacking with variable amount
                    param_type = out[0]
                    sub_widget = out[1]
                    self._layout_iterable(key, sub_widget, param_type,
                                          flatten_widget)
            self.toggle_widget[correct_key].append(list(flatten_widget))
            for name, widget, _ in flatten_widget[:self.number_space]:
                self.last_colums[self.last_n].layout().addRow(name, widget)
                already_placed += 1
            self.number_space -= already_placed
            del flatten_widget[:already_placed]
            while len(flatten_widget) > 0:
                self.last_n += 1
                self.last_colums.append(
                    self.add_forms(flatten_widget, self.grid_layout, 0,
                                   self.items_per_column, self.last_n))
                self.number_space = self.items_per_column - len(flatten_widget)
                del flatten_widget[:self.items_per_column]

        else:
            self._delete_toggle_value(caller)

    def _delete_toggle_value(self, caller):
        """
        Handles removing items from layout when the toggle value is off.

        Parameters
        ----------
        caller : AtWidgets
            checkbox that was clicked
        """
        for key, widget, none_possible in self.widgets["togglevalue"]:
            if widget == caller:
                lay = self.toggle_widget[key][1].layout()
                param_type, sub_widget, widget_ls = self.toggle_widget[key]
                for name, sub_sub_widget, param_type in widget_ls:
                    sub_sub_widget.parent().layout().labelForField(
                        sub_sub_widget).deleteLater()
                    lay.addWidget(sub_sub_widget)
                    if self.number_space != 10:
                        self.number_space += 1
                    else:
                        self.number_space = 1
                        self.grid_layout.removeWidget(
                            self.last_colums[self.last_n])
                        self.last_colums[self.last_n].deleteLater()
                        del self.last_colums[self.last_n]
                        self.last_n -= 1
                self.setFixedSize(self.min_size[0], self.min_size[1])
                del self.toggle_widget[key][2]

    def _save(self):
        """
        Save is the function called to get the parameter out of the widget and save them to a file.
        It saves everything inside self.result.
        It also creates a saved_result dict to save to file since iterables are not handled otherwise.
        """
        saved_result = {}
        for param_type, widgets in self.widgets.items():
            for key, widget, none_possible in widgets:
                # Use skip if there is no need to save to file as it is
                skip = False
                if param_type == "bool":
                    val = widget.isChecked()
                elif param_type == "int":
                    val = widget.value()
                    if none_possible and (val == 0 or val == 0.0):
                        val = None
                elif "iterable" in param_type:
                    val = []
                    none_list = False
                    iter_ran = int(param_type.split("_")[1])
                    for el in range(iter_ran):
                        value = self.sub_ls[widget][el].value()
                        val.append(value)
                        if none_possible and (value == 0 or value == 0.0):
                            none_list = True
                            value = None
                        saved_result[key + "_" + str(el)] = str(value)
                    if none_list:
                        val = None
                    skip = True
                elif param_type == "multipleinput":
                    val = widget.itemData(widget.currentIndex())
                    # Repeated code because val should be the index and not the data
                    saved_result[key] = str(widget.currentIndex())
                    skip = True
                elif param_type == "togglevalue":
                    if not widget.isChecked():
                        continue
                    val = []
                    none_list = False
                    counter = 0
                    for name, sub_sub_widget, _ in self.toggle_widget[key][2]:
                        value = sub_sub_widget.value()
                        val.append(value)
                        if none_possible and (value == 0 or value == 0.0):
                            none_list = True
                            value = None
                        saved_result[name + "_" + str(counter)] = str(value)
                        counter += 1
                    if none_list:
                        val = None
                    skip = True

                else:
                    val = widget.text()
                    if none_possible and val == '':
                        val = None

                self.result[key] = val
                if not skip:
                    if param_type != "bool":
                        val = str(val)
                    saved_result[key] = val
        if self.fnct is not None:
            config.add_config({self.fnct: saved_result})
        self.accept()

    def get_result(self) -> dict:
        """
        Returns the value collected by the widget.

        Returns
        -------
        dict
            Dict composed of variable name as key and the value entered by the user
        """
        return self.result

    def _set_default(self, widget: QWidget, default_val: object) -> object:
        """
        Saves the default value in a dict used to restore to default.

        Parameters
        ----------
        widget : QWidget
            The widget that should have this default value
        default_val : object
            The default value

        Returns
        -------
        object
            returns the input
        """
        self.default[widget] = default_val
        return default_val

    def _restore_default(self):
        """
        Restores all the widget to their default value.
        """
        for param_type, widgets in self.widgets.items():
            for key, widget, none_possible in widgets:
                if param_type == "bool":
                    widget.setChecked(self.default[widget])
                elif param_type == "int":
                    widget.setValue(self.default[widget])
                elif "iterable" in param_type:
                    iter_ran = int(param_type.split("_")[1])
                    for el in range(iter_ran):
                        sub_widget = self.sub_ls[widget][el]
                        self.sub_ls[widget][el].setValue(
                            self.default[sub_widget])
                elif param_type == "multipleinput":
                    widget.setCurrentIndex(0)
                elif param_type == "togglevalue":
                    if widget.isChecked():
                        self._delete_toggle_value(widget)
                    widget.setChecked(False)
                else:
                    widget.clear()
                    widget.setPlaceholderText(self.default[widget])

    def _layout_iterable(self, key, widget, param_type, append_ls):
        """
        Iterates through widgets that have subwidget and adds them to a list.

        Parameters
        ----------
        key : str
            name of of widget
        widget : QtWidgets
            widget that has subwidget that needs to be unpacked
        param_type : str
            Type of the widget
        append_ls : list
            list in which the unpacked widget will be added
        """
        iter_ran = int(param_type.split("_")[1])
        for idx in range(iter_ran):
            sub_widget = widget.layout().itemAt(idx).widget()
            self.sub_ls[widget].append(sub_widget)
            sub_widget.setFixedWidth(100)
            sub_widget.setFixedHeight(30)
            append_ls.append(
                (key.replace("_", " ").capitalize() + " " + str(idx),
                 sub_widget, param_type))

    def _format_layout(self):
        """
        Creates the layout and organizes it based on the list of widgets.
        """
        # Create layout and add widgets
        all_widget = []
        self.sub_ls = defaultdict(list)
        for param_type, widgets in self.widgets.items():
            for key, widget, none_possible in widgets:
                widget.setFixedWidth(100)
                widget.setFixedHeight(30)
                if "iterable" in param_type:
                    # Loop through all children and add them as a single child
                    self._layout_iterable(key, widget, param_type, all_widget)
                else:
                    all_widget.append(
                        (key.replace("_",
                                     " ").capitalize(), widget, param_type))
        self.grid_layout = QGridLayout()
        all_widget.sort(key=lambda x: x[2], reverse=True)
        self.last_colums = []
        self.number_space, self.last_n = self._create_colums(
            all_widget, self.grid_layout)
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel
                                     | QDialogButtonBox.RestoreDefaults)
        buttonBox.accepted.connect(self._save)
        buttonBox.rejected.connect(self.reject)
        buttonBox.button(QDialogButtonBox.RestoreDefaults).clicked.connect(
            self._restore_default)
        self.grid_layout.addWidget(
            buttonBox, 1, 0, 1,
            len(all_widget) // self.items_per_column + 1, Qt.AlignRight)
        self.setLayout(self.grid_layout)
        self.min_size = (self.minimumWidth(), self.minimumHeight())
        self.setFixedSize(self.min_size[0], self.min_size[1])

    def _create_colums(self,
                       widget_list: list,
                       grid_layout: QtWidgets.QGridLayout,
                       n=0):
        """
        Recursively add items to a column.
        The number of items per column depends on self.items_per_column.

        Parameters
        ----------
        widget_list : list
            list of all widgets that need to be added
        grid_layout : QtWidgets.QGridLayout
            the grid layout where the widgets must be added
        n : int, optional
            Used for recursion to keep track on how many items have already been added, by default 0
        """
        slice_bottom = 0 + self.items_per_column * n
        slice_top = self.items_per_column + self.items_per_column * n

        layout = self.add_forms(widget_list, grid_layout, slice_bottom,
                                slice_top, n)
        self.last_colums.append(layout)
        if self.items_per_column * (n + 1) >= len(widget_list):
            return self.items_per_column - len(
                widget_list[slice_bottom:slice_top]), n
        return self._create_colums(widget_list, grid_layout, n=n + 1)

    def add_forms(self,
                  widget_list: list,
                  grid_layout: QtWidgets.QGridLayout,
                  slice_bottom: int,
                  slice_top: int,
                  n=0):
        """
        Add widgets from a list to a form and add that form to a layout.
        Can be called recursively when multiple forms need to be created.

        Parameters
        ----------
        widget_list : list
            list of widget to add to a form
        grid_layout : QtWidgets.QGridLayout
            grid layout in which the forms should be added
        slice_bottom : int
            start index for slicing
        slice_top : int
            end index for slicing
        n : int, optional
            index to which column the form should be added in the grid layout

        Returns
        -------
        QWidget
            widget containing the layout
        """
        tmp = QWidget()
        layout = QFormLayout()
        for name, widget, _ in widget_list[slice_bottom:slice_top]:
            layout.addRow(name, widget)
        tmp.setLayout(layout)
        tmp.setFixedWidth(
            110 + layout.itemAt(0, QFormLayout.FieldRole).geometry().width())
        grid_layout.addWidget(tmp, 0, n)
        return tmp
Beispiel #16
0
    def __init__(self, m1m3):
        super().__init__()

        self.layout = QVBoxLayout()
        self.dataLayout = QGridLayout()
        self.commandLayout = QVBoxLayout()
        self.plotLayout = QVBoxLayout()
        self.layout.addLayout(self.commandLayout)
        self.layout.addLayout(self.dataLayout)
        self.layout.addLayout(self.plotLayout)
        self.setLayout(self.layout)

        self.fxSetpointLabel = QLabel("UNKNOWN")
        self.fxMeasurementLabel = QLabel("UNKNOWN")
        self.fxErrorLabel = QLabel("UNKNOWN")
        self.fxErrorT1Label = QLabel("UNKNOWN")
        self.fxErrorT2Label = QLabel("UNKNOWN")
        self.fxControlLabel = QLabel("UNKNOWN")
        self.fxControlT1Label = QLabel("UNKNOWN")
        self.fxControlT2Label = QLabel("UNKNOWN")
        self.fySetpointLabel = QLabel("UNKNOWN")
        self.fyMeasurementLabel = QLabel("UNKNOWN")
        self.fyErrorLabel = QLabel("UNKNOWN")
        self.fyErrorT1Label = QLabel("UNKNOWN")
        self.fyErrorT2Label = QLabel("UNKNOWN")
        self.fyControlLabel = QLabel("UNKNOWN")
        self.fyControlT1Label = QLabel("UNKNOWN")
        self.fyControlT2Label = QLabel("UNKNOWN")
        self.fzSetpointLabel = QLabel("UNKNOWN")
        self.fzMeasurementLabel = QLabel("UNKNOWN")
        self.fzErrorLabel = QLabel("UNKNOWN")
        self.fzErrorT1Label = QLabel("UNKNOWN")
        self.fzErrorT2Label = QLabel("UNKNOWN")
        self.fzControlLabel = QLabel("UNKNOWN")
        self.fzControlT1Label = QLabel("UNKNOWN")
        self.fzControlT2Label = QLabel("UNKNOWN")
        self.mxSetpointLabel = QLabel("UNKNOWN")
        self.mxMeasurementLabel = QLabel("UNKNOWN")
        self.mxErrorLabel = QLabel("UNKNOWN")
        self.mxErrorT1Label = QLabel("UNKNOWN")
        self.mxErrorT2Label = QLabel("UNKNOWN")
        self.mxControlLabel = QLabel("UNKNOWN")
        self.mxControlT1Label = QLabel("UNKNOWN")
        self.mxControlT2Label = QLabel("UNKNOWN")
        self.mySetpointLabel = QLabel("UNKNOWN")
        self.myMeasurementLabel = QLabel("UNKNOWN")
        self.myErrorLabel = QLabel("UNKNOWN")
        self.myErrorT1Label = QLabel("UNKNOWN")
        self.myErrorT2Label = QLabel("UNKNOWN")
        self.myControlLabel = QLabel("UNKNOWN")
        self.myControlT1Label = QLabel("UNKNOWN")
        self.myControlT2Label = QLabel("UNKNOWN")
        self.mzSetpointLabel = QLabel("UNKNOWN")
        self.mzMeasurementLabel = QLabel("UNKNOWN")
        self.mzErrorLabel = QLabel("UNKNOWN")
        self.mzErrorT1Label = QLabel("UNKNOWN")
        self.mzErrorT2Label = QLabel("UNKNOWN")
        self.mzControlLabel = QLabel("UNKNOWN")
        self.mzControlT1Label = QLabel("UNKNOWN")
        self.mzControlT2Label = QLabel("UNKNOWN")
        self.fxTimestepLabel = QLabel("UNKNOWN")
        self.fxPLabel = QLabel("UNKNOWN")
        self.fxILabel = QLabel("UNKNOWN")
        self.fxDLabel = QLabel("UNKNOWN")
        self.fxNLabel = QLabel("UNKNOWN")
        self.fxCalculatedALabel = QLabel("UNKNOWN")
        self.fxCalculatedBLabel = QLabel("UNKNOWN")
        self.fxCalculatedCLabel = QLabel("UNKNOWN")
        self.fxCalculatedDLabel = QLabel("UNKNOWN")
        self.fxCalculatedELabel = QLabel("UNKNOWN")
        self.fyTimestepLabel = QLabel("UNKNOWN")
        self.fyPLabel = QLabel("UNKNOWN")
        self.fyILabel = QLabel("UNKNOWN")
        self.fyDLabel = QLabel("UNKNOWN")
        self.fyNLabel = QLabel("UNKNOWN")
        self.fyCalculatedALabel = QLabel("UNKNOWN")
        self.fyCalculatedBLabel = QLabel("UNKNOWN")
        self.fyCalculatedCLabel = QLabel("UNKNOWN")
        self.fyCalculatedDLabel = QLabel("UNKNOWN")
        self.fyCalculatedELabel = QLabel("UNKNOWN")
        self.fzTimestepLabel = QLabel("UNKNOWN")
        self.fzPLabel = QLabel("UNKNOWN")
        self.fzILabel = QLabel("UNKNOWN")
        self.fzDLabel = QLabel("UNKNOWN")
        self.fzNLabel = QLabel("UNKNOWN")
        self.fzCalculatedALabel = QLabel("UNKNOWN")
        self.fzCalculatedBLabel = QLabel("UNKNOWN")
        self.fzCalculatedCLabel = QLabel("UNKNOWN")
        self.fzCalculatedDLabel = QLabel("UNKNOWN")
        self.fzCalculatedELabel = QLabel("UNKNOWN")
        self.mxTimestepLabel = QLabel("UNKNOWN")
        self.mxPLabel = QLabel("UNKNOWN")
        self.mxILabel = QLabel("UNKNOWN")
        self.mxDLabel = QLabel("UNKNOWN")
        self.mxNLabel = QLabel("UNKNOWN")
        self.mxCalculatedALabel = QLabel("UNKNOWN")
        self.mxCalculatedBLabel = QLabel("UNKNOWN")
        self.mxCalculatedCLabel = QLabel("UNKNOWN")
        self.mxCalculatedDLabel = QLabel("UNKNOWN")
        self.mxCalculatedELabel = QLabel("UNKNOWN")
        self.myTimestepLabel = QLabel("UNKNOWN")
        self.myPLabel = QLabel("UNKNOWN")
        self.myILabel = QLabel("UNKNOWN")
        self.myDLabel = QLabel("UNKNOWN")
        self.myNLabel = QLabel("UNKNOWN")
        self.myCalculatedALabel = QLabel("UNKNOWN")
        self.myCalculatedBLabel = QLabel("UNKNOWN")
        self.myCalculatedCLabel = QLabel("UNKNOWN")
        self.myCalculatedDLabel = QLabel("UNKNOWN")
        self.myCalculatedELabel = QLabel("UNKNOWN")
        self.mzTimestepLabel = QLabel("UNKNOWN")
        self.mzPLabel = QLabel("UNKNOWN")
        self.mzILabel = QLabel("UNKNOWN")
        self.mzDLabel = QLabel("UNKNOWN")
        self.mzNLabel = QLabel("UNKNOWN")
        self.mzCalculatedALabel = QLabel("UNKNOWN")
        self.mzCalculatedBLabel = QLabel("UNKNOWN")
        self.mzCalculatedCLabel = QLabel("UNKNOWN")
        self.mzCalculatedDLabel = QLabel("UNKNOWN")
        self.mzCalculatedELabel = QLabel("UNKNOWN")

        self.chart = TimeChart(
            {"Command (N or N/m)": ["Fx", "Fy", "Fz", "Mx", "My", "Mz"]}
        )
        self.chartView = TimeChartView(self.chart)

        row = 0
        col = 0
        self.dataLayout.addWidget(QLabel("Setpoint"), row, col + 1)
        self.dataLayout.addWidget(QLabel("Measurement"), row, col + 2)
        self.dataLayout.addWidget(QLabel("Error"), row, col + 3)
        self.dataLayout.addWidget(QLabel("ErrorT1"), row, col + 4)
        self.dataLayout.addWidget(QLabel("ErrorT2"), row, col + 5)
        self.dataLayout.addWidget(QLabel("Control"), row, col + 6)
        self.dataLayout.addWidget(QLabel("ControlT1"), row, col + 7)
        self.dataLayout.addWidget(QLabel("ControlT2"), row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fx"), row, col)
        self.dataLayout.addWidget(self.fxSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fxMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fxErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fxErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fxErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fxControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fxControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fxControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fy"), row, col)
        self.dataLayout.addWidget(self.fySetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fyMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fyErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fyErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fyErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fyControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fyControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fyControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fz"), row, col)
        self.dataLayout.addWidget(self.fzSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fzMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fzErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fzErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fzErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fzControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fzControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fzControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Mx"), row, col)
        self.dataLayout.addWidget(self.mxSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.mxMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.mxErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.mxErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.mxErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.mxControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.mxControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.mxControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("My"), row, col)
        self.dataLayout.addWidget(self.mySetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.myMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.myErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.myErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.myErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.myControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.myControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.myControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Mz"), row, col)
        self.dataLayout.addWidget(self.mzSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.mzMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.mzErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.mzErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.mzErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.mzControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.mzControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.mzControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel(" "), row, col)
        row += 1
        self.dataLayout.addWidget(QLabel("Timestep"), row, col + 1)
        self.dataLayout.addWidget(QLabel("P"), row, col + 2)
        self.dataLayout.addWidget(QLabel("I"), row, col + 3)
        self.dataLayout.addWidget(QLabel("D"), row, col + 4)
        self.dataLayout.addWidget(QLabel("N"), row, col + 5)
        self.dataLayout.addWidget(QLabel("CalculatedA"), row, col + 6)
        self.dataLayout.addWidget(QLabel("CalculatedB"), row, col + 7)
        self.dataLayout.addWidget(QLabel("CalculatedC"), row, col + 8)
        self.dataLayout.addWidget(QLabel("CalculatedD"), row, col + 9)
        self.dataLayout.addWidget(QLabel("CalculatedE"), row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fx"), row, col)
        self.dataLayout.addWidget(self.fxTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fxPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fxILabel, row, col + 3)
        self.dataLayout.addWidget(self.fxDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fxNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fxCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fxCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fxCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fxCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fxCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fy"), row, col)
        self.dataLayout.addWidget(self.fyTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fyPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fyILabel, row, col + 3)
        self.dataLayout.addWidget(self.fyDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fyNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fyCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fyCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fyCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fyCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fyCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fz"), row, col)
        self.dataLayout.addWidget(self.fzTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fzPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fzILabel, row, col + 3)
        self.dataLayout.addWidget(self.fzDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fzNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fzCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fzCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fzCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fzCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fzCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Mx"), row, col)
        self.dataLayout.addWidget(self.mxTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.mxPLabel, row, col + 2)
        self.dataLayout.addWidget(self.mxILabel, row, col + 3)
        self.dataLayout.addWidget(self.mxDLabel, row, col + 4)
        self.dataLayout.addWidget(self.mxNLabel, row, col + 5)
        self.dataLayout.addWidget(self.mxCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.mxCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.mxCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.mxCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.mxCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("My"), row, col)
        self.dataLayout.addWidget(self.myTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.myPLabel, row, col + 2)
        self.dataLayout.addWidget(self.myILabel, row, col + 3)
        self.dataLayout.addWidget(self.myDLabel, row, col + 4)
        self.dataLayout.addWidget(self.myNLabel, row, col + 5)
        self.dataLayout.addWidget(self.myCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.myCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.myCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.myCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.myCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Mz"), row, col)
        self.dataLayout.addWidget(self.mzTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.mzPLabel, row, col + 2)
        self.dataLayout.addWidget(self.mzILabel, row, col + 3)
        self.dataLayout.addWidget(self.mzDLabel, row, col + 4)
        self.dataLayout.addWidget(self.mzNLabel, row, col + 5)
        self.dataLayout.addWidget(self.mzCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.mzCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.mzCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.mzCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.mzCalculatedELabel, row, col + 10)

        self.plotLayout.addWidget(self.chartView)

        m1m3.pidInfo.connect(self.pidInfo)
        m1m3.pidData.connect(self.pidData)
    def doLayout(self):

        self.update_total_value()
        self.intelBox = QGroupBox("Units :")
        self.intelLayout = QGridLayout()
        i = 0
        for g in self.ground_object.groups:
            if not hasattr(g, "units_losts"):
                g.units_losts = []
            for u in g.units:
                unit_display_name = u.type
                unit_type = vehicles.vehicle_map.get(u.type)
                if unit_type is not None:
                    unit_display_name = db.unit_get_expanded_info(
                        self.game.enemy_country, unit_type, 'name')
                self.intelLayout.addWidget(
                    QLabel("<b>Unit #" + str(u.id) + " - " +
                           str(unit_display_name) + "</b>"), i, 0)
                i = i + 1

            for u in g.units_losts:

                utype = unit_type_of(u)
                if utype in PRICES:
                    price = PRICES[utype]
                else:
                    price = 6

                self.intelLayout.addWidget(
                    QLabel("<b>Unit #" + str(u.id) + " - " + str(u.type) +
                           "</b> [DEAD]"), i, 0)
                if self.cp.captured:
                    repair = QPushButton("Repair [" + str(price) + "M]")
                    repair.setProperty("style", "btn-success")
                    repair.clicked.connect(
                        lambda u=u, g=g, p=price: self.repair_unit(g, u, p))
                    self.intelLayout.addWidget(repair, i, 1)
                i = i + 1
        stretch = QVBoxLayout()
        stretch.addStretch()
        self.intelLayout.addLayout(stretch, i, 0)

        self.buildingBox = QGroupBox("Buildings :")
        self.buildingsLayout = QGridLayout()

        j = 0
        total_income = 0
        received_income = 0
        for i, building in enumerate(self.buildings):
            if building.dcs_identifier not in FORTIFICATION_BUILDINGS:
                self.buildingsLayout.addWidget(
                    QBuildingInfo(building, self.ground_object), j / 3, j % 3)
                j = j + 1

            if building.category in REWARDS.keys():
                total_income = total_income + REWARDS[building.category]
                if not building.is_dead:
                    received_income = received_income + REWARDS[
                        building.category]
            else:
                logging.warning(building.category + " not in REWARDS")

        self.financesBox = QGroupBox("Finances: ")
        self.financesBoxLayout = QGridLayout()
        self.financesBoxLayout.addWidget(
            QLabel("Available: " + str(total_income) + "M"), 2, 1)
        self.financesBoxLayout.addWidget(
            QLabel("Receiving: " + str(received_income) + "M"), 2, 2)

        self.financesBox.setLayout(self.financesBoxLayout)
        self.buildingBox.setLayout(self.buildingsLayout)
        self.intelBox.setLayout(self.intelLayout)
Beispiel #18
0
    def __init__(self):
        super(WidgetConfig, self).__init__()

        HEIGHT = 30

        grid = QGridLayout()

        # 使用默认摄像头复选框
        self.check_camera = QCheckBox('Use default camera')
        self.check_camera.setChecked(False)
        self.check_camera.stateChanged.connect(self.slot_check_camera)

        grid.addWidget(self.check_camera, 0, 0, 1, 3)  # 一行三列

        # 选择视频文件
        label_video = QLabel('Detect File')
        self.line_video = QLineEdit()
        if 'video' in GLOBAL.config:
            self.line_video.setText(GLOBAL.config['video'])
        self.line_video.setFixedHeight(HEIGHT)
        self.line_video.setEnabled(False)
        self.line_video.editingFinished.connect(
            lambda: GLOBAL.record_config({'video': self.line_video.text()}))

        self.btn_video = QPushButton('Choose')
        self.btn_video.setFixedHeight(HEIGHT)
        self.btn_video.setEnabled(False)
        self.btn_video.clicked.connect(self.choose_video_file)

        self.slot_check_camera()

        grid.addWidget(label_video, 1, 0)
        grid.addWidget(self.line_video, 1, 1)
        grid.addWidget(self.btn_video, 1, 2)

        # 选择权重文件
        label_weights = QLabel('Weights File')
        self.line_weights = QLineEdit()
        if 'weights' in GLOBAL.config:
            self.line_weights.setText(GLOBAL.config['weights'])
        self.line_weights.setFixedHeight(HEIGHT)
        self.line_weights.editingFinished.connect(lambda: GLOBAL.record_config(
            {'weights': self.line_weights.text()}))

        self.btn_weights = QPushButton('Choose')
        self.btn_weights.setFixedHeight(HEIGHT)
        self.btn_weights.clicked.connect(self.choose_weights_file)

        grid.addWidget(label_weights, 2, 0)
        grid.addWidget(self.line_weights, 2, 1)
        grid.addWidget(self.btn_weights, 2, 2)

        # 是否使用GPU
        label_device = QLabel('CUDA device')
        self.line_device = QLineEdit('cpu')
        if 'device' in GLOBAL.config:
            self.line_device.setText(GLOBAL.config['device'])
        else:
            self.line_device.setText('cpu')
        self.line_device.setPlaceholderText('cpu or 0 or 0,1,2,3')
        self.line_device.setFixedHeight(HEIGHT)
        self.line_device.editingFinished.connect(
            lambda: GLOBAL.record_config({'device': self.line_device.text()}))

        grid.addWidget(label_device, 3, 0)
        grid.addWidget(self.line_device, 3, 1, 1, 2)

        # 设置图像大小
        label_size = QLabel('Img Size')
        self.combo_size = QComboBox()
        self.combo_size.setFixedHeight(HEIGHT)
        self.combo_size.setStyleSheet(
            'QAbstractItemView::item {height: 40px;}')
        self.combo_size.setView(QListView())
        self.combo_size.addItem('320', 320)
        self.combo_size.addItem('416', 416)
        self.combo_size.addItem('480', 480)
        self.combo_size.addItem('544', 544)
        self.combo_size.addItem('640', 640)
        self.combo_size.setCurrentIndex(2)
        self.combo_size.currentIndexChanged.connect(
            lambda: GLOBAL.record_config(
                {'img_size': self.combo_size.currentData()}))

        grid.addWidget(label_size, 4, 0)
        grid.addWidget(self.combo_size, 4, 1, 1, 2)

        # 设置置信度阈值
        label_conf = QLabel('Confidence')
        self.spin_conf = QDoubleSpinBox()
        self.spin_conf.setFixedHeight(HEIGHT)
        self.spin_conf.setDecimals(1)
        self.spin_conf.setRange(0.1, 0.9)
        self.spin_conf.setSingleStep(0.1)
        if 'conf_thresh' in GLOBAL.config:
            self.spin_conf.setValue(GLOBAL.config['conf_thresh'])
        else:
            self.spin_conf.setValue(0.4)  # 默认值
            GLOBAL.record_config({'conf_thresh': 0.4})
        self.spin_conf.valueChanged.connect(lambda: GLOBAL.record_config(
            {'conf_thresh': round(self.spin_conf.value(), 1)}))

        grid.addWidget(label_conf, 5, 0)
        grid.addWidget(self.spin_conf, 5, 1, 1, 2)

        # 设置IOU阈值
        label_iou = QLabel('IOU')
        self.spin_iou = QDoubleSpinBox()
        self.spin_iou.setFixedHeight(HEIGHT)
        self.spin_iou.setDecimals(1)
        self.spin_iou.setRange(0.1, 0.9)
        self.spin_iou.setSingleStep(0.1)
        if 'iou_thresh' in GLOBAL.config:
            self.spin_iou.setValue(GLOBAL.config['iou_thresh'])
        else:
            self.spin_iou.setValue(0.5)  # 默认值
            GLOBAL.record_config({'iou_thresh': 0.5})
        self.spin_iou.valueChanged.connect(lambda: GLOBAL.record_config(
            {'iou_thresh': round(self.spin_iou.value(), 1)}))

        grid.addWidget(label_iou, 6, 0)
        grid.addWidget(self.spin_iou, 6, 1, 1, 2)

        # class-agnostic NMS
        self.check_agnostic = QCheckBox('Agnostic')
        if 'agnostic' in GLOBAL.config:
            self.check_agnostic.setChecked(GLOBAL.config['agnostic'])
        else:
            self.check_agnostic.setChecked(True)
        self.check_agnostic.stateChanged.connect(lambda: GLOBAL.record_config(
            {'agnostic': self.check_agnostic.isChecked()}))

        grid.addWidget(self.check_agnostic, 7, 0, 1, 3)  # 一行三列

        # augmented inference
        self.check_augment = QCheckBox('Augment')
        if 'augment' in GLOBAL.config:
            self.check_augment.setChecked(GLOBAL.config['augment'])
        else:
            self.check_augment.setChecked(True)
        self.check_augment.stateChanged.connect(lambda: GLOBAL.record_config(
            {'augment': self.check_augment.isChecked()}))

        grid.addWidget(self.check_augment, 8, 0, 1, 3)  # 一行三列

        self.setLayout(grid)  # 设置布局
class QGroundObjectMenu(QDialog):

    changed = QtCore.Signal()

    def __init__(self, parent, ground_object: TheaterGroundObject,
                 buildings: Optional[List[TheaterGroundObject]],
                 cp: ControlPoint, game: Game):
        super().__init__(parent)
        self.setMinimumWidth(350)
        self.ground_object = ground_object
        if buildings is None:
            self.buildings = []
        else:
            self.buildings = buildings
        self.cp = cp
        self.game = game
        self.setWindowTitle("Location " + self.ground_object.obj_name)
        self.setWindowIcon(EVENT_ICONS["capture"])
        self.intelBox = QGroupBox("Units :")
        self.buildingBox = QGroupBox("Buildings :")
        self.intelLayout = QGridLayout()
        self.buildingsLayout = QGridLayout()
        self.sell_all_button = None
        self.total_value = 0
        self.init_ui()

    def init_ui(self):

        self.mainLayout = QVBoxLayout()
        self.budget = QBudgetBox(self.game)
        self.budget.setGame(self.game)

        self.doLayout()

        if self.ground_object.dcs_identifier == "AA":
            self.mainLayout.addWidget(self.intelBox)
        else:
            self.mainLayout.addWidget(self.buildingBox)
            if self.cp.captured:
                self.mainLayout.addWidget(self.financesBox)

        self.actionLayout = QHBoxLayout()

        self.sell_all_button = QPushButton("Disband (+" +
                                           str(self.total_value) + "M)")
        self.sell_all_button.clicked.connect(self.sell_all)
        self.sell_all_button.setProperty("style", "btn-danger")

        self.buy_replace = QPushButton("Buy/Replace")
        self.buy_replace.clicked.connect(self.buy_group)
        self.buy_replace.setProperty("style", "btn-success")

        if not isinstance(self.ground_object, NavalGroundObject):
            if self.total_value > 0:
                self.actionLayout.addWidget(self.sell_all_button)
            self.actionLayout.addWidget(self.buy_replace)

        if self.cp.captured and self.ground_object.dcs_identifier == "AA":
            self.mainLayout.addLayout(self.actionLayout)
        self.setLayout(self.mainLayout)

    def doLayout(self):

        self.update_total_value()
        self.intelBox = QGroupBox("Units :")
        self.intelLayout = QGridLayout()
        i = 0
        for g in self.ground_object.groups:
            if not hasattr(g, "units_losts"):
                g.units_losts = []
            for u in g.units:
                unit_display_name = u.type
                unit_type = vehicles.vehicle_map.get(u.type)
                if unit_type is not None:
                    unit_display_name = db.unit_get_expanded_info(
                        self.game.enemy_country, unit_type, 'name')
                self.intelLayout.addWidget(
                    QLabel("<b>Unit #" + str(u.id) + " - " +
                           str(unit_display_name) + "</b>"), i, 0)
                i = i + 1

            for u in g.units_losts:

                utype = unit_type_of(u)
                if utype in PRICES:
                    price = PRICES[utype]
                else:
                    price = 6

                self.intelLayout.addWidget(
                    QLabel("<b>Unit #" + str(u.id) + " - " + str(u.type) +
                           "</b> [DEAD]"), i, 0)
                if self.cp.captured:
                    repair = QPushButton("Repair [" + str(price) + "M]")
                    repair.setProperty("style", "btn-success")
                    repair.clicked.connect(
                        lambda u=u, g=g, p=price: self.repair_unit(g, u, p))
                    self.intelLayout.addWidget(repair, i, 1)
                i = i + 1
        stretch = QVBoxLayout()
        stretch.addStretch()
        self.intelLayout.addLayout(stretch, i, 0)

        self.buildingBox = QGroupBox("Buildings :")
        self.buildingsLayout = QGridLayout()

        j = 0
        total_income = 0
        received_income = 0
        for i, building in enumerate(self.buildings):
            if building.dcs_identifier not in FORTIFICATION_BUILDINGS:
                self.buildingsLayout.addWidget(
                    QBuildingInfo(building, self.ground_object), j / 3, j % 3)
                j = j + 1

            if building.category in REWARDS.keys():
                total_income = total_income + REWARDS[building.category]
                if not building.is_dead:
                    received_income = received_income + REWARDS[
                        building.category]
            else:
                logging.warning(building.category + " not in REWARDS")

        self.financesBox = QGroupBox("Finances: ")
        self.financesBoxLayout = QGridLayout()
        self.financesBoxLayout.addWidget(
            QLabel("Available: " + str(total_income) + "M"), 2, 1)
        self.financesBoxLayout.addWidget(
            QLabel("Receiving: " + str(received_income) + "M"), 2, 2)

        self.financesBox.setLayout(self.financesBoxLayout)
        self.buildingBox.setLayout(self.buildingsLayout)
        self.intelBox.setLayout(self.intelLayout)

    def do_refresh_layout(self):
        try:
            for i in range(self.mainLayout.count()):
                item = self.mainLayout.itemAt(i)
                if item is not None and item.widget() is not None:
                    item.widget().setParent(None)
            self.sell_all_button.setParent(None)
            self.buy_replace.setParent(None)
            self.actionLayout.setParent(None)

            self.doLayout()
            if self.ground_object.dcs_identifier == "AA":
                self.mainLayout.addWidget(self.intelBox)
            else:
                self.mainLayout.addWidget(self.buildingBox)

            self.actionLayout = QHBoxLayout()
            if self.total_value > 0:
                self.actionLayout.addWidget(self.sell_all_button)
            self.actionLayout.addWidget(self.buy_replace)

            if self.cp.captured and self.ground_object.dcs_identifier == "AA":
                self.mainLayout.addLayout(self.actionLayout)

        except Exception as e:
            print(e)
        self.update_total_value()
        self.changed.emit()

    def update_total_value(self):
        total_value = 0
        for group in self.ground_object.groups:
            for u in group.units:
                utype = unit_type_of(u)
                if utype in PRICES:
                    total_value = total_value + PRICES[utype]
                else:
                    total_value = total_value + 1
        if self.sell_all_button is not None:
            self.sell_all_button.setText("Disband (+$" +
                                         str(self.total_value) + "M)")
        self.total_value = total_value

    def repair_unit(self, group, unit, price):
        if self.game.budget > price:
            self.game.budget -= price
            group.units_losts = [
                u for u in group.units_losts if u.id != unit.id
            ]
            group.units.append(unit)
            GameUpdateSignal.get_instance().updateGame(self.game)

            # Remove destroyed units in the vicinity
            destroyed_units = self.game.get_destroyed_units()
            for d in destroyed_units:
                p = Point(d["x"], d["z"])
                if p.distance_to_point(unit.position) < 15:
                    destroyed_units.remove(d)
                    logging.info("Removed destroyed units " + str(d))
            logging.info("Repaired unit : " + str(unit.id) + " " +
                         str(unit.type))

        self.do_refresh_layout()
        self.changed.emit()

    def sell_all(self):
        self.update_total_value()
        self.game.budget = self.game.budget + self.total_value
        self.ground_object.groups = []
        self.do_refresh_layout()
        GameUpdateSignal.get_instance().updateBudget(self.game)

    def buy_group(self):
        self.subwindow = QBuyGroupForGroundObjectDialog(
            self, self.ground_object, self.cp, self.game, self.total_value)
        self.subwindow.changed.connect(self.do_refresh_layout)
        self.subwindow.show()
class QBuyGroupForGroundObjectDialog(QDialog):

    changed = QtCore.Signal()

    def __init__(self, parent, ground_object: TheaterGroundObject,
                 cp: ControlPoint, game: Game, current_group_value: int):
        super(QBuyGroupForGroundObjectDialog, self).__init__(parent)

        self.setMinimumWidth(350)
        self.ground_object = ground_object
        self.cp = cp
        self.game = game
        self.current_group_value = current_group_value

        self.setWindowTitle("Buy units @ " + self.ground_object.obj_name)
        self.setWindowIcon(EVENT_ICONS["capture"])

        self.buySamButton = QPushButton("Buy")
        self.buyArmorButton = QPushButton("Buy")
        self.buySamLayout = QGridLayout()
        self.buyArmorLayout = QGridLayout()
        self.amount = QSpinBox()
        self.buyArmorCombo = QComboBox()
        self.samCombo = QComboBox()
        self.buySamBox = QGroupBox("Buy SAM site :")
        self.buyArmorBox = QGroupBox("Buy defensive position :")

        self.init_ui()

    def init_ui(self):
        faction = self.game.player_faction

        # Sams

        possible_sams = get_faction_possible_sams_generator(faction)
        for sam in possible_sams:
            self.samCombo.addItem(sam.name + " [$" + str(sam.price) + "M]",
                                  userData=sam)
        self.samCombo.currentIndexChanged.connect(self.samComboChanged)

        self.buySamLayout.addWidget(QLabel("Site Type :"), 0, 0, Qt.AlignLeft)
        self.buySamLayout.addWidget(self.samCombo,
                                    0,
                                    1,
                                    alignment=Qt.AlignRight)
        self.buySamLayout.addWidget(self.buySamButton,
                                    1,
                                    1,
                                    alignment=Qt.AlignRight)
        stretch = QVBoxLayout()
        stretch.addStretch()
        self.buySamLayout.addLayout(stretch, 2, 0)

        self.buySamButton.clicked.connect(self.buySam)

        # Armored units

        armored_units = db.find_unittype(
            PinpointStrike,
            faction.name)  # Todo : refactor this legacy nonsense
        for unit in set(armored_units):
            self.buyArmorCombo.addItem(db.unit_type_name_2(unit) + " [$" +
                                       str(db.PRICES[unit]) + "M]",
                                       userData=unit)
        self.buyArmorCombo.currentIndexChanged.connect(self.armorComboChanged)

        self.amount.setMinimum(2)
        self.amount.setMaximum(8)
        self.amount.setValue(2)
        self.amount.valueChanged.connect(self.amountComboChanged)

        self.buyArmorLayout.addWidget(QLabel("Unit type :"), 0, 0,
                                      Qt.AlignLeft)
        self.buyArmorLayout.addWidget(self.buyArmorCombo,
                                      0,
                                      1,
                                      alignment=Qt.AlignRight)
        self.buyArmorLayout.addWidget(QLabel("Group size :"),
                                      1,
                                      0,
                                      alignment=Qt.AlignLeft)
        self.buyArmorLayout.addWidget(self.amount,
                                      1,
                                      1,
                                      alignment=Qt.AlignRight)
        self.buyArmorLayout.addWidget(self.buyArmorButton,
                                      2,
                                      1,
                                      alignment=Qt.AlignRight)
        stretch2 = QVBoxLayout()
        stretch2.addStretch()
        self.buyArmorLayout.addLayout(stretch2, 3, 0)

        self.buyArmorButton.clicked.connect(self.buyArmor)

        # Do layout
        self.buySamBox.setLayout(self.buySamLayout)
        self.buyArmorBox.setLayout(self.buyArmorLayout)

        self.mainLayout = QHBoxLayout()
        self.mainLayout.addWidget(self.buySamBox)

        if self.ground_object.airbase_group:
            self.mainLayout.addWidget(self.buyArmorBox)

        self.setLayout(self.mainLayout)

        try:
            self.samComboChanged(0)
            self.armorComboChanged(0)
        except:
            pass

    def samComboChanged(self, index):
        self.buySamButton.setText("Buy [$" +
                                  str(self.samCombo.itemData(index).price) +
                                  "M] [-$" + str(self.current_group_value) +
                                  "M]")

    def armorComboChanged(self, index):
        self.buyArmorButton.setText(
            "Buy [$" + str(db.PRICES[self.buyArmorCombo.itemData(index)] *
                           self.amount.value()) + "M][-$" +
            str(self.current_group_value) + "M]")

    def amountComboChanged(self):
        self.buyArmorButton.setText("Buy [$" + str(db.PRICES[
            self.buyArmorCombo.itemData(self.buyArmorCombo.currentIndex())] *
                                                   self.amount.value()) +
                                    "M][-$" + str(self.current_group_value) +
                                    "M]")

    def buyArmor(self):
        logging.info("Buying Armor ")
        utype = self.buyArmorCombo.itemData(self.buyArmorCombo.currentIndex())
        logging.info(utype)
        price = db.PRICES[utype] * self.amount.value(
        ) - self.current_group_value
        if price > self.game.budget:
            self.error_money()
            self.close()
            return
        else:
            self.game.budget -= price

        # Generate Armor
        group = generate_armor_group_of_type_and_size(self.game,
                                                      self.ground_object,
                                                      utype,
                                                      int(self.amount.value()))
        self.ground_object.groups = [group]

        GameUpdateSignal.get_instance().updateBudget(self.game)

        self.changed.emit()
        self.close()

    def buySam(self):
        sam_generator = self.samCombo.itemData(self.samCombo.currentIndex())
        price = sam_generator.price - self.current_group_value
        if price > self.game.budget:
            self.error_money()
            return
        else:
            self.game.budget -= price

        # Generate SAM
        generator = sam_generator(self.game, self.ground_object)
        generator.generate()
        self.ground_object.groups = list(generator.groups)

        GameUpdateSignal.get_instance().updateBudget(self.game)

        self.changed.emit()
        self.close()

    def error_money(self):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText("Not enough money to buy these units !")
        msg.setWindowTitle("Not enough money")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.setWindowFlags(Qt.WindowStaysOnTopHint)
        msg.exec_()
        self.close()
    def __init__(self, parent=None):
        super(BlockingClient, self).__init__(parent)

        self.thread = FortuneThread()
        self.currentFortune = ''

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.hostLineEdit = QLineEdit(ipAddress)
        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostLineEdit)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel(
                "This example requires that you run the Fortune Server example as well.")
        self.statusLabel.setWordWrap(True)

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.thread.newFortune.connect(self.showFortune)
        self.thread.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostLineEdit, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Blocking Fortune Client")
        self.portLineEdit.setFocus()
Beispiel #22
0
 def __init__(self, weapon: Weapon, parent: QWidget):
     # noinspection PyTypeChecker
     super(WeaponView, self).__init__(parent, Qt.WindowType.Dialog)
     layout = QGridLayout()
     layout.addWidget(
         QLabel(weapon.name.title()),
         0,
         0,
         1,
         3,
     )
     layout.addWidget(
         QLabel(weapon.type.value.title()),
         0,
         3,
     )
     if weapon.character is not None:
         character = f'{weapon.character.name.title()} only'
     else:
         character = 'All characters'
     layout.addWidget(
         QLabel(character),
         1,
         0,
         1,
         3,
     )
     # if weapon.game is not None:
     #     layout.addWidget(
     #         QLabel(f'{weapon.game}'),
     #         1, 3,
     #     )
     stats_row = layout.rowCount()
     for i, s in enumerate(weapon.stats):
         layout.addWidget(
             QLabel(f'{Stats.titles[i]}: {weapon.stats[i]}'),
             stats_row,
             i,
         )
     self.setWindowTitle(weapon.name.title())
     self.setWindowModality(Qt.WindowModality.WindowModal)
     self.setLayout(layout)
Beispiel #23
0
    def __init__(self, m1m3, mtmount):
        super().__init__()

        self.layout = QHBoxLayout()
        dataLayout = QGridLayout()
        self.layout.addLayout(dataLayout)
        self.setLayout(self.layout)

        self.summaryStateLabel = QLabel("UNKNOWN")
        self.mirrorStateLabel = QLabel("UNKNOWN")
        self.modeStateLabel = QLabel("UNKNOWN")
        self.errorCodeLabel = QLabel("---")
        self.interlockWarningLabel = QLabel("UNKNOWN")
        self.powerWarningLabel = QLabel("UNKNOWN")
        self.forceActuatorWarningLabel = LogEventWarning(
            m1m3.forceActuatorWarning)
        self.hardpointActuatorWarningLabel = QLabel("UNKNOWN")
        self.hardpointMonitorWarningLabel = QLabel("UNKNOWN")
        self.inclinometerWarningLabel = QLabel("UNKNOWN")
        self.accelerometerWarningLabel = QLabel("UNKNOWN")
        self.gyroWarningLabel = QLabel("UNKNOWN")
        self.airSupplyWarningLabel = QLabel("UNKNOWN")
        self.imsWarningLabel = QLabel("UNKNOWN")
        self.cellLightWarningLabel = QLabel("UNKNOWN")
        self.heartbeatLabel = Heartbeat()

        def createForcesAndMoments():
            return {
                "fx": Force(),
                "fy": Force(),
                "fz": Force(),
                "mx": Moment(),
                "my": Moment(),
                "mz": Moment(),
                "forceMagnitude": Force(),
            }

        def createXYR():
            return {
                "xPosition": Mm(),
                "yPosition": Mm(),
                "zPosition": Mm(),
                "xRotation": Arcsec(),
                "yRotation": Arcsec(),
                "zRotation": Arcsec(),
            }

        def addLabelRow(labels, row, col):
            for label in labels:
                dataLayout.addWidget(QLabel(f"<b>{label}</b>"), row, col)
                col += 1

        def addDataRow(variables, row, col):
            for k, v in variables.items():
                dataLayout.addWidget(v, row, col)
                col += 1

        self.faCommanded = createForcesAndMoments()
        self.faMeasured = createForcesAndMoments()
        self.hpMeasured = createForcesAndMoments()

        self.hpPosition = createXYR()
        self.imsPosition = createXYR()

        self.accelationXLabel = QLabel("UNKNOWN")
        self.accelationYLabel = QLabel("UNKNOWN")
        self.accelationZLabel = QLabel("UNKNOWN")
        self.velocityXLabel = QLabel("UNKNOWN")
        self.velocityYLabel = QLabel("UNKNOWN")
        self.velocityZLabel = QLabel("UNKNOWN")
        self.airCommandLabel = QLabel("UNKNOWN")
        self.airValveLabel = QLabel("UNKNOWN")
        self.inclinometerLabel = QLabel("UNKNOWN")
        self.tmaAzimuthLabel = QLabel("UNKNOWN")
        self.tmaElevationLabel = QLabel("UNKNOWN")

        self.cscVersion = QLabel("---")
        self.salVersion = QLabel("---")
        self.xmlVersion = QLabel("---")
        self.osplVersion = QLabel("---")

        row = 0
        col = 0
        dataLayout.addWidget(QLabel("Summary State"), row, col)
        dataLayout.addWidget(self.summaryStateLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Mirror State"), row, col)
        dataLayout.addWidget(self.mirrorStateLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Mode State"), row, col)
        dataLayout.addWidget(self.modeStateLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("ErrorCode"), row, col)
        dataLayout.addWidget(self.errorCodeLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Interlocks"), row, col)
        dataLayout.addWidget(self.interlockWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Power"), row, col)
        dataLayout.addWidget(self.powerWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Force Actuators"), row, col)
        dataLayout.addWidget(self.forceActuatorWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Hardpoint Actuators"), row, col)
        dataLayout.addWidget(self.hardpointActuatorWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Hardpoint Monitors"), row, col)
        dataLayout.addWidget(self.hardpointMonitorWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Inclinometer"), row, col)
        dataLayout.addWidget(self.inclinometerWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Accelerometer"), row, col)
        dataLayout.addWidget(self.accelerometerWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Gyro"), row, col)
        dataLayout.addWidget(self.gyroWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Air Supply"), row, col)
        dataLayout.addWidget(self.airSupplyWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("IMS"), row, col)
        dataLayout.addWidget(self.imsWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Cell Light"), row, col)
        dataLayout.addWidget(self.cellLightWarningLabel, row, col + 1)
        row += 1
        dataLayout.addWidget(QLabel("Heartbeat"), row, col)
        dataLayout.addWidget(self.heartbeatLabel, row, col + 1)

        row = 0
        col = 2
        dataLayout.addWidget(QLabel("<b>Forces</b>"), row, col)
        addLabelRow(["X", "Y", "Z", "Mx", "My", "Mz", "Magnitude"], row,
                    col + 1)

        row += 1
        dataLayout.addWidget(QLabel("<b>Commanded</b>"), row, col)
        addDataRow(self.faCommanded, row, col + 1)
        row += 1

        dataLayout.addWidget(QLabel("<b>Measured</b>"), row, col)
        addDataRow(self.faMeasured, row, col + 1)

        row += 1
        dataLayout.addWidget(QLabel("<b>Hardpoints</b>"), row, col)
        addDataRow(self.hpMeasured, row, col + 1)

        row += 1
        dataLayout.addWidget(QLabel("<b>Mirror Position</b>"), row, col)
        addLabelRow(["X", "Y", "Z", "Rx", "Ry", "Rz"], row, col + 1)

        row += 1
        dataLayout.addWidget(QLabel("<b>Hardpoints</b>"), row, col)
        addDataRow(self.hpPosition, row, col + 1)

        row += 1
        dataLayout.addWidget(QLabel("<b>IMS</b>"), row, col)
        addDataRow(self.imsPosition, row, col + 1)

        row += 1
        dataLayout.addWidget(QLabel("Angular Acceleration"), row, col)
        dataLayout.addWidget(QLabel("X (?)"), row, col + 1)
        dataLayout.addWidget(QLabel("Y (?)"), row, col + 2)
        dataLayout.addWidget(QLabel("Z (?)"), row, col + 3)
        row += 1
        dataLayout.addWidget(self.accelationXLabel, row, col + 1)
        dataLayout.addWidget(self.accelationYLabel, row, col + 2)
        dataLayout.addWidget(self.accelationZLabel, row, col + 3)
        row += 1
        dataLayout.addWidget(QLabel("Angular Velocity"), row, col)
        dataLayout.addWidget(QLabel("X (?)"), row, col + 1)
        dataLayout.addWidget(QLabel("Y (?)"), row, col + 2)
        dataLayout.addWidget(QLabel("Z (?)"), row, col + 3)
        row += 1
        dataLayout.addWidget(self.velocityXLabel, row, col + 1)
        dataLayout.addWidget(self.velocityYLabel, row, col + 2)
        dataLayout.addWidget(self.velocityZLabel, row, col + 3)
        row += 1
        dataLayout.addWidget(QLabel("Air Supply"), row, col)
        dataLayout.addWidget(QLabel("Commanded"), row, col + 1)
        dataLayout.addWidget(QLabel("Valve State"), row, col + 2)
        row += 1
        dataLayout.addWidget(self.airCommandLabel, row, col + 1)
        dataLayout.addWidget(self.airValveLabel, row, col + 2)
        row += 1
        dataLayout.addWidget(QLabel("M1M3"), row, col + 1)
        dataLayout.addWidget(QLabel("TMA"), row, col + 2)
        row += 1
        dataLayout.addWidget(QLabel("Azimuth (deg)"), row, col)
        dataLayout.addWidget(QLabel("-"), row, col + 1)
        dataLayout.addWidget(self.tmaAzimuthLabel, row, col + 2)
        dataLayout.addWidget(QLabel("<b>CsC</b>"), row, col + 4)
        dataLayout.addWidget(QLabel("<b>SAL</b>"), row, col + 5)
        dataLayout.addWidget(QLabel("<b>XML</b>"), row, col + 6)
        dataLayout.addWidget(QLabel("<b>OSPL</b>"), row, col + 7)
        row += 1
        dataLayout.addWidget(QLabel("Elevation (deg)"), row, col)
        dataLayout.addWidget(self.inclinometerLabel, row, col + 1)
        dataLayout.addWidget(self.tmaElevationLabel, row, col + 2)
        dataLayout.addWidget(QLabel("<b>Version</b>"), row, col + 3)
        dataLayout.addWidget(self.cscVersion, row, col + 4)
        dataLayout.addWidget(self.salVersion, row, col + 5)
        dataLayout.addWidget(self.xmlVersion, row, col + 6)
        dataLayout.addWidget(self.osplVersion, row, col + 7)

        m1m3.accelerometerWarning.connect(self.accelerometerWarning)
        m1m3.airSupplyWarning.connect(self.airSupplyWarning)
        m1m3.appliedForces.connect(self.appliedForces)
        m1m3.cellLightWarning.connect(self.cellLightWarning)
        m1m3.detailedState.connect(self.detailedState)
        m1m3.displacementSensorWarning.connect(self.displacementSensorWarning)
        m1m3.errorCode.connect(self.errorCode)
        m1m3.gyroWarning.connect(self.gyroWarning)
        m1m3.hardpointActuatorWarning.connect(self.hardpointActuatorWarning)
        m1m3.hardpointMonitorWarning.connect(self.hardpointMonitorWarning)
        m1m3.heartbeat.connect(self.heartbeatLabel.heartbeat)
        m1m3.inclinometerSensorWarning.connect(self.inclinometerSensorWarning)
        m1m3.interlockWarning.connect(self.interlockWarning)
        m1m3.powerWarning.connect(self.powerWarning)

        m1m3.accelerometerData.connect(self.accelerometerData)
        m1m3.forceActuatorData.connect(self.forceActuatorData)
        m1m3.gyroData.connect(self.gyroData)
        m1m3.hardpointActuatorData.connect(self.hardpointActuatorData)
        m1m3.imsData.connect(self.imsData)
        m1m3.inclinometerData.connect(self.inclinometerData)
        m1m3.softwareVersions.connect(self.softwareVersions)

        mtmount.azimuth.connect(self.azimuth)
        mtmount.elevation.connect(self.elevation)
Beispiel #24
0
class PIDPageWidget(QWidget):
    def __init__(self, m1m3):
        super().__init__()

        self.layout = QVBoxLayout()
        self.dataLayout = QGridLayout()
        self.commandLayout = QVBoxLayout()
        self.plotLayout = QVBoxLayout()
        self.layout.addLayout(self.commandLayout)
        self.layout.addLayout(self.dataLayout)
        self.layout.addLayout(self.plotLayout)
        self.setLayout(self.layout)

        self.fxSetpointLabel = QLabel("UNKNOWN")
        self.fxMeasurementLabel = QLabel("UNKNOWN")
        self.fxErrorLabel = QLabel("UNKNOWN")
        self.fxErrorT1Label = QLabel("UNKNOWN")
        self.fxErrorT2Label = QLabel("UNKNOWN")
        self.fxControlLabel = QLabel("UNKNOWN")
        self.fxControlT1Label = QLabel("UNKNOWN")
        self.fxControlT2Label = QLabel("UNKNOWN")
        self.fySetpointLabel = QLabel("UNKNOWN")
        self.fyMeasurementLabel = QLabel("UNKNOWN")
        self.fyErrorLabel = QLabel("UNKNOWN")
        self.fyErrorT1Label = QLabel("UNKNOWN")
        self.fyErrorT2Label = QLabel("UNKNOWN")
        self.fyControlLabel = QLabel("UNKNOWN")
        self.fyControlT1Label = QLabel("UNKNOWN")
        self.fyControlT2Label = QLabel("UNKNOWN")
        self.fzSetpointLabel = QLabel("UNKNOWN")
        self.fzMeasurementLabel = QLabel("UNKNOWN")
        self.fzErrorLabel = QLabel("UNKNOWN")
        self.fzErrorT1Label = QLabel("UNKNOWN")
        self.fzErrorT2Label = QLabel("UNKNOWN")
        self.fzControlLabel = QLabel("UNKNOWN")
        self.fzControlT1Label = QLabel("UNKNOWN")
        self.fzControlT2Label = QLabel("UNKNOWN")
        self.mxSetpointLabel = QLabel("UNKNOWN")
        self.mxMeasurementLabel = QLabel("UNKNOWN")
        self.mxErrorLabel = QLabel("UNKNOWN")
        self.mxErrorT1Label = QLabel("UNKNOWN")
        self.mxErrorT2Label = QLabel("UNKNOWN")
        self.mxControlLabel = QLabel("UNKNOWN")
        self.mxControlT1Label = QLabel("UNKNOWN")
        self.mxControlT2Label = QLabel("UNKNOWN")
        self.mySetpointLabel = QLabel("UNKNOWN")
        self.myMeasurementLabel = QLabel("UNKNOWN")
        self.myErrorLabel = QLabel("UNKNOWN")
        self.myErrorT1Label = QLabel("UNKNOWN")
        self.myErrorT2Label = QLabel("UNKNOWN")
        self.myControlLabel = QLabel("UNKNOWN")
        self.myControlT1Label = QLabel("UNKNOWN")
        self.myControlT2Label = QLabel("UNKNOWN")
        self.mzSetpointLabel = QLabel("UNKNOWN")
        self.mzMeasurementLabel = QLabel("UNKNOWN")
        self.mzErrorLabel = QLabel("UNKNOWN")
        self.mzErrorT1Label = QLabel("UNKNOWN")
        self.mzErrorT2Label = QLabel("UNKNOWN")
        self.mzControlLabel = QLabel("UNKNOWN")
        self.mzControlT1Label = QLabel("UNKNOWN")
        self.mzControlT2Label = QLabel("UNKNOWN")
        self.fxTimestepLabel = QLabel("UNKNOWN")
        self.fxPLabel = QLabel("UNKNOWN")
        self.fxILabel = QLabel("UNKNOWN")
        self.fxDLabel = QLabel("UNKNOWN")
        self.fxNLabel = QLabel("UNKNOWN")
        self.fxCalculatedALabel = QLabel("UNKNOWN")
        self.fxCalculatedBLabel = QLabel("UNKNOWN")
        self.fxCalculatedCLabel = QLabel("UNKNOWN")
        self.fxCalculatedDLabel = QLabel("UNKNOWN")
        self.fxCalculatedELabel = QLabel("UNKNOWN")
        self.fyTimestepLabel = QLabel("UNKNOWN")
        self.fyPLabel = QLabel("UNKNOWN")
        self.fyILabel = QLabel("UNKNOWN")
        self.fyDLabel = QLabel("UNKNOWN")
        self.fyNLabel = QLabel("UNKNOWN")
        self.fyCalculatedALabel = QLabel("UNKNOWN")
        self.fyCalculatedBLabel = QLabel("UNKNOWN")
        self.fyCalculatedCLabel = QLabel("UNKNOWN")
        self.fyCalculatedDLabel = QLabel("UNKNOWN")
        self.fyCalculatedELabel = QLabel("UNKNOWN")
        self.fzTimestepLabel = QLabel("UNKNOWN")
        self.fzPLabel = QLabel("UNKNOWN")
        self.fzILabel = QLabel("UNKNOWN")
        self.fzDLabel = QLabel("UNKNOWN")
        self.fzNLabel = QLabel("UNKNOWN")
        self.fzCalculatedALabel = QLabel("UNKNOWN")
        self.fzCalculatedBLabel = QLabel("UNKNOWN")
        self.fzCalculatedCLabel = QLabel("UNKNOWN")
        self.fzCalculatedDLabel = QLabel("UNKNOWN")
        self.fzCalculatedELabel = QLabel("UNKNOWN")
        self.mxTimestepLabel = QLabel("UNKNOWN")
        self.mxPLabel = QLabel("UNKNOWN")
        self.mxILabel = QLabel("UNKNOWN")
        self.mxDLabel = QLabel("UNKNOWN")
        self.mxNLabel = QLabel("UNKNOWN")
        self.mxCalculatedALabel = QLabel("UNKNOWN")
        self.mxCalculatedBLabel = QLabel("UNKNOWN")
        self.mxCalculatedCLabel = QLabel("UNKNOWN")
        self.mxCalculatedDLabel = QLabel("UNKNOWN")
        self.mxCalculatedELabel = QLabel("UNKNOWN")
        self.myTimestepLabel = QLabel("UNKNOWN")
        self.myPLabel = QLabel("UNKNOWN")
        self.myILabel = QLabel("UNKNOWN")
        self.myDLabel = QLabel("UNKNOWN")
        self.myNLabel = QLabel("UNKNOWN")
        self.myCalculatedALabel = QLabel("UNKNOWN")
        self.myCalculatedBLabel = QLabel("UNKNOWN")
        self.myCalculatedCLabel = QLabel("UNKNOWN")
        self.myCalculatedDLabel = QLabel("UNKNOWN")
        self.myCalculatedELabel = QLabel("UNKNOWN")
        self.mzTimestepLabel = QLabel("UNKNOWN")
        self.mzPLabel = QLabel("UNKNOWN")
        self.mzILabel = QLabel("UNKNOWN")
        self.mzDLabel = QLabel("UNKNOWN")
        self.mzNLabel = QLabel("UNKNOWN")
        self.mzCalculatedALabel = QLabel("UNKNOWN")
        self.mzCalculatedBLabel = QLabel("UNKNOWN")
        self.mzCalculatedCLabel = QLabel("UNKNOWN")
        self.mzCalculatedDLabel = QLabel("UNKNOWN")
        self.mzCalculatedELabel = QLabel("UNKNOWN")

        self.chart = TimeChart(
            {"Command (N or N/m)": ["Fx", "Fy", "Fz", "Mx", "My", "Mz"]}
        )
        self.chartView = TimeChartView(self.chart)

        row = 0
        col = 0
        self.dataLayout.addWidget(QLabel("Setpoint"), row, col + 1)
        self.dataLayout.addWidget(QLabel("Measurement"), row, col + 2)
        self.dataLayout.addWidget(QLabel("Error"), row, col + 3)
        self.dataLayout.addWidget(QLabel("ErrorT1"), row, col + 4)
        self.dataLayout.addWidget(QLabel("ErrorT2"), row, col + 5)
        self.dataLayout.addWidget(QLabel("Control"), row, col + 6)
        self.dataLayout.addWidget(QLabel("ControlT1"), row, col + 7)
        self.dataLayout.addWidget(QLabel("ControlT2"), row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fx"), row, col)
        self.dataLayout.addWidget(self.fxSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fxMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fxErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fxErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fxErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fxControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fxControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fxControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fy"), row, col)
        self.dataLayout.addWidget(self.fySetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fyMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fyErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fyErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fyErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fyControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fyControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fyControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fz"), row, col)
        self.dataLayout.addWidget(self.fzSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fzMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fzErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fzErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fzErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fzControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fzControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fzControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Mx"), row, col)
        self.dataLayout.addWidget(self.mxSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.mxMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.mxErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.mxErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.mxErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.mxControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.mxControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.mxControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("My"), row, col)
        self.dataLayout.addWidget(self.mySetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.myMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.myErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.myErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.myErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.myControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.myControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.myControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Mz"), row, col)
        self.dataLayout.addWidget(self.mzSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.mzMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.mzErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.mzErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.mzErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.mzControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.mzControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.mzControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel(" "), row, col)
        row += 1
        self.dataLayout.addWidget(QLabel("Timestep"), row, col + 1)
        self.dataLayout.addWidget(QLabel("P"), row, col + 2)
        self.dataLayout.addWidget(QLabel("I"), row, col + 3)
        self.dataLayout.addWidget(QLabel("D"), row, col + 4)
        self.dataLayout.addWidget(QLabel("N"), row, col + 5)
        self.dataLayout.addWidget(QLabel("CalculatedA"), row, col + 6)
        self.dataLayout.addWidget(QLabel("CalculatedB"), row, col + 7)
        self.dataLayout.addWidget(QLabel("CalculatedC"), row, col + 8)
        self.dataLayout.addWidget(QLabel("CalculatedD"), row, col + 9)
        self.dataLayout.addWidget(QLabel("CalculatedE"), row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fx"), row, col)
        self.dataLayout.addWidget(self.fxTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fxPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fxILabel, row, col + 3)
        self.dataLayout.addWidget(self.fxDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fxNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fxCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fxCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fxCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fxCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fxCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fy"), row, col)
        self.dataLayout.addWidget(self.fyTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fyPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fyILabel, row, col + 3)
        self.dataLayout.addWidget(self.fyDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fyNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fyCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fyCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fyCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fyCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fyCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fz"), row, col)
        self.dataLayout.addWidget(self.fzTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fzPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fzILabel, row, col + 3)
        self.dataLayout.addWidget(self.fzDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fzNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fzCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fzCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fzCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fzCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fzCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Mx"), row, col)
        self.dataLayout.addWidget(self.mxTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.mxPLabel, row, col + 2)
        self.dataLayout.addWidget(self.mxILabel, row, col + 3)
        self.dataLayout.addWidget(self.mxDLabel, row, col + 4)
        self.dataLayout.addWidget(self.mxNLabel, row, col + 5)
        self.dataLayout.addWidget(self.mxCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.mxCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.mxCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.mxCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.mxCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("My"), row, col)
        self.dataLayout.addWidget(self.myTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.myPLabel, row, col + 2)
        self.dataLayout.addWidget(self.myILabel, row, col + 3)
        self.dataLayout.addWidget(self.myDLabel, row, col + 4)
        self.dataLayout.addWidget(self.myNLabel, row, col + 5)
        self.dataLayout.addWidget(self.myCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.myCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.myCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.myCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.myCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Mz"), row, col)
        self.dataLayout.addWidget(self.mzTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.mzPLabel, row, col + 2)
        self.dataLayout.addWidget(self.mzILabel, row, col + 3)
        self.dataLayout.addWidget(self.mzDLabel, row, col + 4)
        self.dataLayout.addWidget(self.mzNLabel, row, col + 5)
        self.dataLayout.addWidget(self.mzCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.mzCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.mzCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.mzCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.mzCalculatedELabel, row, col + 10)

        self.plotLayout.addWidget(self.chartView)

        m1m3.pidInfo.connect(self.pidInfo)
        m1m3.pidData.connect(self.pidData)

    @Slot(map)
    def pidInfo(self, data):
        self.fxTimestepLabel.setText("%0.3f" % data.timestep[0])
        self.fxPLabel.setText("%0.3f" % data.p[0])
        self.fxILabel.setText("%0.3f" % data.i[0])
        self.fxDLabel.setText("%0.3f" % data.d[0])
        self.fxNLabel.setText("%0.3f" % data.n[0])
        self.fxCalculatedALabel.setText("%0.3f" % data.calculatedA[0])
        self.fxCalculatedBLabel.setText("%0.3f" % data.calculatedB[0])
        self.fxCalculatedCLabel.setText("%0.3f" % data.calculatedC[0])
        self.fxCalculatedDLabel.setText("%0.3f" % data.calculatedD[0])
        self.fxCalculatedELabel.setText("%0.3f" % data.calculatedE[0])

        self.fyTimestepLabel.setText("%0.3f" % data.timestep[1])
        self.fyPLabel.setText("%0.3f" % data.p[1])
        self.fyILabel.setText("%0.3f" % data.i[1])
        self.fyDLabel.setText("%0.3f" % data.d[1])
        self.fyNLabel.setText("%0.3f" % data.n[1])
        self.fyCalculatedALabel.setText("%0.3f" % data.calculatedA[1])
        self.fyCalculatedBLabel.setText("%0.3f" % data.calculatedB[1])
        self.fyCalculatedCLabel.setText("%0.3f" % data.calculatedC[1])
        self.fyCalculatedDLabel.setText("%0.3f" % data.calculatedD[1])
        self.fyCalculatedELabel.setText("%0.3f" % data.calculatedE[1])

        self.fzTimestepLabel.setText("%0.3f" % data.timestep[2])
        self.fzPLabel.setText("%0.3f" % data.p[2])
        self.fzILabel.setText("%0.3f" % data.i[2])
        self.fzDLabel.setText("%0.3f" % data.d[2])
        self.fzNLabel.setText("%0.3f" % data.n[2])
        self.fzCalculatedALabel.setText("%0.3f" % data.calculatedA[2])
        self.fzCalculatedBLabel.setText("%0.3f" % data.calculatedB[2])
        self.fzCalculatedCLabel.setText("%0.3f" % data.calculatedC[2])
        self.fzCalculatedDLabel.setText("%0.3f" % data.calculatedD[2])
        self.fzCalculatedELabel.setText("%0.3f" % data.calculatedE[2])

        self.mxTimestepLabel.setText("%0.3f" % data.timestep[3])
        self.mxPLabel.setText("%0.3f" % data.p[3])
        self.mxILabel.setText("%0.3f" % data.i[3])
        self.mxDLabel.setText("%0.3f" % data.d[3])
        self.mxNLabel.setText("%0.3f" % data.n[3])
        self.mxCalculatedALabel.setText("%0.3f" % data.calculatedA[3])
        self.mxCalculatedBLabel.setText("%0.3f" % data.calculatedB[3])
        self.mxCalculatedCLabel.setText("%0.3f" % data.calculatedC[3])
        self.mxCalculatedDLabel.setText("%0.3f" % data.calculatedD[3])
        self.mxCalculatedELabel.setText("%0.3f" % data.calculatedE[3])

        self.myTimestepLabel.setText("%0.3f" % data.timestep[4])
        self.myPLabel.setText("%0.3f" % data.p[4])
        self.myILabel.setText("%0.3f" % data.i[4])
        self.myDLabel.setText("%0.3f" % data.d[4])
        self.myNLabel.setText("%0.3f" % data.n[4])
        self.myCalculatedALabel.setText("%0.3f" % data.calculatedA[4])
        self.myCalculatedBLabel.setText("%0.3f" % data.calculatedB[4])
        self.myCalculatedCLabel.setText("%0.3f" % data.calculatedC[4])
        self.myCalculatedDLabel.setText("%0.3f" % data.calculatedD[4])
        self.myCalculatedELabel.setText("%0.3f" % data.calculatedE[4])

        self.mzTimestepLabel.setText("%0.3f" % data.timestep[5])
        self.mzPLabel.setText("%0.3f" % data.p[5])
        self.mzILabel.setText("%0.3f" % data.i[5])
        self.mzDLabel.setText("%0.3f" % data.d[5])
        self.mzNLabel.setText("%0.3f" % data.n[5])
        self.mzCalculatedALabel.setText("%0.3f" % data.calculatedA[5])
        self.mzCalculatedBLabel.setText("%0.3f" % data.calculatedB[5])
        self.mzCalculatedCLabel.setText("%0.3f" % data.calculatedC[5])
        self.mzCalculatedDLabel.setText("%0.3f" % data.calculatedD[5])
        self.mzCalculatedELabel.setText("%0.3f" % data.calculatedE[5])

    @Slot(map)
    def pidData(self, data):
        self.fxSetpointLabel.setText("%0.3f" % data.setpoint[0])
        self.fxMeasurementLabel.setText("%0.3f" % data.measuredPID[0])
        self.fxErrorLabel.setText("%0.3f" % data.error[0])
        self.fxErrorT1Label.setText("%0.3f" % data.errorT1[0])
        self.fxErrorT2Label.setText("%0.3f" % data.errorT2[0])
        self.fxControlLabel.setText("%0.3f" % data.control[0])
        self.fxControlT1Label.setText("%0.3f" % data.controlT1[0])
        self.fxControlT2Label.setText("%0.3f" % data.controlT2[0])
        self.fySetpointLabel.setText("%0.3f" % data.setpoint[1])
        self.fyMeasurementLabel.setText("%0.3f" % data.measuredPID[1])
        self.fyErrorLabel.setText("%0.3f" % data.error[1])
        self.fyErrorT1Label.setText("%0.3f" % data.errorT1[1])
        self.fyErrorT2Label.setText("%0.3f" % data.errorT2[1])
        self.fyControlLabel.setText("%0.3f" % data.control[1])
        self.fyControlT1Label.setText("%0.3f" % data.controlT1[1])
        self.fyControlT2Label.setText("%0.3f" % data.controlT2[1])
        self.fzSetpointLabel.setText("%0.3f" % data.setpoint[2])
        self.fzMeasurementLabel.setText("%0.3f" % data.measuredPID[2])
        self.fzErrorLabel.setText("%0.3f" % data.error[2])
        self.fzErrorT1Label.setText("%0.3f" % data.errorT1[2])
        self.fzErrorT2Label.setText("%0.3f" % data.errorT2[2])
        self.fzControlLabel.setText("%0.3f" % data.control[2])
        self.fzControlT1Label.setText("%0.3f" % data.controlT1[2])
        self.fzControlT2Label.setText("%0.3f" % data.controlT2[2])
        self.mxSetpointLabel.setText("%0.3f" % data.setpoint[3])
        self.mxMeasurementLabel.setText("%0.3f" % data.measuredPID[3])
        self.mxErrorLabel.setText("%0.3f" % data.error[3])
        self.mxErrorT1Label.setText("%0.3f" % data.errorT1[3])
        self.mxErrorT2Label.setText("%0.3f" % data.errorT2[3])
        self.mxControlLabel.setText("%0.3f" % data.control[3])
        self.mxControlT1Label.setText("%0.3f" % data.controlT1[3])
        self.mxControlT2Label.setText("%0.3f" % data.controlT2[3])
        self.mySetpointLabel.setText("%0.3f" % data.setpoint[4])
        self.myMeasurementLabel.setText("%0.3f" % data.measuredPID[4])
        self.myErrorLabel.setText("%0.3f" % data.error[4])
        self.myErrorT1Label.setText("%0.3f" % data.errorT1[4])
        self.myErrorT2Label.setText("%0.3f" % data.errorT2[4])
        self.myControlLabel.setText("%0.3f" % data.control[4])
        self.myControlT1Label.setText("%0.3f" % data.controlT1[4])
        self.myControlT2Label.setText("%0.3f" % data.controlT2[4])
        self.mzSetpointLabel.setText("%0.3f" % data.setpoint[5])
        self.mzMeasurementLabel.setText("%0.3f" % data.measuredPID[5])
        self.mzErrorLabel.setText("%0.3f" % data.error[5])
        self.mzErrorT1Label.setText("%0.3f" % data.errorT1[5])
        self.mzErrorT2Label.setText("%0.3f" % data.errorT2[5])
        self.mzControlLabel.setText("%0.3f" % data.control[5])
        self.mzControlT1Label.setText("%0.3f" % data.controlT1[5])
        self.mzControlT2Label.setText("%0.3f" % data.controlT2[5])

        self.chart.append(data.timestamp, [data.control[x] for x in range(6)])
class MietverhaeltnisView(QWidget, ModifyInfo):
    save = Signal()
    dataChanged = Signal()
    nextMv = Signal()
    prevMv = Signal()

    def __init__(self,
                 mietverhaeltnis: XMietverhaeltnis = None,
                 withSaveButton: bool = False,
                 enableBrowsing=False,
                 parent=None):
        QWidget.__init__(self, parent)
        ModifyInfo.__init__(self)
        self._mietverhaeltnis: XMietverhaeltnis = None
        self._withSaveButton = withSaveButton
        self._enableBrowsing = enableBrowsing  # ob die Browse-Buttons angezeigt werden
        self._layout = QGridLayout()
        self._btnSave = QPushButton()
        self._btnVor = QPushButton()
        self._btnRueck = QPushButton()
        self._sdBeginnMietverh = SmartDateEdit()
        self._sdEndeMietverh = SmartDateEdit()
        self._edMieterName_1 = BaseEdit()
        self._edMieterVorname_1 = BaseEdit()
        self._edMieterName_2 = BaseEdit()
        self._edMieterVorname_2 = BaseEdit()
        self._edMieterTelefon = BaseEdit()
        self._edMieterMobil = BaseEdit()
        self._edMieterMailto = BaseEdit()
        self._edAnzPers = IntEdit()
        self._edNettomiete = FloatEdit()
        self._edNkv = FloatEdit()
        self._edKaution = IntEdit()
        self._sdKautionBezahltAm = SmartDateEdit()
        self._txtBemerkung1 = MultiLineEdit()
        self._txtBemerkung2 = MultiLineEdit()

        self._createGui()
        if mietverhaeltnis:
            self.setMietverhaeltnisData(mietverhaeltnis)
        #self.connectWidgetsToChangeSlot( self.onChange )
        self.connectWidgetsToChangeSlot(self.onChange, self.onResetChangeFlag)

    def onChange(self, newcontent: str = None):
        if not self._btnSave.isEnabled():
            self.setSaveButtonEnabled()
        self.dataChanged.emit()

    def onResetChangeFlag(self):
        self.setSaveButtonEnabled(False)

    def setSaveButtonEnabled(self, enabled: bool = True):
        self._btnSave.setEnabled(enabled)

    def _createGui(self):
        hbox = QHBoxLayout()
        if self._withSaveButton:
            self._createSaveButton(hbox)
        if self._enableBrowsing:
            self._createVorRueckButtons(hbox)
        self._layout.addLayout(hbox, 0, 0, alignment=Qt.AlignLeft)
        self._addHorizontalLine(1)
        self._createFelder(2)
        self.setLayout(self._layout)

    def _createSaveButton(self, hbox):
        btn = self._btnSave
        btn.clicked.connect(self.save.emit)
        btn.setFlat(True)
        btn.setEnabled(False)
        btn.setToolTip("Änderungen am Mietverhältnis speichern")
        icon = ImageFactory.inst().getSaveIcon()
        #icon = QIcon( "./images/save_30.png" )
        btn.setIcon(icon)
        size = QSize(32, 32)
        btn.setFixedSize(size)
        iconsize = QSize(30, 30)
        btn.setIconSize(iconsize)
        hbox.addWidget(btn)

    def _createVorRueckButtons(self, hbox):
        self._prepareButton(self._btnRueck,
                            ImageFactory.inst().getPrevIcon(),
                            "Zum vorigen Mietverhältnis blättern", self.prevMv)
        hbox.addWidget(self._btnRueck)
        self._prepareButton(self._btnVor,
                            ImageFactory.inst().getNextIcon(),
                            "Zum nächsten Mietverhältnis blättern",
                            self.nextMv)
        hbox.addWidget(self._btnVor)

    def _prepareButton(self, btn: QPushButton, icon: QIcon, tooltip: str,
                       signal: Signal):
        btn.setFlat(True)
        btn.setEnabled(True)
        btn.setToolTip(tooltip)
        btn.setIcon(icon)
        size = QSize(32, 32)
        btn.setFixedSize(size)
        iconsize = QSize(30, 30)
        btn.setIconSize(iconsize)
        btn.clicked.connect(signal.emit)

    def _addHorizontalLine(self, r: int):
        hline = HLine()
        self._layout.addWidget(hline, r, 0, 1, 2)
        return r + 1

    def _createFelder(self, r):
        c = 0
        l = self._layout

        lbl = QLabel("Beginn: ")
        l.addWidget(lbl, r, c)
        c += 1
        self._sdBeginnMietverh.setMaximumWidth(100)
        l.addWidget(self._sdBeginnMietverh, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Ende: "), r, c)
        c += 1
        self._sdEndeMietverh.setMaximumWidth(100)
        l.addWidget(self._sdEndeMietverh, r, c)

        c = 0
        r += 1
        lbl = BaseLabel("Name / Vorname 1. Mieter: ")
        l.addWidget(lbl, r, c)
        c += 1
        hbox = QHBoxLayout()
        hbox.addWidget(self._edMieterName_1)
        hbox.addWidget(self._edMieterVorname_1)
        l.addLayout(hbox, r, c)

        c = 0
        r += 1
        lbl = BaseLabel("Name / Vorname 2. Mieter: ")
        l.addWidget(lbl, r, c)
        c += 1
        hbox = QHBoxLayout()
        hbox.addWidget(self._edMieterName_2)
        hbox.addWidget(self._edMieterVorname_2)
        l.addLayout(hbox, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Telefon: "), r, c)
        c += 1
        l.addWidget(self._edMieterTelefon, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Mobil: "), r, c)
        c += 1
        l.addWidget(self._edMieterMobil, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Mailadresse: "), r, c)
        c += 1
        l.addWidget(self._edMieterMailto, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Anzahl Personen i.d. Whg: "), r, c)
        c += 1
        self._edAnzPers.setMaximumWidth(20)
        l.addWidget(self._edAnzPers, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Nettomiete / NKV: "), r, c)

        c += 1
        self._edNettomiete.setMaximumWidth(100)
        #self._edNettomiete.setEnabled( False )
        self._edNkv.setMaximumWidth(100)
        #self._edNkv.setEnabled( False )
        hbox = QHBoxLayout()
        hbox.addWidget(self._edNettomiete)
        hbox.addWidget(self._edNkv)
        hbox.addWidget(
            BaseLabel(
                "  Änderungen der Miete und NKV über Dialog 'Sollmiete'"))
        l.addLayout(hbox, r, c, alignment=Qt.AlignLeft)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Kaution: "), r, c)
        c += 1
        self._edKaution.setMaximumWidth(100)
        l.addWidget(self._edKaution, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel("Kaution bezahlt am: "), r, c)
        c += 1
        self._sdKautionBezahltAm.setMaximumWidth(100)
        l.addWidget(self._sdKautionBezahltAm, r, c)

        c = 0
        r += 1
        l.addWidget(BaseLabel(""), r, c)

        r += 1
        l.addWidget(BaseLabel("Bemerkungen: "), r, c)
        c += 1
        hbox = QHBoxLayout()
        hbox.addWidget(self._txtBemerkung1)
        hbox.addWidget(self._txtBemerkung2)
        l.addLayout(hbox, r, c)

        # cols = self._layout.columnCount()
        # print( cols, " columns" )

    def setNettoUndNkvEnabled(self, enabled: bool = True):
        self._edNettomiete.setEnabled(enabled)
        self._edNkv.setEnabled(enabled)

    def _guiToData(self, x: XMietverhaeltnis):
        """
        Überträgt die Änderungen, die der User im GUI gemacht hat, in das
        übergebene XMietverhaeltnis-Objekt
        :param x: XMietverhaeltnis-Objekt, in das die geänderten Daten übertragen werden
        :return:
        """
        x.von = self._sdBeginnMietverh.getDate()
        x.bis = self._sdEndeMietverh.getDate()
        x.name = self._edMieterName_1.text()
        x.vorname = self._edMieterVorname_1.text()
        x.name2 = self._edMieterName_2.text()
        x.vorname2 = self._edMieterVorname_2.text()
        x.telefon = self._edMieterTelefon.text()
        x.mobil = self._edMieterMobil.text()
        x.mailto = self._edMieterMailto.text()
        x.anzahl_pers = self._edAnzPers.getIntValue()
        x.nettomiete = self._edNettomiete.getFloatValue()
        x.nkv = self._edNkv.getFloatValue()
        x.kaution = self._edKaution.getIntValue()
        x.kaution_bezahlt_am = self._sdKautionBezahltAm.getDate()
        x.bemerkung1 = self._txtBemerkung1.toPlainText()
        x.bemerkung2 = self._txtBemerkung2.toPlainText()

    def getMietverhaeltnisCopyWithChanges(self) -> XMietverhaeltnis:
        """
        gibt eine Kopie der Mietverhaeltnis-Schnittstellendaten mit Änderungen zurück.
        Diese Kopie kann für Validierungszwecke verwendet werden.
        :return: Kopie von XMietverhaeltnis
        """
        mvcopy = copy.copy(self._mietverhaeltnis)
        self._guiToData(mvcopy)
        return mvcopy

    def applyChanges(self):
        """
        überträgt die Änderungen, die der User im GUI gemacht hat, in das
        originale XMietverhaeltnis-Objekt.
        """
        if self.isChanged():
            self._guiToData(self._mietverhaeltnis)

    def setMietverhaeltnisData(self, mv: XMietverhaeltnis):
        """
        Daten, die im GUI angezeigt und geändert werden können.
        :param mv:
        :return:
        """
        self._mietverhaeltnis = mv
        if mv.von:
            self._sdBeginnMietverh.setDateFromIsoString(mv.von)
        if mv.bis:
            self._sdEndeMietverh.setDateFromIsoString(mv.bis)
        self._edMieterName_1.setText(mv.name)
        self._edMieterVorname_1.setText(mv.vorname)
        self._edMieterName_2.setText(mv.name2)
        self._edMieterVorname_2.setText(mv.vorname2)
        self._edMieterTelefon.setText(mv.telefon)
        self._edMieterMobil.setText(mv.mobil)
        self._edMieterMailto.setText(mv.mailto)
        self._edAnzPers.setIntValue(mv.anzahl_pers)
        self._edNettomiete.setFloatValue(mv.nettomiete)
        self._edNkv.setFloatValue(mv.nkv)
        if mv.kaution:
            self._edKaution.setIntValue(mv.kaution)
        if mv.kaution_bezahlt_am:
            self._sdKautionBezahltAm.setDateFromIsoString(
                mv.kaution_bezahlt_am)
        self._txtBemerkung1.setText(mv.bemerkung1)
        self._txtBemerkung2.setText(mv.bemerkung2)
        self.resetChangeFlag()

    def clear(self):
        self._sdBeginnMietverh.clear()
        self._sdEndeMietverh.clear()
        self._edMieterName_1.clear()
        self._edMieterVorname_1.clear()
        self._edMieterName_2.clear()
        self._edMieterVorname_2.clear()
        self._edMieterTelefon.clear()
        self._edMieterMobil.clear()
        self._edMieterMailto.clear()
        self._edAnzPers.clear()
        self._edNettomiete.clear()
        self._edNkv.clear()
        self._edKaution.clear()
        self._sdKautionBezahltAm.clear()
        self._txtBemerkung1.clear()
        self._txtBemerkung2.clear()
    def _setup_ui(self):
        layout = QVBoxLayout(self)
        self.setLayout(layout)
        layout.setMargin(1)
        layout.setSpacing(1)

        s1_s2 = QWidget(self)
        s1_s2_layout = QHBoxLayout(s1_s2)
        s1_s2.setLayout(s1_s2_layout)
        s1_s2_layout.setMargin(1)
        s1_s2_layout.setSpacing(0)
        self._s1 = QRadioButton('S1', s1_s2)
        font = self._s1.font()
        font.setPointSize(7)
        font.setBold(True)
        self._s1.setFont(font)
        self._s1.setLayoutDirection(Qt.RightToLeft)
        self._s1.setChecked(True)
        self._s2 = QRadioButton('S2', s1_s2)
        self._s2.setFont(font)
        self._s2.toggled.connect(lambda s: self._send_mode(s))
        s1_s2_layout.addWidget(self._s1)
        s1_s2_layout.setAlignment(self._s1, Qt.AlignLeft)
        s1_s2_layout.addWidget(self._s2)
        s1_s2_layout.setAlignment(self._s2, Qt.AlignLeft)

        layout.addWidget(s1_s2)
        layout.setAlignment(s1_s2, Qt.AlignRight)

        write_w_box = QGroupBox('WRITE W', self)
        write_w_layout = QGridLayout(write_w_box)
        write_w_box.setLayout(write_w_layout)
        write_w_layout.setMargin(1)
        write_w_layout.setSpacing(1)

        row = 0
        col = 0
        for label, mode in WRITE_W_POSITIONS.items():
            pos = QRadioButton(label, write_w_box)
            pos.setFont(font)
            if label == 'ALL':
                pos.setChecked(True)
            pos.pressed.connect(lambda m=mode: self._update_mode(m))
            write_w_layout.addWidget(pos, row, col)
            col += 1
            if row == 0 or col >= 3:
                col = 0
                row += 1

        layout.addWidget(write_w_box)

        switch_frame = QFrame(self)
        switch_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)
        switch_layout = QGridLayout(switch_frame)
        switch_layout.setMargin(1)
        switch_layout.setSpacing(1)
        switch_frame.setLayout(switch_layout)

        layout.addWidget(switch_frame)

        row = self._add_switches(switch_frame, switch_layout, TIME_SWITCHES,
                                 self._time_switches, self._send_times, row)
        sep = QFrame(switch_frame)
        sep.setFrameStyle(QFrame.HLine | QFrame.Raised)
        switch_layout.addWidget(sep, row, 0, 1, 6)
        row += 1

        self._add_switches(switch_frame, switch_layout, PULSE_SWITCHES,
                           self._pulse_switches, self._send_pulses, row)
Beispiel #27
0
    def __init__(self):
        QWidget.__init__(self)
        """
        PROCESSING ATTRIBUTES
        """
        self.loop_simulation = False
        self.parameters_window = None

        self.term = Terminal()
        self.stl_model = None
        self.stl_model_pressure = None
        self.stl_model_display = None

        self.object_mass = DEFAULT_OBJECT_MASS
        self.dichotomy_precision = DEFAULT_DICHOTOMY_PRECISION
        self.fluid_density = DEFAULT_FLUID_DENSITY

        self.show_draught = DEFAULT_SHOW_DRAUGHT

        self.setWindowTitle("G5 SIMULATION OBJECT FLOTABILITY")
        self.setFixedSize(1280, 1024)

        self.main_layout = QVBoxLayout()
        self.main_layout.setMargin(0)
        self.main_layout.setSpacing(0)
        self.setLayout(self.main_layout)
        """
        TOPBAR WIDGETS
        """
        self.topbar_layout = QGridLayout()
        self.topbar_layout.setAlignment(Qt.AlignTop)
        self.topbar_layout.setSpacing(32)

        buttons_icons = [
            'stl_file', 'parameters', 'prepare_simulation', 'start_simulation',
            'loop_simulation', 'stop_simulation', 'generate_animation_gif'
        ]
        group_buttons_labels = ['LOAD 3D MODEL', 'PARAMETERS', 'SIMULATION']
        buttons_slots = [
            self.loadSTLModel, self.displayParametersWindow,
            self.prepareSimulation, self.startSimulation, self.loopSimulation,
            self.stopSimulation, self.generateAnimationsGIF
        ]
        buttons_tooltips = [
            'Load 3d model', 'Set parameters', 'Prepare the simulation',
            'Start the simulation', 'Loop the simulation',
            'Stop the simulation', 'Generate animations GIF'
        ]
        self.buttons = [QPushButton() for i in range(7)]
        for i, button in enumerate(self.buttons):
            button.setIcon(QIcon(ICONS_FOLDER + buttons_icons[i] +
                                 '_icon.png'))
            button.setIconSize(QSize(50, 50))
            button.setStyleSheet('border:none; margin-top : 24px;')
            button.clicked.connect(buttons_slots[i])
            button.setToolTip(buttons_tooltips[i])
            if i > 0: button.setDisabled(True)
            self.topbar_layout.addWidget(button, 0, i, 1, 1)

        for i, group_buttons_label in enumerate(group_buttons_labels):
            label = QLabel(group_buttons_label)
            label.setFixedHeight(32)
            label.setAlignment(Qt.AlignCenter)
            label.setStyleSheet(
                'border-top : 2px solid #dfdfdf; font-family: Calibri; font-size : 10pt; color: #2C3E50;'
            )
            self.topbar_layout.addWidget(label, 1, i, 1, 1 if i != 2 else 5)
        self.main_layout.addLayout(self.topbar_layout)
        """
        BODY_WIDGETS
        """
        self.body_layout = QGridLayout()
        self.body_layout.setSpacing(0)

        self.stl_model_graph = QLabel()
        self.stl_model_graph.setPixmap(QPixmap(DEFAULT_STL_MODEL_GRAPH_FOLDER))
        self.stl_model_graph.setFixedSize(640, 480)

        self.draught_graph = QLabel()
        self.draught_graph.setPixmap(QPixmap(DEFAULT_DRAUGHT_GRAPH_FOLDER))
        self.draught_graph.setFixedSize(640, 480)

        self.body_layout.addWidget(self.stl_model_graph, 0, 0, 1, 1)
        self.body_layout.addWidget(self.draught_graph, 0, 1, 1, 1)

        self.colored_parts_legend = QLabel()
        self.colored_parts_legend.setPixmap(
            QPixmap(LEGEND_FOLDER + 'colored_parts_legend.png'))
        self.colored_parts_legend.setStyleSheet(
            'padding : 0 0 13px 24px; background : #fff')
        self.body_layout.addWidget(self.colored_parts_legend, 1, 0, 1, 2)

        self.draught_legend = QLabel()
        self.draught_legend.setPixmap(
            QPixmap(LEGEND_FOLDER + 'draught_legend.png'))
        self.draught_legend.setStyleSheet(
            'padding : 0 0 13px 24px; background : #fff')
        self.draught_legend.hide()
        self.body_layout.addWidget(self.draught_legend, 2, 0, 1, 2)

        self.term.setFixedWidth(1280)
        self.main_layout.addLayout(self.body_layout)
        self.main_layout.addWidget(self.term)

        self.show()
Beispiel #28
0
    def _initControls(self):
        #
        # command line
        #
        self.frmCmdLine = QFormLayout()
        btnPasteClipboard = QPushButtonWidget(
            Text.txt0164,
            function=lambda: qtRunFunctionInThread(self.pasteClipboard),
            margins="  ",
            toolTip=Text.txt0165,
        )
        self.cmdLine = QLineEdit()
        self.cmdLine.setValidator(
            ValidateCommand(self, self.cliValidateSignal, log=self.log)
        )
        self.frmCmdLine.addRow(btnPasteClipboard, self.cmdLine)
        self.frmCmdLine.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        self.command = QWidget()
        self.command.setLayout(self.frmCmdLine)

        #
        # Button group definition
        #
        self.btnGroup = QGroupBox()
        self.btnGrid = QGridLayout()

        btnAddCommand = QPushButtonWidget(
            Text.txt0160,
            function=lambda: self.addCommand(JobStatus.Waiting),
            margins="  ",
            toolTip=Text.txt0161,
        )
        btnRename = QPushButtonWidget(
            Text.txt0182,
            function=self.parent.renameWidget.setAsCurrentTab,
            margins="  ",
            toolTip=Text.txt0183,
        )
        btnAddQueue = QPushButtonWidget(
            Text.txt0166,
            function=lambda: self.addCommand(JobStatus.AddToQueue),
            margins="  ",
            toolTip=Text.txt0167,
        )
        btnStartQueue = QPushButtonWidget(
            Text.txt0126,
            function=self.parent.jobsQueue.run,
            margins="  ",
            toolTip=Text.txt0169,
        )
        btnAnalysis = QPushButtonWidget(
            Text.txt0170,
            function=lambda: qtRunFunctionInThread(
                runAnalysis,
                command=self.cmdLine.text(),
                output=self.output,
                log=self.log,
            ),
            margins="  ",
            toolTip=Text.txt0171,
        )
        btnShowCommands = QPushButtonWidget(
            Text.txt0172,
            function=lambda: qtRunFunctionInThread(
                showCommands,
                output=self.output,
                command=self.cmdLine.text(),
                oCommand=self.oCommand,
                log=self.log,
            ),
            margins="  ",
            toolTip=Text.txt0173,
        )
        btnCheckFiles = QPushButtonWidget(
            Text.txt0174,
            function=lambda: qtRunFunctionInThread(
                checkFiles,
                output=self.output,
                command=self.cmdLine.text(),
                oCommand=self.oCommand,
                log=self.log,
            ),
            margins="  ",
            toolTip=Text.txt0175,
        )
        btnClear = QPushButtonWidget(
            Text.txt0176,
            function=self.clearOutputWindow,
            margins="  ",
            toolTip=Text.txt0177,
        )
        btnReset = QPushButtonWidget(
            Text.txt0178,
            function=self.reset,
            margins="  ",
            toolTip=Text.txt0179,
        )

        self.btnGrid.addWidget(btnAddCommand, 0, 0)
        self.btnGrid.addWidget(btnRename, 0, 1)
        self.btnGrid.addWidget(btnAddQueue, 1, 0)
        self.btnGrid.addWidget(btnStartQueue, 1, 1)
        self.btnGrid.addWidget(HorizontalLine(), 2, 0, 1, 2)
        self.btnGrid.addWidget(btnAnalysis, 3, 0)
        self.btnGrid.addWidget(btnShowCommands, 3, 1)
        self.btnGrid.addWidget(btnCheckFiles, 4, 0)
        self.btnGrid.addWidget(HorizontalLine(), 5, 0, 1, 2)
        self.btnGrid.addWidget(btnClear, 6, 0)
        self.btnGrid.addWidget(btnReset, 6, 1)
        self.btnGroup.setLayout(self.btnGrid)

        self.btnGroupBox = QGroupBox()
        self.btnHBox = QHBoxLayout()

        self.lblAlgorithm = QLabelWidget(
            Text.txt0094,
            textSuffix=":  ",
        )
        self.rbZero = QRadioButton("0", self)
        self.rbOne = QRadioButton("1", self)
        self.rbTwo = QRadioButton("2", self)

        btnDefaultAlgorithm = QPushButtonWidget(
            Text.txt0092,
            function=self.setDefaultAlgorithm,
            margins="  ",
            toolTip=Text.txt0093,
        )

        self.radioButtons = [self.rbZero, self.rbOne, self.rbTwo]

        self.btnHBox.addWidget(self.lblAlgorithm)
        self.btnHBox.addWidget(self.rbZero)
        self.btnHBox.addWidget(self.rbOne)
        self.btnHBox.addWidget(self.rbTwo)
        self.btnHBox.addWidget(btnDefaultAlgorithm)
        self.btnGroupBox.setLayout(self.btnHBox)
    def __init__(self, parent=None):
        super(AddDialogWidget, self).__init__(parent)

        nameLabel = QLabel("Name")
        addressLabel = QLabel("Address")
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel)

        self.nameText = QLineEdit()
        self.addressText = QTextEdit()

        grid = QGridLayout()
        grid.setColumnStretch(1, 2)
        grid.addWidget(nameLabel, 0, 0)
        grid.addWidget(self.nameText, 0, 1)
        grid.addWidget(addressLabel, 1, 0, Qt.AlignLeft | Qt.AlignTop)
        grid.addWidget(self.addressText, 1, 1, Qt.AlignLeft)

        layout = QVBoxLayout()
        layout.addLayout(grid)
        layout.addWidget(buttonBox)

        self.setLayout(layout)

        self.setWindowTitle("Add a Contact")

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
    def _layoutratingTab(self) -> None:
        layout = QGridLayout(self)

        nameLabel = QLabel('Movie Name')
        nameLineEdit = QLineEdit()
        nameLineEdit.setPlaceholderText('Enter name of the movie')
        layout.addWidget(nameLabel, 0, 0)
        layout.addWidget(nameLineEdit, 0, 1)

        ratingLabel = QLabel('Rating')
        actualRating = QLabel()
        layout.addWidget(ratingLabel, 1, 0)
        layout.addWidget(actualRating, 1, 1)

        positive_review = QLabel('Most Positive Review')
        most_positive_review = QLabel()
        layout.addWidget(positive_review, 2, 0)
        layout.addWidget(most_positive_review, 2, 1)

        negative_review = QLabel('Most Negative Review')
        most_negative_review = QLabel()
        layout.addWidget(negative_review, 3, 0)
        layout.addWidget(most_negative_review, 3, 1)

        # Button to open the camera and transfer control to another
        # program that will recognise the face
        ratingButton = QPushButton('Generate Rating')
        # Set a target method for `ratingButton` when clicked
        ratingButton.clicked.connect(
            partial(self._transferToGenerateRating, ratingButton, nameLineEdit,
                    actualRating, most_positive_review, most_negative_review))
        # Add `ratingButton` to the layout
        layout.addWidget(ratingButton, 5, 0, 2, 2)

        # Set this as the layout of the 'Recognition' tab
        self.ratingTab.setLayout(layout)
Beispiel #31
0
class MainWindow(QWidget):
    """
    Créer la fenêtre principale
    """
    def __init__(self):
        QWidget.__init__(self)
        """
        PROCESSING ATTRIBUTES
        """
        self.loop_simulation = False
        self.parameters_window = None

        self.term = Terminal()
        self.stl_model = None
        self.stl_model_pressure = None
        self.stl_model_display = None

        self.object_mass = DEFAULT_OBJECT_MASS
        self.dichotomy_precision = DEFAULT_DICHOTOMY_PRECISION
        self.fluid_density = DEFAULT_FLUID_DENSITY

        self.show_draught = DEFAULT_SHOW_DRAUGHT

        self.setWindowTitle("G5 SIMULATION OBJECT FLOTABILITY")
        self.setFixedSize(1280, 1024)

        self.main_layout = QVBoxLayout()
        self.main_layout.setMargin(0)
        self.main_layout.setSpacing(0)
        self.setLayout(self.main_layout)
        """
        TOPBAR WIDGETS
        """
        self.topbar_layout = QGridLayout()
        self.topbar_layout.setAlignment(Qt.AlignTop)
        self.topbar_layout.setSpacing(32)

        buttons_icons = [
            'stl_file', 'parameters', 'prepare_simulation', 'start_simulation',
            'loop_simulation', 'stop_simulation', 'generate_animation_gif'
        ]
        group_buttons_labels = ['LOAD 3D MODEL', 'PARAMETERS', 'SIMULATION']
        buttons_slots = [
            self.loadSTLModel, self.displayParametersWindow,
            self.prepareSimulation, self.startSimulation, self.loopSimulation,
            self.stopSimulation, self.generateAnimationsGIF
        ]
        buttons_tooltips = [
            'Load 3d model', 'Set parameters', 'Prepare the simulation',
            'Start the simulation', 'Loop the simulation',
            'Stop the simulation', 'Generate animations GIF'
        ]
        self.buttons = [QPushButton() for i in range(7)]
        for i, button in enumerate(self.buttons):
            button.setIcon(QIcon(ICONS_FOLDER + buttons_icons[i] +
                                 '_icon.png'))
            button.setIconSize(QSize(50, 50))
            button.setStyleSheet('border:none; margin-top : 24px;')
            button.clicked.connect(buttons_slots[i])
            button.setToolTip(buttons_tooltips[i])
            if i > 0: button.setDisabled(True)
            self.topbar_layout.addWidget(button, 0, i, 1, 1)

        for i, group_buttons_label in enumerate(group_buttons_labels):
            label = QLabel(group_buttons_label)
            label.setFixedHeight(32)
            label.setAlignment(Qt.AlignCenter)
            label.setStyleSheet(
                'border-top : 2px solid #dfdfdf; font-family: Calibri; font-size : 10pt; color: #2C3E50;'
            )
            self.topbar_layout.addWidget(label, 1, i, 1, 1 if i != 2 else 5)
        self.main_layout.addLayout(self.topbar_layout)
        """
        BODY_WIDGETS
        """
        self.body_layout = QGridLayout()
        self.body_layout.setSpacing(0)

        self.stl_model_graph = QLabel()
        self.stl_model_graph.setPixmap(QPixmap(DEFAULT_STL_MODEL_GRAPH_FOLDER))
        self.stl_model_graph.setFixedSize(640, 480)

        self.draught_graph = QLabel()
        self.draught_graph.setPixmap(QPixmap(DEFAULT_DRAUGHT_GRAPH_FOLDER))
        self.draught_graph.setFixedSize(640, 480)

        self.body_layout.addWidget(self.stl_model_graph, 0, 0, 1, 1)
        self.body_layout.addWidget(self.draught_graph, 0, 1, 1, 1)

        self.colored_parts_legend = QLabel()
        self.colored_parts_legend.setPixmap(
            QPixmap(LEGEND_FOLDER + 'colored_parts_legend.png'))
        self.colored_parts_legend.setStyleSheet(
            'padding : 0 0 13px 24px; background : #fff')
        self.body_layout.addWidget(self.colored_parts_legend, 1, 0, 1, 2)

        self.draught_legend = QLabel()
        self.draught_legend.setPixmap(
            QPixmap(LEGEND_FOLDER + 'draught_legend.png'))
        self.draught_legend.setStyleSheet(
            'padding : 0 0 13px 24px; background : #fff')
        self.draught_legend.hide()
        self.body_layout.addWidget(self.draught_legend, 2, 0, 1, 2)

        self.term.setFixedWidth(1280)
        self.main_layout.addLayout(self.body_layout)
        self.main_layout.addWidget(self.term)

        self.show()

    def updatePreview(self, show_draught=False):
        self.stl_model_display.emptyFolder(STL_MODEL_LOADED_VIEW_FOLDER)
        self.stl_model_display.saveSTLModelGraph(STL_MODEL_LOADED_VIEW_FOLDER,
                                                 'preview', show_draught)
        self.term.addProcessMessage(
            'Displaying of the updated preview of the STL model')
        self.stl_model_graph.setPixmap(
            QPixmap(STL_MODEL_LOADED_VIEW_FOLDER + 'preview.png'))

    def loadSTLModel(self):
        """
        Charger la maquette du fichier STL sélectionné et afficher un aperçu
        """
        ### BEFORE PROCESS
        for i in range(1, 7):
            self.buttons[i].setDisabled(True)
        ### START_PROCESS
        self.explorer = QFileDialog()
        self.explorer.setNameFilter("*.stl")
        if self.explorer.exec_():
            self.stl_model = STLModel(self.explorer.selectedFiles()[0],
                                      self.term)
            if self.stl_model.facets_number != 0:
                self.initial_bottom_ref = self.stl_model.bottom_ref
                self.stl_model_display = STLModelDisplay(
                    self.stl_model, self.term)

                self.updatePreview()

                ### END_PROCESS
                self.buttons[1].setDisabled(False)
                self.buttons[2].setDisabled(False)
                self.term.addSuccessMessage('STL model properly loaded')

    def displayParametersWindow(self):
        """
        Appeler la classe ParametersWindow pour afficher la fenêtre de paramètres
        """
        self.term.addInformativeMessage('Display the parameters window')
        self.parameters_window = ParametersWindow(self)

    def prepareSimulation(self):
        """
        Lancer l'algorithme de dichotomie et enregistrer les graphiques étape par étape
        """
        ### BEFORE_PROCESS
        self.buttons[2].setDisabled(True)

        # reset
        self.stl_model.translateZ(self.initial_bottom_ref -
                                  self.stl_model.bottom_ref)
        self.updatePreview(self.show_draught)

        if isinstance(self.parameters_window, ParametersWindow):
            self.parameters_window.close()
        for i in range(7):
            if i != 2: self.buttons[i].setDisabled(True)
        X, Y = [0], [
            -self.stl_model.bottom_ref if self.stl_model.bottom_ref < 0 else 0
        ]

        self.stl_model_display.emptyFolder(STL_MODEL_GRAPHS_FOLDER)
        self.stl_model_display.emptyFolder(DRAUGHT_GRAPHS_FOLDER)

        self.stl_model_display.saveSTLModelGraph(STL_MODEL_GRAPHS_FOLDER,
                                                 FRAMES_BASENAME + '0')
        self.stl_model_display.saveDraughGraph(FRAMES_BASENAME + '0', X, Y,
                                               self.dichotomy_precision)

        self.stl_model_pressure = STLModelPressure(self.stl_model, self.term)

        self.stl_model.setMass(self.object_mass)
        self.stl_model_pressure.setFluidDensity(self.fluid_density)
        ### START_PROCESS
        self.term.addProcessMessage('Launching the dichotomy algorithm')
        while self.stl_model_pressure.draught_range[
                1] - self.stl_model_pressure.draught_range[
                    0] > self.dichotomy_precision:
            Y.append(self.stl_model_pressure.dichotomy())
            X.append(self.stl_model_pressure.dichotomy_achieved)
            self.stl_model_display.saveSTLModelGraph(
                STL_MODEL_GRAPHS_FOLDER, FRAMES_BASENAME +
                str(self.stl_model_pressure.dichotomy_achieved),
                self.show_draught)
            self.stl_model_display.saveDraughGraph(
                FRAMES_BASENAME +
                str(self.stl_model_pressure.dichotomy_achieved), X, Y,
                self.dichotomy_precision)
        self.term.addSuccessMessage('Preparation of the simulation complete')
        ### END_PROCESS
        for i in range(7):
            if i != 5: self.buttons[i].setDisabled(False)
            if i == 2: self.buttons[i].setDisabled(True)

    def startSimulation(self):
        """
        Lancer l'animation des graphiques en asynchrone pour ne pas bloquer les clicked event
        """
        thread = threading.Thread(target=self._startSimulation)
        thread.start()

    def _startSimulation(self):
        """
        Recuperer et afficher avec une temporisation les images des graphiques afin de constituer l'animation
        """
        ### BEFORE PROCESS
        for i in range(7):
            if i != 5: self.buttons[i].setDisabled(True)

        self.term.addProcessMessage(
            'Recovery of all the images needed for the animation')
        stl_model_frames = os.listdir(STL_MODEL_GRAPHS_FOLDER)
        stl_model_frames = sorted(
            stl_model_frames,
            key=lambda frame: int(
                frame.replace(FRAMES_BASENAME, '').split('.')[0]))
        stl_draught_frames = os.listdir(DRAUGHT_GRAPHS_FOLDER)
        stl_draught_frames = sorted(
            stl_draught_frames,
            key=lambda frame: int(
                frame.replace(FRAMES_BASENAME, '').split('.')[0]))
        self.term.addSuccessMessage('All the images have been recovered')
        self.term.addInformativeMessage('Launching simulation animation')
        frames_number = len(stl_model_frames)
        if frames_number == len(stl_draught_frames):
            for i in range(frames_number):
                self.stl_model_graph.setPixmap(STL_MODEL_GRAPHS_FOLDER +
                                               stl_model_frames[i])
                self.draught_graph.setPixmap(DRAUGHT_GRAPHS_FOLDER +
                                             stl_draught_frames[i])
                time.sleep(.1)
            while self.loop_simulation:
                for i in range(frames_number):
                    self.stl_model_graph.setPixmap(STL_MODEL_GRAPHS_FOLDER +
                                                   stl_model_frames[i])
                    self.draught_graph.setPixmap(DRAUGHT_GRAPHS_FOLDER +
                                                 stl_draught_frames[i])
                    time.sleep(.1)
            self.term.addSuccessMessage(
                'Animation of the simulation correctly carried out')
            for i in range(7):
                if i in [0, 1, 3, 4, 6]: self.buttons[i].setDisabled(False)
        else:
            self.term.addErrorMessage(
                'An error occurred during frames synchronization')

    def loopSimulation(self):
        """
        Activer ou désactive la répétition infinie de l'animation
        """
        self.loop_simulation = not self.loop_simulation
        loop_button = self.buttons[4]
        stop_button = self.buttons[5]
        loop_icon = 'loop_simulation_icon.png'
        if self.loop_simulation:
            loop_icon = 'selected_' + loop_icon
            stop_button.setDisabled(False)
            self.term.addInformativeMessage(
                'The displayed simulation will now be looped')
        else:
            stop_button.setDisabled(True)
            self.term.addInformativeMessage(
                'The displayed simulation will now be played only once')
        loop_button.setIcon(QIcon(ICONS_FOLDER + loop_icon))

    def stopSimulation(self):
        """
        Interrompre la boucle pour arrêter l'animation
        """
        self.loop_simulation = False
        loop_button = self.buttons[4]
        stop_button = self.buttons[5]
        loop_button.setIcon(QIcon(ICONS_FOLDER + 'loop_simulation_icon.png'))
        stop_button.setDisabled(True)
        self.term.addInformativeMessage('Simulation properly stopped')

    def generateAnimationsGIF(self):
        """
        Générer et télécharger des GIF de la simulation produite
        """
        self.stl_model_display.generateGIFAnimations()
    def __init__(self, targetImage=None, axeSize=500, layer=None, parent=None):
        super().__init__(targetImage=targetImage, axeSize=axeSize, layer=layer, parent=parent)
        graphicsScene = self.scene()
        #########
        # L curve
        #########
        cubic = activeCubicSpline(axeSize)
        graphicsScene.addItem(cubic)
        graphicsScene.cubicR = cubic
        cubic.channel = channelValues.L
        # get histogram as a Qimage
        cubic.histImg = graphicsScene.layer.inputImg().histogram(size=graphicsScene.axeSize,
                                                                    bgColor=graphicsScene.bgColor, range=(0, 1),
                                                                    chans=channelValues.L, mode='Lab')
        # L curve use the default axes
        cubic.axes = graphicsScene.defaultAxes
        cubic.initFixedPoints()
        cubic.axes.setVisible(False)
        cubic.setVisible(False)
        ##########
        # a curve (Green--> Magenta axis)
        #########
        cubic = activeCubicSpline(axeSize)
        graphicsScene.addItem(cubic)
        graphicsScene.cubicG = cubic
        cubic.channel = channelValues.a
        cubic.histImg = graphicsScene.layer.inputImg().histogram(size=graphicsScene.axeSize,
                                                                    bgColor=graphicsScene.bgColor, range=(-100, 100),
                                                                    chans=channelValues.a, mode='Lab')
        #  add specific axes
        gradient = QRadialGradient()
        gradient.setCenter(QPoint(0, 1))
        gradient.setRadius(axeSize*1.4)
        gradient.setColorAt(0.0, Qt.green)
        gradient.setColorAt(1.0, Qt.magenta)
        cubic.axes = self.drawPlotGrid(axeSize, gradient)
        graphicsScene.addItem(cubic.axes)
        cubic.initFixedPoints()
        cubic.axes.setVisible(False)
        cubic.setVisible(False)

        # b curve (Blue-->Yellow axis)
        cubic = activeCubicSpline(axeSize)
        graphicsScene.addItem(cubic)
        graphicsScene.cubicB = cubic
        cubic.channel = channelValues.b
        cubic.histImg = graphicsScene.layer.inputImg().histogram(size=graphicsScene.axeSize,
                                                                    bgColor=graphicsScene.bgColor, range=(-100, 100),
                                                                    chans=channelValues.b, mode='Lab')
        # add specific axes
        gradient.setColorAt(0.0, Qt.blue)
        gradient.setColorAt(1.0, Qt.yellow)
        cubic.axes = self.drawPlotGrid(axeSize, gradient)
        graphicsScene.addItem(cubic.axes)
        cubic.initFixedPoints()
        cubic.axes.setVisible(False)
        cubic.setVisible(False)

        # set current to L curve and axes
        graphicsScene.cubicItem = graphicsScene.cubicR
        graphicsScene.cubicItem.setVisible(True)
        graphicsScene.cubicItem.axes.setVisible(True)
        # buttons
        pushButton1 = QPushButton("Reset Current")
        pushButton1.adjustSize()
        pushButton1.clicked.connect(self.resetCurve)
        pushButton2 = QPushButton("Reset All")
        pushButton2.adjustSize()
        pushButton2.clicked.connect(self.resetAllCurves)

        # options
        options = ['L', 'a', 'b']
        self.listWidget1 = optionsWidget(options=options, exclusive=True)
        self.listWidget1.setMinimumSize(self.listWidget1.sizeHintForColumn(0) + 5,
                                        self.listWidget1.sizeHintForRow(0) * len(options) + 5)

        # selection changed handler
        curves = [graphicsScene.cubicR, graphicsScene.cubicG, graphicsScene.cubicB]
        curveDict = dict(zip(options, curves))

        def onSelect1(item):
            cubicItem = self.scene().cubicItem
            cubicItem.setVisible(False)
            cubicItem.axes.setVisible(False)
            self.scene().cubicItem = curveDict[item.text()]
            self.scene().cubicItem.setVisible(True)
            self.scene().cubicItem.axes.setVisible(True)
            # Force to redraw  histogram
            self.scene().invalidate(QRectF(0.0, -self.scene().axeSize, self.scene().axeSize, self.scene().axeSize),
                                    QGraphicsScene.BackgroundLayer)
        self.listWidget1.onSelect = onSelect1
        # set initial selection to L
        item = self.listWidget1.items[options[0]]
        item.setCheckState(Qt.Checked)
        self.listWidget1.select(item)
        self.setWhatsThis("""<b>Lab curves</b><br>""" + self.whatsThis())

        def f():
            l = graphicsScene.layer
            l.applyToStack()
            l.parentImage.onImageChanged()
        self.scene().cubicR.curveChanged.sig.connect(f)
        self.scene().cubicG.curveChanged.sig.connect(f)
        self.scene().cubicB.curveChanged.sig.connect(f)

        # layout
        gl = QGridLayout()
        gl.addWidget(self.listWidget1, 0, 0, 2, 1)
        for i, button in enumerate([pushButton1, pushButton2]):
            gl.addWidget(button, i, 1)
        self.addCommandLayout(gl)
Beispiel #33
0
class ParametersWindow(QWidget):
    """
    Créer la fenêtre des paramètres
    """
    def __init__(self, settings):
        QWidget.__init__(self)
        self.settings = settings

        self.setWindowTitle('PARAMETERS')
        self.setFixedSize(360, 500)

        self.main_layout = QGridLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.setLayout(self.main_layout)

        calculous_parameters_label = QLabel('CALCULOUS PARAMETERS')
        calculous_parameters_label.setAlignment(Qt.AlignCenter)
        calculous_parameters_label.setFixedHeight(58)
        calculous_parameters_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(calculous_parameters_label, 0, 0, 1, 2)

        object_mass_label = QLabel('Object mass (kg)')
        object_mass_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        object_mass_label.setFixedHeight(32)
        self.main_layout.addWidget(object_mass_label, 1, 0, 1, 1)

        self.object_mass_input = QLineEdit()
        self.object_mass_input.setAlignment(Qt.AlignRight)
        self.object_mass_input.setText(str(self.settings.object_mass))
        self.object_mass_input.textChanged.connect(self.updateObjectMass)
        self.main_layout.addWidget(self.object_mass_input, 1, 1, 1, 1)

        dichotomy_precision_label = QLabel('Dichotomy precision')
        dichotomy_precision_label.setFixedHeight(32)
        dichotomy_precision_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(dichotomy_precision_label, 2, 0, 1, 1)

        self.dichotomy_precision_input = QLineEdit()
        self.dichotomy_precision_input.setAlignment(Qt.AlignRight)
        self.dichotomy_precision_input.setText(
            str(self.settings.dichotomy_precision))
        self.dichotomy_precision_input.textChanged.connect(
            self.updateDichotomyPrecision)
        self.main_layout.addWidget(self.dichotomy_precision_input, 2, 1, 1, 1)

        fluid_density_label = QLabel('Fluid density (kg/m3)')
        fluid_density_label.setFixedHeight(32)
        fluid_density_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(fluid_density_label, 3, 0, 1, 1)

        self.fluid_density_options = QComboBox()
        if self.settings.fluid_density == SALTWATER_DENSITY:
            self.fluid_density_options.addItem('saltwater (' +
                                               str(SALTWATER_DENSITY) +
                                               ' kg/m3)')
            self.fluid_density_options.addItem('freshwater (' +
                                               str(FRESHWATER_DENSITY) +
                                               ' kg/m3)')
        else:
            self.fluid_density_options.addItem('freshwater (' +
                                               str(FRESHWATER_DENSITY) +
                                               ' kg/m3)')
            self.fluid_density_options.addItem('saltwater (' +
                                               str(SALTWATER_DENSITY) +
                                               ' kg/m3)')
        self.fluid_density_options.addItem('Other')
        self.fluid_density_options.activated.connect(
            self.updateFluidDensityWithOption)
        self.main_layout.addWidget(self.fluid_density_options, 3, 1, 1, 1)

        self.fluid_density_input = QLineEdit()
        self.fluid_density_input.setAlignment(Qt.AlignRight)
        self.fluid_density_input.textChanged.connect(
            self.updateFluidDensityWithInput)
        if self.settings.fluid_density in [
                FRESHWATER_DENSITY, SALTWATER_DENSITY
        ]:
            self.fluid_density_input.hide()
        else:
            self.fluid_density_input.setText(str(self.settings.fluid_density))
        self.main_layout.addWidget(self.fluid_density_input, 4, 1, 1, 1)

        display_parameters_label = QLabel('DISPLAY PARAMETERS')
        display_parameters_label.setAlignment(Qt.AlignCenter)
        display_parameters_label.setFixedHeight(58)
        display_parameters_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(display_parameters_label, 5, 0, 1, 2)

        show_draught_label = QLabel('Show draught')
        show_draught_label.setFixedHeight(32)
        show_draught_label.setStyleSheet(
            'font-family: Calibri; font-size : 10pt; color: #2C3E50;')
        self.main_layout.addWidget(show_draught_label, 6, 0, 1, 1)
        self.show_draught_checkbox = QCheckBox()
        self.show_draught_checkbox.stateChanged.connect(self.updateShowDraught)
        self.show_draught_checkbox.setCheckState(
            Qt.CheckState.Checked if self.settings.show_draught else Qt.
            CheckState.Unchecked)
        self.main_layout.addWidget(self.show_draught_checkbox, 6, 1, 1, 1)

        self.show()

    def updateObjectMass(self):
        """
        Mettre à jour la masse entrée par l'utilisateur
        """
        try:
            if float(self.object_mass_input.text()
                     ) != self.settings.object_mass:
                self.settings.object_mass = float(
                    self.object_mass_input.text())
                self.lockSimulationButtons()
                self.settings.term.addSuccessMessage(
                    'The mass you entered is in a valid format')
        except Exception:
            self.settings.term.addErrorMessage(
                'The mass you entered is not in a valid format')
        finally:
            pass

    def updateDichotomyPrecision(self):
        """
        Mettre à jour la précision entrée par l'utilisateur
        """
        try:
            if float(self.dichotomy_precision_input.text()
                     ) != self.settings.dichotomy_precision:
                self.settings.dichotomy_precision = float(
                    self.dichotomy_precision_input.text())
                self.lockSimulationButtons()
                self.settings.term.addSuccessMessage(
                    'The dichotomy_precision you entered is in a valid format')
        except Exception:
            self.settings.term.addErrorMessage(
                'The dichotomy_precision you entered is not in a valid format')
        finally:
            pass

    def updateFluidDensityWithOption(self):
        """
        Mettre à jour la densité sélectionnée par l'utilisateur
        """
        option = self.fluid_density_options.currentText()
        if option == 'Other':
            self.fluid_density_input.show()
        else:
            self.fluid_density_input.hide()
            if option == 'freshwater (' + str(FRESHWATER_DENSITY) + ' kg/m3)':
                if self.settings.fluid_density != FRESHWATER_DENSITY:
                    self.settings.fluid_density = FRESHWATER_DENSITY
                    self.lockSimulationButtons()
            else:
                if self.settings.fluid_density != SALTWATER_DENSITY:
                    self.settings.fluid_density = SALTWATER_DENSITY
                    self.lockSimulationButtons()
            self.settings.term.addSuccessMessage(
                'The density of the fluid has correctly been changed')

    def updateFluidDensityWithInput(self):
        """
        Permettre à l'utilisateur d'entrer une densité de lui-même
        """
        try:
            if float(self.fluid_density_input.text()
                     ) != self.settings.fluid_density:
                self.settings.fluid_density = float(
                    self.fluid_density_input.text())
                self.lockSimulationButtons()
                self.settings.term.addSuccessMessage(
                    'The fluid density you entered is in a valid format')
        except Exception:
            self.settings.term.addErrorMessage(
                'The fluid density entered is not in a valid format')
        finally:
            pass

    def updateShowDraught(self):
        """
        Afficher le tirant d'eau si l'utilisateur le désire
        """
        if self.show_draught_checkbox.isChecked(
        ) != self.settings.show_draught:
            self.settings.show_draught = self.show_draught_checkbox.isChecked()
            self.lockSimulationButtons()
            if self.settings.show_draught:
                self.settings.draught_legend.show()
            else:
                self.settings.draught_legend.hide()
            self.settings.term.addSuccessMessage(
                'Show draught has correctly changed')

            self.settings.updatePreview(self.settings.show_draught)

    def lockSimulationButtons(self):
        """
        Désactiver certains boutons lors de la modification des paramètres
        """
        for i in range(3, 7):
            self.settings.buttons[i].setDisabled(True)
        self.settings.buttons[2].setDisabled(False)
Beispiel #34
0
    def __init__(self):
        super(Window, self).__init__()

        self.renderArea = RenderArea()

        self.shapeComboBox = QComboBox()
        self.shapeComboBox.addItem("Polygon", RenderArea.Polygon)
        self.shapeComboBox.addItem("Rectangle", RenderArea.Rect)
        self.shapeComboBox.addItem("Rounded Rectangle", RenderArea.RoundedRect)
        self.shapeComboBox.addItem("Ellipse", RenderArea.Ellipse)
        self.shapeComboBox.addItem("Pie", RenderArea.Pie)
        self.shapeComboBox.addItem("Chord", RenderArea.Chord)
        self.shapeComboBox.addItem("Path", RenderArea.Path)
        self.shapeComboBox.addItem("Line", RenderArea.Line)
        self.shapeComboBox.addItem("Polyline", RenderArea.Polyline)
        self.shapeComboBox.addItem("Arc", RenderArea.Arc)
        self.shapeComboBox.addItem("Points", RenderArea.Points)
        self.shapeComboBox.addItem("Text", RenderArea.Text)
        self.shapeComboBox.addItem("Pixmap", RenderArea.Pixmap)

        shapeLabel = QLabel("&Shape:")
        shapeLabel.setBuddy(self.shapeComboBox)

        self.penWidthSpinBox = QSpinBox()
        self.penWidthSpinBox.setRange(0, 20)
        self.penWidthSpinBox.setSpecialValueText("0 (cosmetic pen)")

        penWidthLabel = QLabel("Pen &Width:")
        penWidthLabel.setBuddy(self.penWidthSpinBox)

        self.penStyleComboBox = QComboBox()
        self.penStyleComboBox.addItem("Solid", Qt.SolidLine)
        self.penStyleComboBox.addItem("Dash", Qt.DashLine)
        self.penStyleComboBox.addItem("Dot", Qt.DotLine)
        self.penStyleComboBox.addItem("Dash Dot", Qt.DashDotLine)
        self.penStyleComboBox.addItem("Dash Dot Dot", Qt.DashDotDotLine)
        self.penStyleComboBox.addItem("None", Qt.NoPen)

        penStyleLabel = QLabel("&Pen Style:")
        penStyleLabel.setBuddy(self.penStyleComboBox)

        self.penCapComboBox = QComboBox()
        self.penCapComboBox.addItem("Flat", Qt.FlatCap)
        self.penCapComboBox.addItem("Square", Qt.SquareCap)
        self.penCapComboBox.addItem("Round", Qt.RoundCap)

        penCapLabel = QLabel("Pen &Cap:")
        penCapLabel.setBuddy(self.penCapComboBox)

        self.penJoinComboBox = QComboBox()
        self.penJoinComboBox.addItem("Miter", Qt.MiterJoin)
        self.penJoinComboBox.addItem("Bevel", Qt.BevelJoin)
        self.penJoinComboBox.addItem("Round", Qt.RoundJoin)

        penJoinLabel = QLabel("Pen &Join:")
        penJoinLabel.setBuddy(self.penJoinComboBox)

        self.brushStyleComboBox = QComboBox()
        self.brushStyleComboBox.addItem("Linear Gradient",
                Qt.LinearGradientPattern)
        self.brushStyleComboBox.addItem("Radial Gradient",
                Qt.RadialGradientPattern)
        self.brushStyleComboBox.addItem("Conical Gradient",
                Qt.ConicalGradientPattern)
        self.brushStyleComboBox.addItem("Texture", Qt.TexturePattern)
        self.brushStyleComboBox.addItem("Solid", Qt.SolidPattern)
        self.brushStyleComboBox.addItem("Horizontal", Qt.HorPattern)
        self.brushStyleComboBox.addItem("Vertical", Qt.VerPattern)
        self.brushStyleComboBox.addItem("Cross", Qt.CrossPattern)
        self.brushStyleComboBox.addItem("Backward Diagonal", Qt.BDiagPattern)
        self.brushStyleComboBox.addItem("Forward Diagonal", Qt.FDiagPattern)
        self.brushStyleComboBox.addItem("Diagonal Cross", Qt.DiagCrossPattern)
        self.brushStyleComboBox.addItem("Dense 1", Qt.Dense1Pattern)
        self.brushStyleComboBox.addItem("Dense 2", Qt.Dense2Pattern)
        self.brushStyleComboBox.addItem("Dense 3", Qt.Dense3Pattern)
        self.brushStyleComboBox.addItem("Dense 4", Qt.Dense4Pattern)
        self.brushStyleComboBox.addItem("Dense 5", Qt.Dense5Pattern)
        self.brushStyleComboBox.addItem("Dense 6", Qt.Dense6Pattern)
        self.brushStyleComboBox.addItem("Dense 7", Qt.Dense7Pattern)
        self.brushStyleComboBox.addItem("None", Qt.NoBrush)

        brushStyleLabel = QLabel("&Brush Style:")
        brushStyleLabel.setBuddy(self.brushStyleComboBox)

        otherOptionsLabel = QLabel("Other Options:")
        self.antialiasingCheckBox = QCheckBox("&Antialiasing")
        self.transformationsCheckBox = QCheckBox("&Transformations")

        self.shapeComboBox.activated.connect(self.shapeChanged)
        self.penWidthSpinBox.valueChanged.connect(self.penChanged)
        self.penStyleComboBox.activated.connect(self.penChanged)
        self.penCapComboBox.activated.connect(self.penChanged)
        self.penJoinComboBox.activated.connect(self.penChanged)
        self.brushStyleComboBox.activated.connect(self.brushChanged)
        self.antialiasingCheckBox.toggled.connect(self.renderArea.setAntialiased)
        self.transformationsCheckBox.toggled.connect(self.renderArea.setTransformed)

        mainLayout = QGridLayout()
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(3, 1)
        mainLayout.addWidget(self.renderArea, 0, 0, 1, 4)
        mainLayout.setRowMinimumHeight(1, 6)
        mainLayout.addWidget(shapeLabel, 2, 1, Qt.AlignRight)
        mainLayout.addWidget(self.shapeComboBox, 2, 2)
        mainLayout.addWidget(penWidthLabel, 3, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penWidthSpinBox, 3, 2)
        mainLayout.addWidget(penStyleLabel, 4, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penStyleComboBox, 4, 2)
        mainLayout.addWidget(penCapLabel, 5, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penCapComboBox, 5, 2)
        mainLayout.addWidget(penJoinLabel, 6, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penJoinComboBox, 6, 2)
        mainLayout.addWidget(brushStyleLabel, 7, 1, Qt.AlignRight)
        mainLayout.addWidget(self.brushStyleComboBox, 7, 2)
        mainLayout.setRowMinimumHeight(8, 6)
        mainLayout.addWidget(otherOptionsLabel, 9, 1, Qt.AlignRight)
        mainLayout.addWidget(self.antialiasingCheckBox, 9, 2)
        mainLayout.addWidget(self.transformationsCheckBox, 10, 2)
        self.setLayout(mainLayout)

        self.shapeChanged()
        self.penChanged()
        self.brushChanged()
        self.antialiasingCheckBox.setChecked(True)

        self.setWindowTitle("Basic Drawing")
    def __init__(self, type, index, parent=None):
        super(DocumentTableHeaderDialog, self).__init__(parent)

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

        # Group box
        text = 'Binary Number' if index >= 0 else 'Binary Numbers'
        toolTip = 'Change label to a binary number' if index >= 0 else 'Change all labels to binary numbers'
        rdbBinary = QRadioButton(text)
        rdbBinary.setToolTip(toolTip)

        text = 'With prefix 0b'
        toolTip = 'Change label to a binary number with prefix 0b otherwise without prefix' if index >= 0 else 'Change all labels to binary numbers with prefix 0b otherwise without prefix'
        self.chkBinary = QCheckBox(text)
        self.chkBinary.setChecked(True)
        self.chkBinary.setEnabled(False)
        self.chkBinary.setToolTip(toolTip)
        rdbBinary.toggled.connect(
            lambda checked: self.chkBinary.setEnabled(checked))

        text = 'Octal Number' if index >= 0 else 'Octal Numbers'
        toolTip = 'Change label to a octal number' if index >= 0 else 'Change all labels to octal numbers'
        rdbOctal = QRadioButton(text)
        rdbOctal.setToolTip(toolTip)

        text = 'With prefix 0o'
        toolTip = 'Change label to a octal number with prefix 0o otherwise without prefix' if index >= 0 else 'Change all labels to octal numbers with prefix 0o otherwise without prefix'
        self.chkOctal = QCheckBox(text)
        self.chkOctal.setChecked(True)
        self.chkOctal.setEnabled(False)
        self.chkOctal.setToolTip(toolTip)
        rdbOctal.toggled.connect(
            lambda checked: self.chkOctal.setEnabled(checked))

        text = 'Decimal Number' if index >= 0 else 'Decimal Numbers'
        toolTip = 'Change label to a decimal number' if index >= 0 else 'Change all labels to decimal numbers'
        rdbDecimal = QRadioButton(text)
        rdbDecimal.setToolTip(toolTip)

        text = 'Enumeration starting with 1'
        toolTip = 'Change label to a decimal number with the enumeration starting with 1 otherwise with 0' if index >= 0 else 'Change all labels to decimal numbers with the enumeration starting with 1 otherwise with 0'
        self.chkDecimal = QCheckBox(text)
        self.chkDecimal.setChecked(True)
        self.chkDecimal.setEnabled(False)
        self.chkDecimal.setToolTip(toolTip)
        rdbDecimal.toggled.connect(
            lambda checked: self.chkDecimal.setEnabled(checked))

        text = 'Hexadecimal Number' if index >= 0 else 'Hexadecimal Numbers'
        toolTip = 'Change label to a hexadecimal number' if index >= 0 else 'Change all labels to hexadecimal numbers'
        rdbHexadecimal = QRadioButton(text)
        rdbHexadecimal.setToolTip(toolTip)

        text = 'With prefix 0x'
        toolTip = 'Change label to a hexadecimal number with prefix 0x otherwise without prefix' if index >= 0 else 'Change all labels to hexadecimal numbers with prefix 0x otherwise without prefix'
        self.chkHexadecimal = QCheckBox(text)
        self.chkHexadecimal.setChecked(True)
        self.chkHexadecimal.setEnabled(False)
        self.chkHexadecimal.setToolTip(toolTip)
        rdbHexadecimal.toggled.connect(
            lambda checked: self.chkHexadecimal.setEnabled(checked))

        text = 'Capital Letter' if index >= 0 else 'Capital Letters'
        toolTip = 'Change label to a capital letter' if index >= 0 else 'Change all labels to capital letters'
        rdbLetter = QRadioButton(text)
        rdbLetter.setToolTip(toolTip)

        text = 'Letter as uppercase letter' if index >= 0 else 'Letters as uppercase letters'
        toolTip = 'Change label to a letter as uppercase letter otherwise lowercase letter' if index >= 0 else 'Change all labels to letters as uppercase letters otherwise lowercase letters'
        self.chkLetter = QCheckBox(text)
        self.chkLetter.setChecked(True)
        self.chkLetter.setEnabled(False)
        self.chkLetter.setToolTip(toolTip)
        rdbLetter.toggled.connect(
            lambda checked: self.chkLetter.setEnabled(checked))

        text = 'User-defined Text' if index >= 0 else 'User-defined Texts'
        toolTip = 'Change label to a user-defined text' if index >= 0 else 'Change all labels to user-defined texts'
        rdbCustom = QRadioButton(text)
        rdbCustom.setToolTip(toolTip)

        toolTip = 'Change label to a user-defined text' if index >= 0 else 'Change all labels to user-defined texts'
        self.ledCustom = QLineEdit()
        self.ledCustom.setEnabled(False)
        self.ledCustom.setToolTip(toolTip)
        rdbCustom.toggled.connect(
            lambda checked: self.ledCustom.setEnabled(checked))

        text = '# will be replaced with column index' if type == 'horizontal' else '# will be replaced with row index'
        lblCustom = QLabel(text)
        lblCustom.setEnabled(False)
        rdbCustom.toggled.connect(
            lambda checked: lblCustom.setEnabled(checked))

        self.grpHeaderLabel = QButtonGroup(self)
        self.grpHeaderLabel.addButton(rdbBinary,
                                      Preferences.HeaderLabel.Binary.value)
        self.grpHeaderLabel.addButton(rdbOctal,
                                      Preferences.HeaderLabel.Octal.value)
        self.grpHeaderLabel.addButton(rdbDecimal,
                                      Preferences.HeaderLabel.Decimal.value)
        self.grpHeaderLabel.addButton(
            rdbHexadecimal, Preferences.HeaderLabel.Hexadecimal.value)
        self.grpHeaderLabel.addButton(rdbLetter,
                                      Preferences.HeaderLabel.Letter.value)
        self.grpHeaderLabel.addButton(rdbCustom,
                                      Preferences.HeaderLabel.Custom.value)
        self.grpHeaderLabel.buttonClicked.connect(self.onSettingChanged)

        groupLayout = QGridLayout()
        groupLayout.addWidget(rdbBinary, 0, 0)
        groupLayout.addWidget(self.chkBinary, 0, 1)
        groupLayout.addWidget(rdbOctal, 1, 0)
        groupLayout.addWidget(self.chkOctal, 1, 1)
        groupLayout.addWidget(rdbDecimal, 2, 0)
        groupLayout.addWidget(self.chkDecimal, 2, 1)
        groupLayout.addWidget(rdbHexadecimal, 3, 0)
        groupLayout.addWidget(self.chkHexadecimal, 3, 1)
        groupLayout.addWidget(rdbLetter, 4, 0)
        groupLayout.addWidget(self.chkLetter, 4, 1)
        groupLayout.addWidget(rdbCustom, 5, 0)
        groupLayout.addWidget(self.ledCustom, 5, 1)
        groupLayout.addWidget(lblCustom, 6, 1)
        groupLayout.setRowStretch(7, 1)

        text = 'Change label to a …' if index >= 0 else 'Change all labels to …'
        groupBox = QGroupBox(text)
        groupBox.setLayout(groupLayout)

        # Button box
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        self.buttonOk = buttonBox.button(QDialogButtonBox.Ok)
        self.buttonOk.setEnabled(False)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        # Main layout
        layout = QVBoxLayout()
        layout.addWidget(groupBox)
        layout.addWidget(buttonBox)

        self.setLayout(layout)
    def __init__(self):
        super(Window, self).__init__()

        aliasedLabel = self.createLabel("Aliased")
        antialiasedLabel = self.createLabel("Antialiased")
        intLabel = self.createLabel("Int")
        floatLabel = self.createLabel("Float")

        layout = QGridLayout()
        layout.addWidget(aliasedLabel, 0, 1)
        layout.addWidget(antialiasedLabel, 0, 2)
        layout.addWidget(intLabel, 1, 0)
        layout.addWidget(floatLabel, 2, 0)

        timer = QTimer(self)

        for i in range(2):
            for j in range(2):
                w = CircleWidget()
                w.setAntialiased(j != 0)
                w.setFloatBased(i != 0)

                timer.timeout.connect(w.nextAnimationFrame)

                layout.addWidget(w, i + 1, j + 1)

        timer.start(100)
        self.setLayout(layout)

        self.setWindowTitle("Concentric Circles")
    def __init__(self, parent):
        super().__init__(parent)
        
        self.setWindowTitle("Connect Database")

        self.user_label = QLabel("Database User:"******"e.g. root")
        self.user.setDragEnabled(True)
        self.user.setFocus()
        self.user.setClearButtonEnabled(True)

        self.pw_label = QLabel("Database Password:"******"e.g. toor")
        self.password.setClearButtonEnabled(True)
        self.password.setEchoMode(QLineEdit.Password)

        self.db_name_label = QLabel("Database Name:")
        self.db_name = QLineEdit()
        self.db_name.setPlaceholderText("e.g. bank-db")
        self.db_name.setDragEnabled(True)
        self.db_name.setClearButtonEnabled(True)

        self.host_name_label = QLabel("Host Name:")
        self.host_name = QLineEdit()
        self.host_name.setPlaceholderText("e.g. localhost")
        self.host_name.setDragEnabled(True)
        self.host_name.setClearButtonEnabled(True)
        
        self.connect_bttn = QPushButton("Connect")
        self.connect_bttn.clicked.connect(self.connect)

        layout = QGridLayout()
        
        layout.addWidget(self.user_label, 0, 0)
        layout.addWidget(self.user, 0, 1)

        layout.addWidget(self.pw_label, 1, 0)
        layout.addWidget(self.password, 1, 1)

        layout.addWidget(self.db_name_label, 2, 0)
        layout.addWidget(self.db_name, 2, 1)

        layout.addWidget(self.host_name_label, 3, 0)
        layout.addWidget(self.host_name, 3, 1)

        layout.addWidget(self.connect_bttn, 4, 1)

        self.setLayout(layout)
        self.setModal(True)
class Widget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setMinimumSize(800, 600)
        self.donuts = []
        self.chart_view = QtCharts.QChartView()
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart = self.chart_view.chart()
        self.chart.legend().setVisible(False)
        self.chart.setTitle("Nested donuts demo")
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)

        self.min_size = 0.1
        self.max_size = 0.9
        self.donut_count = 5

        self.setup_donuts()

        # create main layout
        self.main_layout = QGridLayout(self)
        self.main_layout.addWidget(self.chart_view, 1, 1)
        self.setLayout(self.main_layout)

        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.update_rotation)
        self.update_timer.start(1250)

    def setup_donuts(self):
        for i in range(self.donut_count):
            donut = QtCharts.QPieSeries()
            slccount = randrange(3, 6)
            for j in range(slccount):
                value = randrange(100, 200)

                slc = QtCharts.QPieSlice(str(value), value)
                slc.setLabelVisible(True)
                slc.setLabelColor(Qt.white)
                slc.setLabelPosition(QtCharts.QPieSlice.LabelInsideTangential)

                # Connection using an extra parameter for the slot
                slc.hovered[bool].connect(partial(self.explode_slice, slc=slc))

                donut.append(slc)
                size = (self.max_size - self.min_size)/self.donut_count
                donut.setHoleSize(self.min_size + i * size)
                donut.setPieSize(self.min_size + (i + 1) * size)

            self.donuts.append(donut)
            self.chart_view.chart().addSeries(donut)



    def update_rotation(self):
        for donut in self.donuts:
            phase_shift =  randrange(-50, 100)
            donut.setPieStartAngle(donut.pieStartAngle() + phase_shift)
            donut.setPieEndAngle(donut.pieEndAngle() + phase_shift)

    def explode_slice(self, exploded, slc):
        if exploded:
            self.update_timer.stop()
            slice_startangle = slc.startAngle()
            slice_endangle = slc.startAngle() + slc.angleSpan()

            donut = slc.series()
            idx = self.donuts.index(donut)
            for i in range(idx + 1, len(self.donuts)):
                self.donuts[i].setPieStartAngle(slice_endangle)
                self.donuts[i].setPieEndAngle(360 + slice_startangle)
        else:
            for donut in self.donuts:
                donut.setPieStartAngle(0)
                donut.setPieEndAngle(360)

            self.update_timer.start()

        slc.setExploded(exploded)
Beispiel #39
0
    def _load_screen(self):

        box = QGridLayout()
        box.addWidget(QLabel(_("Database user")), 0, 0, 1, 1, Qt.AlignBottom)
        self.inp_user = QLineEdit()
        self.inp_user.setPlaceholderText(_("openmeetingsuser"))
        box.addWidget(self.inp_user, 1, 0, 1, 1, Qt.AlignTop)
        box.addWidget(QLabel(_("User password")), 2, 0, 1, 1, Qt.AlignTop)
        box.addWidget(QLabel(_("* At least 8 character")), 3, 0, 1, 1,
                      Qt.AlignTop)
        box.addWidget(QLabel(_("SPECIAL CHARACTERS NOT ALLOWED")), 4, 0, 1, 1,
                      Qt.AlignTop)
        self.inp_pwd = QLineEdit()
        self.inp_pwd.setEchoMode(QLineEdit.Password)
        self.inp_pwd.setPlaceholderText(_("p4ssw0rd"))
        box.addWidget(self.inp_pwd, 5, 0, 1, 1, Qt.AlignTop)
        self.inp_pwd2 = QLineEdit()
        self.inp_pwd2.setEchoMode(QLineEdit.Password)
        self.inp_pwd2.setPlaceholderText(_("p4ssw0rd"))
        box.addWidget(self.inp_pwd2, 6, 0, 1, 1, Qt.AlignTop)
        box.addWidget(QLabel(_("Admin user")), 7, 0, 1, 1, Qt.AlignBottom)
        self.inp_admin = QLineEdit()
        self.inp_admin.setPlaceholderText(_("admin"))
        box.addWidget(self.inp_admin, 8, 0, 1, 1, Qt.AlignTop)
        box.addWidget(QLabel(_("Admin password")), 9, 0, 1, 1, Qt.AlignTop)
        box.addWidget(QLabel(_("* At least 8 character")), 10, 0, 1, 1,
                      Qt.AlignTop)
        box.addWidget(
            QLabel(
                _("* Uppercase and lowercase\n* Alphanumeric\n* With special characters (!, #, &...) "
                  )), 11, 0, 1, 1, Qt.AlignTop)
        self.inp_apwd = QLineEdit()
        self.inp_apwd.setEchoMode(QLineEdit.Password)
        self.inp_apwd.setPlaceholderText(_("P4ssw0rd!"))
        box.addWidget(self.inp_apwd, 12, 0, 1, 1, Qt.AlignTop)
        self.inp_apwd2 = QLineEdit()
        self.inp_apwd2.setEchoMode(QLineEdit.Password)
        self.inp_apwd2.setPlaceholderText(_("P4ssw0rd!"))
        box.addWidget(self.inp_apwd2, 13, 0, 1, 1, Qt.AlignTop)
        box.addWidget(QLabel(_("Admin email")), 14, 0, 1, 1, Qt.AlignTop)
        self.inp_mail = QLineEdit()
        self.inp_mail.setPlaceholderText(_("*****@*****.**"))
        box.addWidget(self.inp_mail, 15, 0, 1, 1, Qt.AlignTop)
        self.setLayout(box)
        self.updateScreen()
        return (self)
    def add_purchase_row(
        self,
        item: TransactionItemType,
        layout: QGridLayout,
        row: int,
    ) -> None:
        exist = QGroupBox()
        exist.setProperty("style", "buy-box")
        exist.setMaximumHeight(72)
        exist.setMinimumHeight(36)
        existLayout = QHBoxLayout()
        existLayout.setSizeConstraint(QLayout.SetMinimumSize)
        exist.setLayout(existLayout)

        existing_units = self.current_quantity_of(item)

        unitName = QLabel(f"<b>{self.display_name_of(item, multiline=True)}</b>")
        unitName.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        )

        existing_units = QLabel(str(existing_units))
        existing_units.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.existing_units_labels[item] = existing_units

        price = QLabel(f"<b>$ {self.price_of(item)}</b> M")
        price.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        purchase_group = PurchaseGroup(item, self)
        self.purchase_groups[item] = purchase_group

        info = QGroupBox()
        info.setProperty("style", "buy-box")
        info.setMaximumHeight(72)
        info.setMinimumHeight(36)
        infolayout = QHBoxLayout()
        info.setLayout(infolayout)

        unitInfo = QPushButton("i")
        unitInfo.setProperty("style", "btn-info")
        unitInfo.setMinimumSize(16, 16)
        unitInfo.setMaximumSize(16, 16)
        unitInfo.clicked.connect(lambda: self.info(item))
        unitInfo.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        existLayout.addWidget(unitName)
        existLayout.addItem(
            QSpacerItem(20, 0, QSizePolicy.Minimum, QSizePolicy.Minimum)
        )
        existLayout.addWidget(existing_units)
        existLayout.addItem(
            QSpacerItem(20, 0, QSizePolicy.Minimum, QSizePolicy.Minimum)
        )
        existLayout.addWidget(price)

        infolayout.addWidget(unitInfo)

        layout.addWidget(exist, row, 1)
        layout.addWidget(purchase_group, row, 2)
        layout.addWidget(info, row, 3)
Beispiel #41
0
    def __init__(self):
        super().__init__()
        self.Zones1 = []
        self.Zones2 = []
        self.MainLayout = QGridLayout()
        self.setLayout(self.MainLayout)
        self.DialogColorPicker = DialogColorPicker()

        # Create a list of Dictionnary to manage the Library manually
        zoneconf1 = []
        zoneconf2 = []

        zoneconf1.append({"offset1": 0, "lengthled": 20})
        zoneconf1.append({"offset1": 20, "lengthled": 10})
        zoneconf1.append({"offset1": 30, "lengthled": 10})
        zoneconf1.append({"offset1": 40, "lengthled": 10})
        zoneconf1.append({"offset1": 50, "lengthled": 10})

        zoneconf2.append({"offset1": 60, "lengthled": 20})
        zoneconf2.append({"offset1": 80, "lengthled": 10})
        zoneconf2.append({"offset1": 90, "lengthled": 10})
        zoneconf2.append({"offset1": 100, "lengthled": 10})
        zoneconf2.append({"offset1": 110, "lengthled": 10})

        # Create the specific push button for each Zone of the Library

        offset2 = 0

        for zone in zoneconf1:
            offset2 = offset2 + zone["lengthled"]

        print(offset2)

        for zone in zoneconf1:
            self.Zones1.append(
                Zone(zone["offset1"], zone["lengthled"], offset2))
            self.Zones1[-1].setStyleSheet(
                "QPushButton {background-color:black}")
            self.Zones1[-1].clickeddata.connect(
                self.DialogColorPicker.showFullScreen)

        offset2 = 0

        for zone in zoneconf2:
            offset2 = offset2 + zone["lengthled"]

        print(offset2)

        for zone in zoneconf2:
            self.Zones2.append(
                Zone(zone["offset1"], zone["lengthled"], offset2))
            self.Zones2[-1].setStyleSheet(
                "QPushButton {background-color:black}")
            self.Zones2[-1].clickeddata.connect(
                self.DialogColorPicker.showFullScreen)

        # Create the interface
        i = 0
        for zone in self.Zones1:
            self.MainLayout.addWidget(zone, i, 1)
            i = i + 1

        i = 0
        for zone in self.Zones2:
            self.MainLayout.addWidget(zone, i, 2)
            i = i + 1
Beispiel #42
0
    def _init_widgets(self):
        try:
            from tracer import QEMURunner
        except:
            QMessageBox.about(self, 'Error', f"Unable to import QEMURunner, install angr tracer")
            self.close()

        self.setWindowTitle('New trace state')
        container = QVBoxLayout()
        layout = QGridLayout()
        row = 0

        args_label = QLabel(self)
        args_label.setText("Command-line arguments:")
        layout.addWidget(args_label, row, 0)
        row += 1

        args = QLineEdit(self)
        bin_name = str(self.instance.project).split(" ")[1][:-1]
        args.setText(bin_name)
        layout.addWidget(args, row, 0)
        row += 1

        input_label = QLabel(self)
        input_label.setText("Input:")
        layout.addWidget(input_label, row, 0)
        row += 1

        input_box = QPlainTextEdit()
        input_box.setWordWrapMode(QTextOption.WordWrap)
        layout.addWidget(input_box, row, 0)
        row += 1

        addr_label = QLabel(self)
        addr_label.setText("Stop address:")
        layout.addWidget(addr_label, row, 0)
        row += 1

        addr_box = QLineEdit(self)
        layout.addWidget(addr_box, row, 0)
        row += 1

        def parse_address():
            txt = addr_box.text()
            try:
                return self.instance.project.kb.labels.lookup(txt)
            except KeyError:
                pass

            try:
                return int(txt, 16)
            except ValueError:
                return None

        ok_button = QPushButton(self)
        ok_button.setText('OK')
        def do_ok():
            argv = shlex.split(args.text())
            inp = bytes(input_box.toPlainText().encode('latin-1'))
            addr = parse_address()

            try:
                p = self.instance.project
                r = QEMURunner(binary=bin_name,
                               argv=argv,
                               input=inp,
                               project=p)

                s = p.factory.entry_state(
                        mode='tracing',
                        stdin=angr.SimFileStream)
                s.preconstrainer.preconstrain_file(inp, s.posix.stdin, True)

                sm = p.factory.simgr(
                    s,
                    save_unsat=True,
                    hierarchy=False,
                    save_unconstrained=r.crash_mode)

                t = sm.use_technique(
                    angr.exploration_techniques.Tracer(
                        trace=r.trace,
                        resiliency=True,
                        keep_predecessors=1,
                        crash_addr=r.crash_addr))
                sm.use_technique(angr.exploration_techniques.Oppologist())
                sm.explore(find=addr)

                # add state to global state store
                state = sm.traced[0] if len(sm.traced) > 0 else sm.found[0]
                name = f"{hex(state.addr)} trace"
                state.gui_data.base_name = name
                state.gui_data.is_base = True
                state.gui_data.name = name
                state.gui_data.is_original = True
                self.instance.states.append(state)
                self._base_state_combo.refresh()
                for i in range(self._base_state_combo.count()):
                    if self._base_state_combo.itemText(i) == name:
                        self._base_state_combo.setCurrentIndex(i)
                self._address_box.setText(hex(state.addr))

                self.close()
            except Exception as e:
                QMessageBox.about(self, 'Error', f"{repr(e)}")

        ok_button.clicked.connect(do_ok)

        cancel_button = QPushButton(self)
        cancel_button.setText('Cancel')
        def do_cancel():
            self.close()
        cancel_button.clicked.connect(do_cancel)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)

        container.addLayout(layout)
        container.addLayout(buttons_layout)

        self.setLayout(container)
        self.exec_()
Beispiel #43
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('Commander V 0.1')
        self.resize(1600, 1200)

        #Functions
        self.commands = {

            # GUI commands
            'CLEARALL': self.clear_all_results,
            # Basic Text Commands
            'transform': TextFunctions().transform,
            '-tf': TextFunctions().transform,
            # Translation Commands
            'translate': TextFunctions().translate,
            '-tr': TextFunctions().translate,
            # Information Commands
            'extract': ExtractFunctions().extract,
            '-ext': ExtractFunctions().extract,
            'regex': ExtractFunctions().regex,
            '-re': ExtractFunctions().regex,
            # Image Functions
            'grayscale': ImageFunctions().grayscale,
            'bw': ImageFunctions().bw,
            'flip': ImageFunctions().flip,
            'invert': ImageFunctions().invert
        }

        # Fonts
        self.text_font = QFont('monospace', 16)
        self.button_font = QFont('monospace', 18)
        self.console_font = QFont('monospace', 14)

        # Create widgets

        self.input_area = QTabWidget()
        self.input_area.setFont(self.text_font)

        self.text_area = QTextEdit()
        self.text_area.setFont(self.text_font)

        self.file_area = FileArea()

        self.image_area = ImageArea()

        self.result_scroll_area = QScrollArea()

        self.result_area = QWidget()
        self.result_area.layout = QVBoxLayout()
        self.result_area.setLayout(self.result_area.layout)

        self.result_scroll_area.setWidget(self.result_area)
        self.result_scroll_area.setWidgetResizable(True)

        self.console = QTextEdit()
        self.console.setMaximumHeight(300)
        self.console.setReadOnly(True)
        self.console.setStyleSheet(
            'background-color: #0F0E0D; color: white; border: 0;')
        self.console.setFont(self.console_font)

        def set_command_line_focus(event):
            self.command_line.setFocus()

        self.console.mousePressEvent = set_command_line_focus

        self.command_line = QLineEdit()
        # self.command_line.setStyleSheet('background-color: #0F0E0D; color: white; border: 0;')
        self.command_line.setFont(self.console_font)
        self.command_line.setPlaceholderText('Enter command')
        self.command_line.setTextMargins(5, 0, 0, 0)

        self.execute_button = QPushButton("Execute")
        self.execute_button.setFont(self.button_font)
        self.execute_button.setStyleSheet(
            'background-color: red; color: white;')
        self.command_line.returnPressed.connect(self.execute_button.click)
        self.execute_button.setVisible(False)

        # Create layout and add widgets
        self.layout = QGridLayout()

        self.top_layout = QGridLayout()

        # Tabbed input area
        self.top_layout.addWidget(self.input_area, 0, 0)
        self.input_area.insertTab(0, self.text_area, 'Text')
        self.input_area.insertTab(1, self.file_area, 'File')
        self.input_area.insertTab(2, self.image_area, 'Image')

        self.top_layout.addWidget(self.result_scroll_area, 0, 2)

        self.bottom_layout = QGridLayout()
        self.bottom_layout.setSpacing(0)

        self.bottom_layout.addWidget(self.console, 0, 0)
        self.bottom_layout.addWidget(self.command_line, 1, 0)
        self.bottom_layout.addWidget(self.execute_button, 2, 0)

        # Set layout
        self.setLayout(self.layout)
        self.layout.addLayout(self.top_layout, 0, 0)
        self.layout.addLayout(self.bottom_layout, 1, 0)

        # Add button signal to execution function
        self.execute_button.clicked.connect(self.execute_command)

        # Set focus to command line
        self.command_line.setFocus()