예제 #1
0
class GUi(QApplication):
    def __init__(self):
        self.InitU()

    def InitU(self):
        self.win = QWidget()
        self.win.setWindowTitle("赵二黑不黑")
        self.win.backgroundRole()
예제 #2
0
파일: main.py 프로젝트: baolonglin/funmath
 def showQuestion(self, question):
     if question:
         self.questionWidget = QuestionWidget(self, question)
         layout = QVBoxLayout()
         layout.addStretch(1)
         layout.addWidget(self.questionWidget, 1)
         layout.addStretch(1)
         cmdLayout = QHBoxLayout()
         prevButton = QPushButton("<<")
         prevButton.clicked.connect(self.prevButtonClicked)
         prevButton.setFocusPolicy(Qt.NoFocus)
         nextButton = QPushButton(">>")
         nextButton.clicked.connect(self.nextButtonClicked)
         nextButton.setFocusPolicy(Qt.NoFocus)
         cmdLayout.addWidget(prevButton)
         cmdLayout.addStretch(1)
         cmdLayout.addWidget(nextButton)
         layout.addLayout(cmdLayout)
         centralWidget = QWidget()
         centralWidget.setAutoFillBackground(True)
         p = centralWidget.palette()
         p.setColor(centralWidget.backgroundRole(), QColor(219, 238, 221))
         centralWidget.setPalette(p)
         centralWidget.setLayout(layout)
         self.setCentralWidget(centralWidget)
         self.questionWidget.setFocus()
     else:
         reply = QMessageBox.question(self, self.tr('Message'),
                                      self.tr("Do you want to submit?"),
                                      QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.No)
         if reply == QMessageBox.Yes:
             self.stop()
예제 #3
0
    def InitWindow(self):
        """
            Метод инициализации основных компонентов основного экрана
        """
        self.timer = QTimer(self)
        self.timer.setSingleShot(False)
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.redraw_event)

        q_maze_grid = QGridLayout()
        q_maze_grid.setSpacing(0)
        q_maze_grid.addWidget(QWidget())

        row, col = 0, 0
        for i in range(1):
            maze = QMazeVisualizer(maze_matrix.Maze(50, 50))
            self.mazes.append(maze)

            if col >= 2:
                row += 1
                col = 0

            q_maze_grid.addWidget(maze, row, col)
            col += 1

        main_layout = QHBoxLayout()
        main_layout.addLayout(q_maze_grid)
        widget = QWidget()
        palette = widget.palette()
        widget.setAutoFillBackground(True)
        palette.setColor(widget.backgroundRole(), Qt.black)
        widget.setPalette(palette)
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)
예제 #4
0
    def initUI(self):
        """
            Create the GUI of the window.
        """
        central_widget = QWidget()

        central_widget.layout = QHBoxLayout()
        central_widget.setLayout(central_widget.layout)
        logo = makeWidget.make_pixmap("ressources/logo2.png")
        central_widget.layout.addWidget(logo)

        text_area = makeWidget.make_vbox()
        # todo: demander une confirmation de la traduction
        description = """
        <html>
        <h1>RDRP Database Tools</h1>
        <h3>"Reaction-Diffusion modelling for Retention and Permation Database Tools"</h3>
        <p><b>Version 1.0</b></p>
        <br/>
        <p> A Graphical User Interface made by the <a href="www.lspm.cnrs.fr/">LSPM</a> (Laboratory of Sciences of Processes and Materials).</p>
        </html>"""
        desc_label = QLabel(description)
        desc_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        desc_label.setOpenExternalLinks(True)
        text_area.layout.addWidget(desc_label)
        central_widget.layout.addWidget(text_area)
        p = central_widget.palette()
        p.setColor(central_widget.backgroundRole(), QColor(0, 0, 0))
        central_widget.setPalette(p)
        self.setCentralWidget(central_widget)
예제 #5
0
class ListItem:
    def __init__(self, window, name, now, freshUntil):
        self.window = window
        self.listWidget = QListWidgetItem(window.ui.listWidget)
        self.widget = QWidget(self.window)
        self.ui = listItem.Ui_ListItem()
        self.ui.setupUi(self.widget)
        self.ui.labelItem.setText(name)
        self.insert = now
        self.freshUntil = freshUntil
        self.name = name
        self.expired = False

        self.currentCategory = 0

        self.thresholds = [(100, QColor(0x55, 0xff, 0x7f)),
                           (50, QColor(0xff, 0xaa, 0x00)),
                           (25, QColor(0xff, 0x55, 0x00))]

        self.ui.removeButton.clicked.connect(self.removeClicked)
        self.setStatus(now)

    def setStatus(self, now):
        if self.expired:
            return

        remaining = now.daysTo(self.freshUntil)
        if remaining < 0:
            self.expired = True
            color = QColor(0xff, 0x9b, 0x9b)
            palette = self.widget.palette()
            palette.setColor(self.widget.backgroundRole(), color)
            self.widget.setPalette(palette)
            self.listWidget.setBackground(color)
            return

        fraction = int(
            (float(remaining) / self.insert.daysTo(self.freshUntil)) * 100)

        category = self.currentCategory
        for i in range(len(self.thresholds)):
            if fraction < self.thresholds[i][0]:
                category = i

        if category != self.currentCategory:
            self.currentCategory = category
            palette = self.ui.freshBar.palette()
            palette.setColor(QPalette.Highlight, self.thresholds[category][1])
            self.ui.freshBar.setPalette(palette)

        self.ui.freshBar.setValue(fraction)

    def setEnabled(self, enabled):
        self.ui.removeButton.setEnabled(enabled)

    def removeClicked(self):
        self.window.removeItem(self)
 def init_eraser(self, w, h):
     eraser = QWidget(self)
     eraser.setAttribute(Qt.WA_TransparentForMouseEvents)
     effect = QGraphicsOpacityEffect(eraser)
     effect.setOpacity(0.4)
     eraser.setGraphicsEffect(effect)
     eraser.setGeometry(0, 0, w, h)
     eraser.setAutoFillBackground(True)
     p = eraser.palette()
     p.setColor(eraser.backgroundRole(),
                QColor(self.conf['colors']['eraser']))
     eraser.setPalette(p)
     eraser.hide()
     return eraser
 def init_cursor(self, w, h):
     cursor = QWidget(self)
     cursor.setAttribute(Qt.WA_TransparentForMouseEvents)
     effect = QGraphicsOpacityEffect(cursor)
     effect.setOpacity(0.4)
     cursor.setGraphicsEffect(effect)
     cursor.setGeometry(0, 0, w, h)
     cursor.setAutoFillBackground(True)
     p = cursor.palette()
     p.setColor(cursor.backgroundRole(),
                QColor(self.conf['colors']['cursor']))
     cursor.setPalette(p)
     cursor.hide()
     return cursor
예제 #8
0
    def setLayoutApp(self):
        centralWidget = QWidget()
        p = centralWidget.palette()
        p.setColor(centralWidget.backgroundRole(), pg.mkColor('k'))
        centralWidget.setPalette(p)

        fcentral = QVBoxLayout()
        gcentral = QGroupBox("Forma de Onda")
        filas = QVBoxLayout()

        self.plt1 = pg.PlotWidget()
        filas.addWidget(self.plt1)

        gcentral.setLayout(filas)
        fcentral.addWidget(gcentral)
        centralWidget.setLayout(fcentral)
        self.setCentralWidget(centralWidget)
예제 #9
0
    def _get_directory_browse_widget(self):
        widget = QWidget()
        p=widget.palette()
        p.setColor(widget.backgroundRole(),Qt.red)
        widget.setPalette(p)
        widget.setStyleSheet(SOME_STYLE)
        hbox = QHBoxLayout(widget)
        hbox.setContentsMargins(0, 0, 0, 0)

        self._path_edit = QLineEdit(self._download_dir)
        self._path_edit.setReadOnly(True)
        hbox.addWidget(self._path_edit, 3)

        browse_button = QPushButton('Browse...')
        browse_button.clicked.connect(self._browse)
        hbox.addWidget(browse_button, 1)

        widget.setLayout(hbox)
        return widget
예제 #10
0
    def _createFileInfo(self, filePath, data):
        self.clear()

        w = QWidget(self)
        w.setLayout(QFormLayout())
        w.layout().setContentsMargins(2, 2, 2, 2)
        w.layout().setSizeConstraint(QLayout.SetMinimumSize)

        sa = QScrollArea(self)
        sa.setWidget(w)
        sa.setBackgroundRole(w.backgroundRole())

        fileNameLabel = QLabel(os.path.split(filePath)[1], self)
        fileNameLabel.setToolTip(fileNameLabel.text())

        fpsLabel = QLabel(str(data.fps), self)
        fpsLabel.setToolTip(fpsLabel.text())

        formatLabel = QLabel(data.outputFormat.NAME, self)
        formatLabel.setToolTip(formatLabel.text())

        inEncodingLabel = QLabel(data.inputEncoding, self)
        inEncodingLabel.setToolTip(inEncodingLabel.text())

        outEncodingLabel = QLabel(data.outputEncoding, self)
        outEncodingLabel.setToolTip(outEncodingLabel.text())

        if data.videoPath is not None:
            videoLabel = QLabel(data.videoPath, self)
            videoLabel.setToolTip(videoLabel.text())
        else:
            videoLabel = QLabel("-", self)
            videoLabel.setToolTip(_("No video"))

        w.layout().addRow(_("File name:"), fileNameLabel)
        w.layout().addRow(_("Video:"), videoLabel)
        w.layout().addRow(_("FPS:"), fpsLabel)
        w.layout().addRow(_("Format:"), formatLabel)
        w.layout().addRow(_("Input encoding:"), inEncodingLabel)
        w.layout().addRow(_("Output encoding:"), outEncodingLabel)

        self.layout().addWidget(sa)
예제 #11
0
    def setLayoutApp(self):
        centralWidget = QWidget()
        p = centralWidget.palette()
        p.setColor(centralWidget.backgroundRole(), pg.mkColor('k'))
        centralWidget.setPalette(p)

        fcentral = QVBoxLayout()
        gcentral = QGroupBox("Forma de Onda")
        filas = QVBoxLayout()
        self.plt1 = pg.PlotWidget()
        self.plt2 = pg.PlotWidget()
        filas.addWidget(self.plt1)
        self.labelFps = QLabel()
        self.labelFps.setText('Frames por segundos: 0.0')
        self.labelFps.setStyleSheet('color: green')
        filas.addWidget(self.labelFps)
        filas.addWidget(self.plt2)

        gcentral.setLayout(filas)
        fcentral.addWidget(gcentral)
        centralWidget.setLayout(fcentral)
        self.setCentralWidget(centralWidget)
예제 #12
0
            x = msg_2.exec_()


if __name__ == "__main__":
    import sys

    #firebase = firebase.FirebaseApplication('https://e-trac-5d530.firebaseio.com/', None)
    app = QtWidgets.QApplication(sys.argv)
    #GPIO.cleanup()
    #GPIO.setmode(GPIO.BCM)
    #GPIO.setwarnings(False)
    #GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    Dialog = QtWidgets.QDialog()
    u_i = Ui_Dialog()
    u_i.setupUi(Dialog)
    Dialog.show()
    u_i.boot()

    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    w = QWidget()
    p = w.palette()
    w.setColor(w.backgroundRole(), Qt.white)
    w.setPalette(p)
    w.show()

    sys.exit(app.exec_())
    #GPIO.cleanup()
    #app = QtWidgets.QApplication(sys.argv)
예제 #13
0
파일: windows.py 프로젝트: gridl/PyGenoCar
class DensityWindow(QWidget):
    def __init__(self, parent, size):
        super().__init__(parent)
        self.size = size
        self.resize(size[0], size[1])
        self._gradient_widget = QWidget()
        self._gradient_widget.resize(size[0] / 2, size[1])
        self._create_linear_gradient()

        self.boxcar_form = QFormLayout()

        self.layout = QVBoxLayout()
        column_layout = QHBoxLayout()  # For the densities and gradient
        self.layout.setContentsMargins(0, 0, 0, 0)

        # Add the headers for the two columns we will have
        headers = QHBoxLayout()
        headers.setContentsMargins(0, 0, 0, 0)
        # Add header for chassis density
        label_chassis_densities = QLabel()
        label_chassis_densities.setText('Chassis Density')
        label_chassis_densities.setAlignment(Qt.AlignHCenter | Qt.AlignBottom)
        headers.addWidget(label_chassis_densities)
        # Add spacer
        headers.addStretch(1)
        # Add header for wheel density
        label_wheel_density = QLabel()
        label_wheel_density.setText('Wheel Density')
        label_wheel_density.setAlignment(Qt.AlignHCenter | Qt.AlignBottom)
        headers.addWidget(label_wheel_density)

        # Add headers
        self.layout.addLayout(headers)

        # Add Chassis Density stuff
        chassis_density_vbox = QVBoxLayout()
        chassis_density_vbox.setContentsMargins(0, 0, 0, 0)
        min_chassis_density = get_boxcar_constant('min_chassis_density')
        max_chassis_density = get_boxcar_constant('max_chassis_density')
        chassis_range = max_chassis_density - min_chassis_density
        num_slices = 10  # Number of sections to add
        chassis_slices = [
            (chassis_range) / (num_slices - 1) * i + min_chassis_density
            for i in range(num_slices)
        ]

        for chassis_slice in chassis_slices:
            label = QLabel()
            text = '{:.2f} -'.format(chassis_slice)
            label.setAlignment(Qt.AlignRight | Qt.AlignTop)
            label.setText(text)
            chassis_density_vbox.addWidget(label)

        # Add the VBox to the layout
        column_layout.addLayout(chassis_density_vbox)

        # Add the actual gradient but add it to a VBox to be cheeky and set stretch at the bottom
        gradient_vbox = QVBoxLayout()
        gradient_vbox.addWidget(self._gradient_widget, 15)
        column_layout.addLayout(gradient_vbox, 3)

        # Add Wheel Density stufff
        wheel_density_vbox = QVBoxLayout()
        wheel_density_vbox.setContentsMargins(0, 0, 0, 0)
        min_wheel_density = get_boxcar_constant('min_wheel_density')
        max_wheel_density = get_boxcar_constant('max_wheel_density')
        wheel_range = max_wheel_density - min_wheel_density
        num_slices = 10  # Number of sections to add (I'm keeping it the same as the chassis density for now)
        wheel_slices = [
            (wheel_range) / (num_slices - 1) * i + min_wheel_density
            for i in range(num_slices)
        ]

        for i, wheel_slice in enumerate(wheel_slices):
            label = QLabel()
            text = '- {:.2f}'.format(wheel_slice)
            label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
            label.setText(text)
            wheel_density_vbox.addWidget(label)

        # Add the VBox to the layout
        column_layout.addLayout(wheel_density_vbox)

        # Add column_layout to the layout
        self.layout.addLayout(column_layout, 5)
        self.layout.addStretch(1)

        # Add the boxcar settings
        self._add_boxcar_settings()

        # Set overall layout
        self.setLayout(self.layout)

    def resizeEvent(self, event):
        self._create_linear_gradient()
        return super().resizeEvent(event)

    def _create_linear_gradient(self) -> None:
        self._gradient_widget.setAutoFillBackground(True)
        gradient = QLinearGradient()
        gradient.setStart(self._gradient_widget.width(), 0.0)
        gradient.setFinalStop(self._gradient_widget.width(),
                              self._gradient_widget.height())

        # Create gradient stops
        stops = []
        i = 0.0
        for i in range(360):
            stop_location = i / 360.0
            color = QColor.fromHsvF(i / 360.0, 1.0, 0.8)
            stop = (stop_location, color)
            stops.append(stop)

        gradient.setStops(stops)

        # Add Gradient to the rectangle
        brush = QtGui.QBrush(gradient)
        palette = self._gradient_widget.palette()
        palette.setBrush(self._gradient_widget.backgroundRole(), brush)
        self._gradient_widget.setPalette(palette)

    def _add_boxcar_settings(self) -> None:
        label_boxcar_settings = QLabel()
        label_boxcar_settings.setFont(font_bold)
        label_boxcar_settings.setText('Boxcar Settings')
        label_boxcar_settings.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.layout.addWidget(label_boxcar_settings)

        # Make small note
        small_note = QLabel()
        small_note.setFont(QtGui.QFont('Times', 8, QtGui.QFont.Normal))
        small_note.setText('*indicates it is part of the Genetic Algorithm')
        small_note.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.layout.addWidget(small_note)

        self._add_bc_row_entry('floor_tile_height', 'Tile Height:', font_bold,
                               normal_font)
        self._add_bc_row_entry('floor_tile_width', 'Tile Width:', font_bold,
                               normal_font)
        self._add_bc_row_entry('max_floor_tiles', 'Num Floor Tiles:',
                               font_bold, normal_font)
        self._add_bc_row_entry('floor_creation_type', 'Floor Type:', font_bold,
                               normal_font)
        # Ramp specific stuff
        if get_boxcar_constant('floor_creation_type') == 'ramp':
            # Is the ramp constant?
            if get_boxcar_constant('ramp_constant_angle'):
                self._add_bc_row_entry('ramp_constant_angle',
                                       'Ramp Constant Angle:', font_bold,
                                       normal_font)
                self._add_bc_row_entry('ramp_constant_distance',
                                       'Ramp Distance:', font_bold,
                                       normal_font)
            # Otherwise it's increasing angle
            else:
                self._add_bc_row_entry('ramp_increasing_angle',
                                       'Ramp Increasing Angle:', font_bold,
                                       normal_font)
                self._add_bc_row_entry('ramp_start_angle', 'Start Angle:',
                                       font_bold, normal_font)
                self._add_bc_row_entry('ramp_increasing_type', 'Increase By:',
                                       font_bold, normal_font)
                self._add_bc_row_entry('ramp_max_angle', 'Max Ramp Angle:',
                                       font_bold, normal_font)
                self._add_bc_row_entry('ramp_approach_distance',
                                       'Approach Distance:', font_bold,
                                       normal_font)
            self._add_bc_row_entry('ramp_distance_needed_to_jump',
                                   'Jump Distance:', font_bold, normal_font)
        # Gaussian specific stuff
        elif get_boxcar_constant('floor_creation_type') == 'gaussian':
            self._add_bc_row_entry('gaussian_floor_seed', 'Seed:', font_bold,
                                   normal_font)
            self._add_bc_row_entry('tile_angle_mu', 'Tile Angle (mu):',
                                   font_bold, normal_font)
            self._add_bc_row_entry('tile_angle_std', 'Tile Andle (std):',
                                   font_bold, normal_font)
            self._add_bc_row_entry('tile_gaussian_denominator',
                                   'Angle Normalizer:', font_bold, normal_font)
            self._add_bc_row_entry('tile_gaussian_threshold', 'Max Numerator:',
                                   font_bold, normal_font)
        # Jagged specific stuff
        elif get_boxcar_constant('floor_creation_type') == 'jagged':
            angle_range = '-{:.2f}, {:.2f}'.format(
                get_boxcar_constant('jagged_increasing_angle'),
                get_boxcar_constant('jagged_decreasing_angle'))
            self._add_bc_row_entry(None,
                                   'Jagged Angle:',
                                   font_bold,
                                   normal_font,
                                   force_value=angle_range)
        else:
            raise Exception(
                'Unable to determine floor_creation_type "{}"'.format(
                    get_boxcar_constant('floor_creation_type')))
        self._add_bc_row_entry('car_max_tries', 'Car Max Tries:', font_bold,
                               normal_font)
        # Chassis Axis
        chassis_axis_range = '[{:.2f}, {:.2f})'.format(
            get_boxcar_constant('min_chassis_axis'),
            get_boxcar_constant('max_chassis_axis'))
        self._add_bc_row_entry(None,
                               '*Chassis Axis:',
                               font_bold,
                               normal_font,
                               force_value=chassis_axis_range)
        # Chassis Density
        chassis_density_range = '[{:.2f}, {:.2f})'.format(
            get_boxcar_constant('min_chassis_density'),
            get_boxcar_constant('max_chassis_density'))
        self._add_bc_row_entry(None,
                               '*Chassis Density:',
                               font_bold,
                               normal_font,
                               force_value=chassis_density_range)
        # Wheel Density
        wheel_density_range = '[{:.2f}, {:.2f})'.format(
            get_boxcar_constant('min_wheel_density'),
            get_boxcar_constant('max_wheel_density'))
        self._add_bc_row_entry(None,
                               '*Wheel Density:',
                               font_bold,
                               normal_font,
                               force_value=wheel_density_range)
        # Num Wheels
        num_wheels_range = '[{:.2f}, {:.2f}]'.format(
            get_boxcar_constant('min_num_wheels'),
            get_boxcar_constant('max_num_wheels'))
        self._add_bc_row_entry(None,
                               '*Num. Wheels:',
                               font_bold,
                               normal_font,
                               force_value=num_wheels_range)
        # Wheel Radius
        wheel_radius_range = '[{:.2f}, {:.2f})'.format(
            get_boxcar_constant('min_wheel_radius'),
            get_boxcar_constant('max_wheel_radius'))
        self._add_bc_row_entry(None,
                               '*Wheel Radius:',
                               font_bold,
                               normal_font,
                               force_value=wheel_radius_range)
        # Wheel motor wpeed
        # wheel_motor_speed_range = '[{:.2f}, {:.2f})'.format(
        #     get_boxcar_constant('min_wheel_motor_speed'),
        #     get_boxcar_constant('max_wheel_motor_speed')
        # )
        # self._add_bc_row_entry(None, '*Wheel Speed:', font_bold, normal_font, force_value=wheel_motor_speed_range)

        self._add_bc_row_entry('gravity', 'Gravity (x, y):', font_bold,
                               normal_font)
        self._add_bc_row_entry('fps', 'FPS:', font_bold, normal_font)

        widget = QWidget()
        widget.setLayout(self.boxcar_form)
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidget(widget)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll_area.setMaximumHeight(250)
        self.scroll_area.setWidgetResizable(False)

        vbox = QVBoxLayout()
        vbox.addWidget(self.scroll_area, 0)
        self.layout.addLayout(vbox, 0)  # @TODO: Adjust this

    def _add_bc_row_entry(self,
                          constant: str,
                          label_text: str,
                          label_font,
                          value_font,
                          alignment: Qt.AlignmentFlag = Qt.AlignLeft
                          | Qt.AlignVCenter,
                          force_value=None):
        _add_row_entry(self.boxcar_form, 'boxcar', constant, label_text,
                       label_font, value_font, alignment, force_value)
예제 #14
0
class Ui_insertusr(object):
    def setupUi(self, MainWindow):
        self.insertusr = QWidget(MainWindow)
        self.insertusr.setObjectName("insertusrWidget")
        self.insertusr.resize(1200, 590)
        self.insertusr.setGeometry(QtCore.QRect(0, 70, 1200, 590))
        jpeg = QtGui.QPixmap()
        jpeg.load("pictures/UserBg.png")
        palette1 = QtGui.QPalette()
        palette1.setBrush(self.insertusr.backgroundRole(), QtGui.QBrush(jpeg))
        self.insertusr.setPalette(palette1)
        self.insertusr.setAutoFillBackground(True)

        # self.label = QtWidgets.QLabel(self.insertusr)
        # self.label.setGeometry(QtCore.QRect(250, 120, 80, 20))
        # self.label.setObjectName("label")
        # self.label_2 = QtWidgets.QLabel(self.insertusr)
        # self.label_2.setGeometry(QtCore.QRect(250, 200, 80, 20))
        # self.label_2.setObjectName("label_2")
        # self.label_3 = QtWidgets.QLabel(self.insertusr)
        # self.label_3.setGeometry(QtCore.QRect(250, 280, 80, 20))
        # self.label_3.setObjectName("label_3")

        self.widget3 = QtWidgets.QWidget(self.insertusr)
        self.widget3.setGeometry(QtCore.QRect(375, 150, 450, 50))
        self.widget3.setStyleSheet("background-color: rgba(0,0,0,0);")
        self.widget3.setObjectName("widget3")
        self.roomNoEdit = QtWidgets.QLineEdit(self.widget3)
        self.roomNoEdit.setGeometry(QtCore.QRect(0, 0, 450, 50))
        self.roomNoEdit.setStyleSheet(
            "border-color: rgba(0, 0, 0, 0);font: 11pt 'Adobe Hebrew';")
        self.roomNoEdit.setStyleSheet(
            "QLineEdit{color:rgb(0,204,255);font: 75 12pt \"微软雅黑\";}")
        self.roomNoEdit.setObjectName("roomNoEdit")

        self.widget = QtWidgets.QWidget(self.insertusr)
        self.widget.setGeometry(QtCore.QRect(375, 225, 450, 50))
        self.widget.setStyleSheet("background-color: rgba(0,0,0,0);")
        self.widget.setObjectName("widget")
        self.nameEdit = QtWidgets.QLineEdit(self.widget)
        self.nameEdit.setGeometry(QtCore.QRect(0, 0, 450, 50))
        self.nameEdit.setStyleSheet(
            "border-color: rgba(0, 0, 0, 0);font: 11pt 'Adobe Hebrew';")
        self.nameEdit.setStyleSheet(
            "QLineEdit{color:rgb(0,204,255);font: 75 12pt \"微软雅黑\";}")
        self.nameEdit.setObjectName("lineEdit")

        self.widget2 = QtWidgets.QWidget(self.insertusr)
        self.widget2.setGeometry(QtCore.QRect(375, 300, 450, 50))
        self.widget2.setStyleSheet("background-color: rgba(0,0,0,0);")
        self.widget2.setObjectName("widget2")
        self.pwdEdit = QtWidgets.QLineEdit(self.widget2)
        self.pwdEdit.setGeometry(QtCore.QRect(0, 0, 450, 50))
        self.pwdEdit.setObjectName("pwdEdit")
        self.pwdEdit.setStyleSheet(
            "border-color: rgba(0, 0, 0, 0);font: 11pt 'Adobe Hebrew';")
        self.pwdEdit.setStyleSheet(
            "QLineEdit{color:rgb(0,204,255);font: 75 12pt \"微软雅黑\";}")

        self.ensureButton = QtWidgets.QPushButton(self.insertusr)
        self.ensureButton.setGeometry(QtCore.QRect(475, 400, 250, 50))
        self.ensureButton.setObjectName("ensureButton")
        self.ensureButton.setStyleSheet(
            "QPushButton{border-style:outset;border-radius: 10px;border-color: beige;font: bold 14px;}"
            "QPushButton{background-image: url(pictures/insertuserButton.png);}"
            "QPushButton:hover{background-image: url(pictures/insertuserButton2.png);}"
            "QPushButton:pressed{background-image: url(pictures/insertuserButton3.png);}"
        )
        self.ensureButton.clicked.connect(self.insertUser)

        self.retranslateUi(self.insertusr)
        QtCore.QMetaObject.connectSlotsByName(self.insertusr)

    def retranslateUi(self, insertusr):
        _translate = QtCore.QCoreApplication.translate
        insertusr.setWindowTitle(_translate("insertusr", "Form"))
        # self.label.setText(_translate("insertusr", "房间号:"))
        # self.label_2.setText(_translate("insertusr", "用户名:"))
        # self.label_3.setText(_translate("insertusr", "身份证号:"))
        # self.ensureButton.setText(_translate("insertusr", "确认"))

    def insertUser(self):
        # 取输入的用户名与密码
        roomNo = self.roomNoEdit.text()
        userName = self.nameEdit.text()
        passwd = self.pwdEdit.text()

        # 调用控制器的登录认证函数
        controller = M_insertUserController.InsertUserController()
        print(roomNo, userName, passwd)
        message = controller.insert(roomNo, userName, passwd)

        # 根据认证结果弹窗,执行下一步
        Message = QMessageBox()  # 一个消息框
        # 消息框的类型(内置了五种好像)(本体,标题,正文,按键组)
        QMessageBox.information(Message, "Message", message, QMessageBox.Ok)
        self.roomNoEdit.clear()
        self.nameEdit.clear()
        self.pwdEdit.clear()
예제 #15
0
    def InitWindowGrid(self):

        self.timer = QTimer(self)
        self.timer.setSingleShot(False)
        self.timer.setInterval(constants.DEF_TIMEOUT / 100)
        self.timer.timeout.connect(self.signal)

        h_layout_main = QHBoxLayout()
        h_right_layout = QHBoxLayout()
        v_right_layout = QVBoxLayout() # правый макет с элементами управления

        start_button = QPushButton('Start', self)
        start_button.clicked.connect(self.start_timer)

        stop_button = QPushButton('Stop', self)
        stop_button.clicked.connect(self.stop_timer)

        h_right_layout.addWidget(start_button)
        h_right_layout.addWidget(stop_button)

        gr_layout = QGridLayout()
        gr_layout.setSpacing(20)
        gr_layout.addWidget(QWidget())

        self.lcd = QLabel(f'Кол-во эл.: {self.count_bar_items}', self)
        self.lcd.setStyleSheet('color: white')

        self.lb_speed = QLabel(f'Шаг каждые: {constants.DEF_TIMEOUT / 1000}(мс)')
        self.lb_speed.setStyleSheet('color: white')

        sld = QSlider(Qt.Horizontal, self)
        sld.valueChanged.connect(self.slider_value_changed)
        sld.setMinimum(1)
        sld.setMaximum(1000)
        sld.setSingleStep(1)
        sld.setValue(100)

        sld_speed = QSlider(Qt.Horizontal, self)
        sld_speed.valueChanged.connect(self.set_timer_interval)
        sld_speed.setMinimum(1)
        sld_speed.setMaximum(100000)
        sld_speed.setSingleStep(1)
        sld_speed.setValue(constants.DEF_TIMEOUT)

        v_right_layout.addLayout(h_right_layout)
        v_right_layout.addWidget(self.lcd)
        v_right_layout.addWidget(sld)

        q_grid_boxes = QGridLayout()
        row, col = 0, 0
        for i, sub_class in enumerate(self.get_alghoritms()):
            ch_box = QCheckBox(sub_class.NAME, self)
            ch_box.setStyleSheet('color: white')
            self.selected_algh[sub_class.NAME] = False
            ch_box.stateChanged.connect(self.add_q_box_signal(i, sub_class.NAME))

            if col >= 2:
                row += 1
                col = 0
            q_grid_boxes.addWidget(ch_box, row, col)
            col += 1

        v_right_layout.addLayout(q_grid_boxes)
        v_right_layout.addWidget(self.lb_speed)
        v_right_layout.addWidget(sld_speed)
        v_right_layout.addWidget(QWidget(), 5)


        h_layout_main.addLayout(gr_layout, 5)
        h_layout_main.addLayout(v_right_layout, 1)

        widget = QWidget()
        palette = widget.palette()
        widget.setAutoFillBackground(True)
        palette.setColor(widget.backgroundRole(), Qt.black)
        widget.setPalette(palette)
        widget.setLayout(h_layout_main)
        self.main_layout = gr_layout
        self.setCentralWidget(widget)
예제 #16
0
class TimePlotGui(QWidget):
    """ 
    QWidget collects and displays data in line plot item in real time
    
    
    Parameters
    ----------
    parent : QWidget
        PyQt handle to introduce inheritance dependence
    window : QWidget, QMainWindow
        specifies QWidget in which TimePlotgui will be placed
    devices : lst, DeviceWrapper object
        DeviceWrapper objects handle hardware communication 
    folder_filename : str
        directory where  plot settings and plot data will be stored
    sampling_latency : float
        time delay between two sample acquistion
    
    
    """

    DEFAULT_DATA_FILENAME = 'stored_data.json'

    start_signal = QtCore.pyqtSignal()
    stop_signal = QtCore.pyqtSignal()
    pause_signal = QtCore.pyqtSignal()
    restart_signal = QtCore.pyqtSignal()

    # =======================================================================
    # decorator
    # =======================================================================

    def disable_fft_and_log_mode(func):
        """function wrapper to temporarily disable FFT and log mode.
        
        This function can be used to wrap function which require FFT and log 
        mode to be temporarily disabled. Examples of this are 
        ``save_all_data()`` and ``update_datapoint()``.
        
        
        Return
        ------
        func
            function wrapper which disables FFT and log mode while given 
            function is executed. restores previous FFT and log mode again
            before finish.
        
        """
        @wraps(func)
        def wrapper(tpg, *args, **kwargs):
            # print("inhere")
            # print('args: ', args)
            # print('args: ', kwargs)

            # save current state
            frequency_state = tpg.frequency_state
            x_log_check = tpg.context_menu.x_log_check.isChecked()
            y_log_check = tpg.context_menu.y_log_check.isChecked()

            # disable FFT, x log, and y log state
            tpg.graphItem.ctrl.fftCheck.setChecked(False)
            tpg.context_menu.x_log_check.setChecked(False)
            tpg.context_menu.y_log_check.setChecked(False)

            # execute function
            rtrn = func(tpg, *args, **kwargs)

            # reinstate FFT, x log, and y log state
            tpg.graphItem.ctrl.fftCheck.setChecked(frequency_state)
            tpg.context_menu.x_log_check.setChecked(x_log_check)
            tpg.context_menu.y_log_check.setChecked(y_log_check)
            # print("still inhere")
            return rtrn

        return wrapper

    # =======================================================================
    #
    # =======================================================================

    def __init__(self,
                 parent=None,
                 window=None,
                 devices=None,
                 folder_filename=None,
                 sampling_latency=.005):
        super(TimePlotGui, self).__init__(parent=parent)
        self._create_absolute_time_stamp()
        self.dev_lst = self._check_devices_type(devices)
        self.dev_num = len(self.dev_lst)
        self.sampling_latency = sampling_latency

        # ===============================
        # Allow for coercion of data and settings to the same number of lines
        # ===============================
        self.started = False
        self.start_button_counter = 0
        self.previous_x_max = None
        self.previous_y_max = None
        # ===============================
        # setup gui and worker thread
        # ===============================
        self._init_settings(folder_filename)
        self._init_ui(window, self.dev_lst)
        self._init_multi_worker_thread(self.dev_lst)

    def _init_ui(self, mainwindow, dev_lst):
        """ Creates the ui layout and initializes all the necessary QWidget 
        components
        
        Parameter
        ---------
        mainwindow : QMainWindow, QWidget
            QWidget which will be used as central_widget for TimePlotGui
        dev_lst : lst
            lst of DeviceWrapper object used to collect data
            
            
        """
        # =====================================================================
        # Creates and configures central widget for window
        # =====================================================================
        self.central_wid = QWidget(mainwindow)
        self._set_central_wid_properties()
        # =====================================================================
        # control panel - initializes layout item to put widgets
        # =====================================================================
        self.graphics_layout = QGridLayout()
        # =====================================================================
        # control buttons - Non-plot widgets (stop/start buttons and spacers)
        # =====================================================================
        self.playBtn = QPushButton()
        self.playBtn.setFixedSize(QSize(30, 30))
        self.playBtn.setSizePolicy(
            QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        points = [
            QPoint(0, 0),
            QPoint(0, self.playBtn.height()),
            QPoint(self.playBtn.width(),
                   self.playBtn.height() / 2)
        ]
        self.playBtn.setMask(QRegion(QPolygon(points)))
        self.playBtn.setStyleSheet("background-color: rgb(120,120,120);")

        self.stopBtn = QPushButton()
        self.stopBtn.setFixedSize(QSize(110, 30))
        self.stopBtn.setSizePolicy(
            QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        points = [
            QPoint((self.stopBtn.width() + 50) / 2, 0),
            QPoint((self.stopBtn.width() + 50) / 2, self.stopBtn.height()),
            QPoint(self.stopBtn.width(), self.stopBtn.height()),
            QPoint(self.stopBtn.width(), 0)
        ]
        self.stopBtn.setMask(QRegion(QPolygon(points)))
        self.stopBtn.setStyleSheet("background-color: rgb(120,120,120);")

        self.blankWidget = QWidget()
        self.blankWidget.setFixedSize(QSize(500, 30))

        self.blankWidget2 = QWidget()
        self.blankWidget2.setFixedSize(QSize(30, 30))
        # =====================================================================
        # Initialize the plot
        # =====================================================================
        self._init_plot(dev_lst)
        # =====================================================================
        # Add Widgets to layout, including the Plot itself. Note that the order
        # in which these are added matters because several widgets overlap.
        # =====================================================================
        self.graphics_layout.addWidget(self.blankWidget, 0, 2)
        self.graphics_layout.addWidget(self.blankWidget2, 0, 1)
        self.graphics_layout.addWidget(self.graphWidget, 0, 0, 5, 4)
        self.graphics_layout.addWidget(self.stopBtn, 0, 0)
        self.graphics_layout.addWidget(self.playBtn, 0, 0)

        # =====================================================================
        # control buttons - connections
        # =====================================================================
        self.playBtn.clicked.connect(self.save_line_settings)
        self.playBtn.clicked.connect(self.thread_status_changed)
        self.playBtn.clicked.connect(self.start_thread)
        self.stopBtn.clicked.connect(self.pause_thread)
        # ============================================================
        # Assign layout widget to window
        # ============================================================
        self.central_wid.setLayout(self.graphics_layout)

    def _init_plot(self, dev_lst):
        """Initializes plot item by customizing corresponding Widgets
        
        This function initializes the main plot item by customizing the 
        ``pyqtgraph`` objects like ``PlotWidget``, ``PlotItem``, and 
        ``ViewBox``.
        
        
        Parameter
        ---------
        dev_lst : lst
            lst of DeviceWrapper object used to collect data
        
        """

        try:
            self.viewbox = ViewBoxV2()
            self.graphItem = pg.PlotItem(viewBox=self.viewbox)
            self.axis_item = TimeAxisItem(
                orientation='bottom',
                t0=self.t0,
                relative_time=self.settings['relative_timestamp'])
            self.graphWidget = pg.PlotWidget(
                axisItems={'bottom': self.axis_item}, plotItem=self.graphItem)
        except:
            print(
                "ERROR with custom viewbox class. 'Except' case run instead.")
            self.graphWidget = pg.PlotWidget(
                axisItems={'bottom': self.axis_item})
            self.graphItem = self.graphWidget.getPlotItem()
            self.viewbox = self.graphItem.getViewBox()
        # ===============================
        # Enable Automatic Axis Label Updates
        # ===============================
        self.graphItem.ctrl.fftCheck.stateChanged.connect(
            self.change_label_state)
        # ===============================
        # initlialize data lines
        # ===============================
        self._init_data_table(dev_lst)
        self._align_time_stamps()
        # ===============================
        # Customize the context menu
        # ===============================
        menu = self.graphItem.getMenu()
        viewbox_menu = self.graphItem.getViewBox().getMenu(True)
        self.context_menu = TimePlotContextMenu(menu, viewbox_menu, self)
        # self._modify_context_menu()
        # ===============================
        # customize plot settings with stored values
        # ===============================
        self.set_custom_settings()

    def _init_data_table(self, dev_lst, new_data=None):
        """initialize data table by populating it with data items
        
        data items are initialized from scratch or loaded from file
        
        Parameter
        ---------
        dev_lst : lst
            lst of DeviceWrapper object used to collect data
        new_data :  str
            data filename if new data is loaded. Used inside Open finder
            
        """
        self.data_table = {}

        id_nr = 0
        while True:
            data_item = self._create_data_item(id_nr)
            if new_data is None:
                data_item.recall_data(self.data_fn)
            else:
                data_item.recall_data(new_data)

            if len(data_item.get_time_data()) == 0:
                break

            self._add_data_item(id_nr, data_item)
            id_nr += 1

    def _init_settings(self, folder_filename):
        """initialize plot settings
        
        Settings are initialized by loading from file or from default values. 
        To initialize the plot settings a PlotItemSettings object is created.
        
        Parameters
        ----------
        folder_filename : str
            path to settings filename
            
        
        """
        self.plot_item_settings = PlotItemSettings(
            number_of_lines=self.dev_num, folder_filename=folder_filename)
        self.settings = self.plot_item_settings.settings
        self.data_fn = os.path.join(self.plot_item_settings.folder_filename,
                                    self.DEFAULT_DATA_FILENAME)
        return

    def _check_devices_type(self, devices):
        """checks devices and reformats if necessary
        
        Function is used to allow TimePlotGui initialization with either one 
        devicewrapper object or a list of devicewrapper objects. Function 
        returns a list of device wrappers
        
        Parameters
        ----------
        devices : DeviceWrapper object or list of DeviceWrapper objects
            DeviceWrapper object handle hardware communication
            
        Returns
        -------
        lst
            list of DeviceWrapper object
        
        Raises
        ------
        TimePlotGuiException
            if devices contains variables which are not of type DeviceWrapper
        
        """
        err_msg = """
        Given devices are not of type DeviceWrapper. 
        Make sure that elemnts in devices are DeviceWrapper and initialize 
        TimePlotGui again.
        """

        if type(devices) is DeviceWrapper:
            return [devices]
        if all([type(d) is DeviceWrapper for d in devices]):
            return devices
        else:
            raise TimePlotGuiException(err_msg)

    def _create_data_item(self, id_nr):
        """initializes and returns a ``TimePlotDataItem`` object
        
        Parameter
        ---------
        id_nr : int
            reference number of data item.
            
        """
        data_item = TimePlotDataItem(data_fn=self.data_fn,
                                     id_nr=id_nr,
                                     absolute_time=self.t0)
        return data_item

    def _add_data_item(self, id_nr, data_item):
        """add data_item to ``data_table`` and to plot item
        
        Parameter
        ---------
        id_nr : int
            number is used as id reference in data_table
        data_item : TimePlotDataItem object
            represents one data line in the plot
            
        """
        self.data_table.update({id_nr: data_item})
        self.graphItem.addItem(data_item.get_plot_data_item())

    def _remove_data_item(self, id_nr):
        """add data_item to data_table and to plot item
        
        Parameter
        ---------
        id_nr : int
            number is used as id reference in data_table
            
        """
        self.graphItem.removeItem(self.data_table[id_nr].get_plot_data_item())
        self.data_table.pop(id_nr)

    def _create_absolute_time_stamp(self):
        self.t0 = time.time()

    def reset_absolute_time_stamp(self):
        self.t0 = time.time()

    def _align_time_stamps(self):
        """compares and aligns time stamps between TimePlotGui and data_items"""

        if not hasattr(self, 'data_table'):
            raise TimePlotGuiException(
                'data_table variable not present. Call init_data_items() first'
            )

        # define the TimePlotGui absolute_time to be the earliest time stemp present
        t0_lst = [
            data_item.absolute_time for data_item in self.data_table.values()
        ]
        self.t0 = min(t0_lst + [self.t0])

        # shift times in data_item object in respect to TimePlotGui absolute_time
        for data_item in self.data_table.values():
            if not np.isclose(self.t0, data_item.absolute_time, rtol=1e-3):
                dt = data_item.absolute_time - self.t0
                t, y = data_item.get_data()
                data_item.set_data(t + dt, y)
                data_item.absolute_time = self.t0

    def thread_status_changed(self):
        self.started = not self.started
        self.resize_line_settings()
        self.context_menu._add_line_settings_menu()

    def resize_line_settings(self):
        """resizes line settings to make number of data object present
        
        If thread is started the number of data objects corresponds to number 
        of devices concted. If thread does not run, number of data objects
        is given by length of data_table
        
        """
        if self.started:
            self.coerce_same_length(data_length=len(self.dev_lst))
            self.resize_data_table()
        else:
            self.coerce_same_length(data_length=len(self.data_table))
        self.update_line_settings()

    def resize_data_table(self):
        """resizes data table to make number of data object match with devices
        connected
        
        Function adds or removes data_items from data table as long as number 
        of data items does not match to number of devices connceted to 
        TimePlotGui
        
        """
        len_data_table = len(self.data_table)
        while self.dev_num != len_data_table:
            if self.dev_num > len_data_table:
                id_nr = len_data_table
                data_item = self._create_data_item(id_nr)
                self._add_data_item(id_nr, data_item)
            else:
                self._remove_data_item(id_nr)
            len_data_table = len(self.data_table)

    def coerce_same_length(self, data_length):
        """changes number of line settings until it matches data_length.
        
        This function is required to adjust number of line settings to actual 
        data present. Here the data_length variable is supposed to provide the 
        information on how many data items are present in TimePlotGui. This
        can either be the number of devices connected for data acquisition or 
        the number of data items in the data table.
        
        Parameter
        ---------
        data_length : int
            lenght of data objects present in  TimePlotGui class. This can be 
            either number of devices connected or number of data_items in 
            data_table
        
        """
        n_lines = self.plot_item_settings.get_nr_lines()
        while data_length != n_lines:
            if data_length > n_lines:
                self.plot_item_settings.add_line()
            else:
                self.plot_item_settings.remove_line()
            n_lines = self.plot_item_settings.get_nr_lines()

    def set_custom_settings(self):
        """updates PlotItem settings with values from settings dictionary
        """

        # Log mode
        self.graphItem.setLogMode(x=self.settings['xscalelog'],
                                  y=self.settings['yscalelog'])

        # grid lines
        self.graphItem.showGrid(x=self.settings['xgridlines'],
                                y=self.settings['ygridlines'],
                                alpha=self.settings['gridopacity'])

        # line settings
        self.update_line_settings()

        # autopan
        self.viewbox.setAutoPan(x=self.settings['autoPan'])

        # axis limits
        self.viewbox.setRange(xRange=self.settings['xlim'],
                              yRange=self.settings['ylim'])

        # autorange
        self.viewbox.enableAutoRange(x=self.settings['xautorange'],
                                     y=self.settings['yautorange'])

        # auto_clear
        self.context_menu.data_options.automatic_clear_checkbox.setChecked(
            self.settings['auto_clear_data'])

        # zoom
        self.viewbox.setMouseEnabled(x=self.settings['x_zoom'],
                                     y=self.settings['y_zoom'])

        # mouse mode
        if self.settings['mouseMode'] == 1:
            self.viewbox.setLeftButtonAction(mode='rect')
        else:
            self.viewbox.setLeftButtonAction(mode='pan')

        # frequency state
        self.frequency_state = self.settings['frequency_state']
        self.graphItem.ctrl.fftCheck.setChecked(self.frequency_state)

        # autosave
        self.set_all_autosave(self.settings['do_autosave'])
        self.set_all_autosave_nr(self.settings['autosave_nr'])

        # time stamp
        self.change_time_markers(self.settings['relative_timestamp'])

        # labels
        self.update_plot_labels()

    def update_line_settings(self):
        """updates PlotDataItem settings with values from settings dictionary
        """
        for line_nr, time_data_item in self.data_table.items():
            pdi = time_data_item.get_plot_data_item()
            line_setting = self.settings['line_settings'][str(line_nr)]

            pdi.setAlpha(alpha=line_setting['line_alpha'], auto=False)
            pdi.setPen(
                pg.mkPen(width=line_setting['line_width'],
                         color=line_setting['line_color']))
            pdi.setFftMode(self.settings['frequency_state'])

    def update_plot_labels(self):
        """updates plot labels and title corresponding to currently set fft 
        mode.
        """
        if self.frequency_state:
            self.set_frequency_labels()
        else:
            self.set_time_labels()

    def change_label_state(self):
        """changes fft label and updates plot labels accordingly"""
        self.frequency_state = self.graphItem.ctrl.fftCheck.isChecked()
        self.update_plot_labels()

    def set_frequency_labels(self):
        """sets title, xlabel, and ylabel settings in PlotItem object if
        TimePlotGui is in FFT mode

        """
        labels = self.get_axis_labels()
        labels.update({
            'title': 'Fourier Transform of ' + labels['title'],
            'x_label': 'Frequency [Hz]',
            'y_label': 'Amplitude'
        })
        self._set_labels(**labels)

    def set_time_labels(self):
        """sets title, xlabel, and ylabel settings in PlotItem object if
        TimePlotGui is not in FFT mode

        """
        labels = self.get_axis_labels()
        self._set_labels(**labels)

    def _set_labels(self, title, title_font_size, title_font_color, x_label,
                    x_font_size, x_font_color, y_label, y_font_size,
                    y_font_color):
        """sets title, xlabel, and ylabel settings in PlotItem object"""
        self.graphItem.setTitle(title,
                                color=title_font_color,
                                size=title_font_size)
        self.graphItem.setLabel(
            'left', y_label, **{
                'color': y_font_color,
                'font-size': y_font_size
            })
        self.graphItem.setLabel(
            'bottom', x_label, **{
                'color': x_font_color,
                'font-size': x_font_size
            })
        return

    def get_axis_labels(self):
        """returns dictionary with formated xlabel, ylabel, and title settings

        Formating of the displayed xlabel, ylabel, and title strings is defined
        in this function. The *axis_data_type* and *axis_unit* stored in the
        settings dictionary are used to construct the x and ylabel strings

        """
        tmp = self.settings['labels'].copy()

        # concatenate label strings
        if tmp['x_axis_unit'] == '':
            x_label = tmp['x_axis_data_type']
        else:
            x_label = '{} [{}]'.format(tmp['x_axis_data_type'],
                                       tmp['x_axis_unit'])

        if tmp['y_axis_unit'] == '':
            y_label = tmp['y_axis_data_type']
        else:
            y_label = '{} [{}]'.format(tmp['y_axis_data_type'],
                                       tmp['y_axis_unit'])

        labels = {
            'x_label': x_label,
            'y_label': y_label,
            'title': tmp['title_text']
        }

        # reformat font_size values
        labels.update({
            'x_font_size': str(tmp['x_axis_font_size']) + 'pt',
            'y_font_size': str(tmp['y_axis_font_size']) + 'pt',
            'title_font_size': str(tmp['title_font_size']) + 'pt'
        })

        # extract color values
        labels.update({
            'x_font_color': tmp['x_axis_font_color'],
            'y_font_color': tmp['y_axis_font_color'],
            'title_font_color': tmp['title_font_color']
        })

        return labels

    def save_current_settings(self):
        """updates settings dictionary from settings in PloIem and saves then
        to JSON file
        """
        self.save_line_settings()
        viewboxstate = self.viewbox.getState()
        settings = {
            # log mode
            'xscalelog':
            self.graphItem.ctrl.logXCheck.isChecked(),
            'yscalelog':
            self.graphItem.ctrl.logYCheck.isChecked(),
            # grid lines
            'xgridlines':
            self.graphItem.ctrl.xGridCheck.isChecked(),
            'ygridlines':
            self.graphItem.ctrl.yGridCheck.isChecked(),
            'gridopacity':
            self.graphItem.ctrl.gridAlphaSlider.value() / 255,
            # autopan
            'autoPan':
            viewboxstate['autoPan'][0],
            # axis limits
            'xlim':
            viewboxstate['targetRange'][0],
            'ylim':
            viewboxstate['targetRange'][1],
            # autorange
            'xautorange':
            viewboxstate['autoRange'][0],
            'yautorange':
            viewboxstate['autoRange'][1],
            # auto clear
            'auto_clear_data':
            self.context_menu.data_options.automatic_clear_checkbox.isChecked(
            ),
            # zoom
            'x_zoom':
            viewboxstate['mouseEnabled'][0],
            'y_zoom':
            viewboxstate['mouseEnabled'][1],
            # mouse mode
            'mouseMode':
            viewboxstate['mouseMode'],
            # frequency
            'frequency_state':
            self.graphItem.ctrl.fftCheck.isChecked(),
            # autosave
            'do_autosave':
            self.context_menu.data_options.autosave_checkbox.isChecked(),
            'autosave_nr':
            self.context_menu.data_options.autosave_nr.value(),
            # time stamp

            # labels
            'labels':
            self.settings['labels'],
            # auto visible only
            'autoVisibleOnly_x':
            self.context_menu.autoVisibleOnly_x.isChecked(),
            'autoVisibleOnly_y':
            self.context_menu.autoVisibleOnly_y.isChecked(),
            # alpha
            'plotalpha':
            self.graphItem.alphaState(),
        }
        self.plot_item_settings.save_settings(**settings)

    def restore_default_settings(self):
        """restores default plot settings and deletes the settings file
        
        This function deletes the settings file and restores the default plot 
        settings from the DEFAULT_SETTINGS dictionary specified in the 
        PlotItemSettings class. The line settings are not restored.
        After restoring the default settings the context menu and the plot item
        are updated 
        
        """
        if path.exists(self.plot_item_settings.settings_filename):
            os.remove(self.plot_item_settings.settings_filename)

        self.plot_item_settings.restore_default_settings(
            keep_line_settings=True)
        self.resize_line_settings()

        self.context_menu.update_line_settings_context_menu()
        self.set_custom_settings()

    def clear_line_settings(self):
        """restores default line settings"""
        self.plot_item_settings.clear_all_line_settings()
        self.update_line_settings()
        self.context_menu.update_line_settings_context_menu()

    def open_finder(self):
        self.started = False
        data_fname, file_info = QFileDialog.getOpenFileName(
            self, 'Select data file', '~/', "JSON files (*.json)")
        if data_fname != '':
            settings_fname, file_info = QFileDialog.getOpenFileName(
                self, 'Select settings file', '~/', "JSON files (*.json)")
            if settings_fname != '':
                del self.plot_item_settings
                self.plot_item_settings = PlotItemSettings(
                    unusal_settings_file=settings_fname)
                self.settings = self.plot_item_settings.settings
            if data_fname is not None:
                self.clear_all_plot_data_items()
                self._init_data_table(self.dev_lst, new_data=data_fname)
                self.resize_line_settings()
                self.context_menu._add_line_settings_menu(self.data_table)
                self.set_custom_settings()
                # self.update_line_settings_context_menu()

    def set_local_ft_mode(self, local_ft_mode):
        """starts or stops the local FT mode depending on local fourier checkbox
        state
        """
        if local_ft_mode:
            if not self.graphItem.ctrl.fftCheck.isChecked():
                for dataitem in self.data_table.values():
                    dataitem.start_local_ft_mode()
            else:
                self.transform_menu.local_fourier.defaultWidget().layout(
                ).itemAt(1).widget().setChecked(
                    False
                )  # !! kehaus:  i think this would cause an erros since transform_menu os not attribute of time_plot_gui
                self.local_ft_error()
        else:
            for dataitem in self.data_table.values():
                dataitem.stop_local_ft_mode()
        return

    def clear_all_plot_data_items(self):
        """remove all PlotDataItems from PLotItem"""
        data_items = self.graphItem.listDataItems()
        for data_item in data_items:
            self.graphItem.removeItem(data_item)

    def save_data_settings(self):
        """save plot settings"""
        self.plot_item_settings.save_settings(
            auto_clear_data=self.context_menu.data_options.
            automatic_clear_checkbox.isChecked())

    def save_line_settings(self):
        """ """
        for line in self.context_menu.line_settings_menu.lines:
            line.update_line_settings()
        self.plot_item_settings.save_settings(
            line_settings=self.settings['line_settings'])

    @disable_fft_and_log_mode
    def store_all_data(self):
        """store all data objects

        Function stores data of every data_item by calling its store_data().
        To avoid problems when importing data the next time this function
        temporarily disables FFT, x log, and y log mode.

        """

        # # save current state
        # frequency_state = self.frequency_state
        # x_log_check = self.context_menu.x_log_check.isChecked()
        # y_log_check = self.context_menu.y_log_check.isChecked()

        # # disable FFT, x log, and y log mode
        # self.graphItem.ctrl.fftCheck.setChecked(False)
        # self.context_menu.x_log_check.setChecked(False)
        # self.context_menu.y_log_check.setChecked(False)

        # sava data
        if path.exists(self.data_fn):
            os.remove(self.data_fn)
        for data_item in self.data_table.values():
            data_item.store_data()

        # # restore FFT,x log, and y log states
        # self.graphItem.ctrl.fftCheck.setChecked(frequency_state)
        # self.context_menu.x_log_check.setChecked(x_log_check)
        # self.context_menu.y_log_check.setChecked(y_log_check)

    def change_time_markers(self, relative_time):
        self.axis_item.relative_time = relative_time

    def set_all_autosave(self, autosave):
        for data_item in self.data_table.values():
            data_item.do_autosave = autosave

    def set_all_autosave_nr(self, autosave_nr):
        for data_item in self.data_table.values():
            data_item.autosave_nr = autosave_nr

    def clear_all_data(self):
        """clears data in all data items by calling the corresponding clear()
        function

        """
        self.reset_absolute_time_stamp()
        for data_item in self.data_table.values():
            data_item.clear_data()
            data_item.reset_absolute_time(absolute_time=self.t0)

    def change_title(self):
        title, acccepted = QInputDialog.getText(self, 'Change title',
                                                'Enter new title:')
        if acccepted:
            self.settings['labels']['title_text'] = title
            self.update_plot_labels()

    def change_x_axis_label(self):
        axis_label, acccepted = QInputDialog.getText(self,
                                                     'Change x axis label',
                                                     'Enter new label:')
        if acccepted:
            self.settings['labels']['x_axis_data_type'] = axis_label
            self.update_plot_labels()

    def change_y_axis_label(self):
        axis_label, acccepted = QInputDialog.getText(self,
                                                     'Change y axis label',
                                                     'Enter new label:')
        if acccepted:
            self.settings['labels']['y_axis_data_type'] = axis_label
            self.update_plot_labels()

    def _set_central_wid_properties(self):
        """ """
        self.central_wid.setAutoFillBackground(True)
        p = self.central_wid.palette()
        p.setColor(self.central_wid.backgroundRole(), QtCore.Qt.darkGray)
        self.central_wid.setPalette(p)

    def _init_multi_worker_thread(self, devices):
        """initializes a worker thread for every devicewrapper in devices"""

        # set up QWaitCondition
        self.mutex_table = {idx: QMutex() for idx in range(len(devices))}
        self.cond_table = {
            idx: QWaitCondition()
            for idx in range(len(devices))
        }

        # set up the measurement engine
        self.worker_table = {}
        for idx, devicewrapper in enumerate(devices):
            worker = TimePlotWorker(devicewrapper,
                                    self.mutex_table[idx],
                                    self.cond_table[idx],
                                    id_nr=idx)

            # connect signal and slot
            worker.reading.connect(self.newReading)
            self.start_signal.connect(worker.start)
            self.stop_signal.connect(worker.stop)
            self.pause_signal.connect(worker.pause)
            self.restart_signal.connect(worker.restart)

            self.worker_table.update({idx: worker})

    def leaving_fft_mode(self):

        msg = """
        You are exiting FFT Transform mode and entering Time Dependence
        mode. If you would like to re-enter FFT Transform mode, you may
        do so from the context menu.
        """
        mode_change_popup = QMessageBox()
        mode_change_popup.setText(msg)
        mode_change_popup.setIcon(QMessageBox.Information)
        mode_change_popup.exec_()

    def local_ft_error(self):

        msg = """
        You are already in FFT mode. If you would like a local transform,
        please select a region in Time Dependence mode.
        """
        local_ft_error = QMessageBox()
        local_ft_error.setText(msg)
        local_ft_error.setIcon(QMessageBox.Information)
        local_ft_error.exec_()

    def y_autopan_warning(self):

        msg = """
        Auopanning functionality for the y axis is not supported.
        """
        y_autopan_warning = QMessageBox()
        y_autopan_warning.setText(msg)
        y_autopan_warning.setIcon(QMessageBox.Information)
        y_autopan_warning.exec_()

    def start_thread(self):
        """start data acquisition in worker thread

        if clauses handle the following causes: previous data are removed if
        autoclear button is checked. FFT mode is switched off and warning
        QMessage is emitted if previous data is removed.


        """
        if self.start_button_counter == 0:
            self.start_button_counter += 1
            is_checked = False
            if self.context_menu.data_options.automatic_clear_checkbox.isChecked(
            ):
                if self.graphItem.ctrl.fftCheck.isChecked():
                    is_checked = True
                self.graphItem.ctrl.fftCheck.setChecked(False)
                self.clear_all_data()
            self.start_signal.emit()
            if is_checked:
                self.leaving_fft_mode()
        else:
            self.restart_thread()

    def pause_thread(self):
        self.stop_thread()
        # self.pause_signal.emit()

    def restart_thread(self):
        self.restart_signal.emit()

    def stop_thread(self):
        # self.restart_signal.emit()
        # time.sleep(2)
        self.stop_signal.emit()

    @disable_fft_and_log_mode
    def update_datapoint(self, id_nr, val, time_val):
        """updates TimePlotDataItem object with corresponding id_nr
        
        To account for the fact that different lines are present, the 
        ``id_nr`` variable selects the right ``TimePlotdataItem`` object from
        the ``data_table`` and appends the values.
        
        Parameter
        ---------
        id_nr : int
            identifier for ``TimePlotDataItem`` in ``data_table``
        val : float
            collected value from measurement instrument
        time_val : float
            corresponding time stamp
        
        
        """

        # # save current state
        # frequency_state = self.frequency_state
        # x_log_check = self.context_menu.x_log_check.isChecked()
        # y_log_check = self.context_menu.y_log_check.isChecked()

        # # disable FFT, x log, and y log state
        # self.graphItem.ctrl.fftCheck.setChecked(False)
        # self.context_menu.x_log_check.setChecked(False)
        # self.context_menu.y_log_check.setChecked(False)

        # update value
        self.data_table[id_nr].append_value(val, time_val)

        # # reinstate FFT, x log, and y log state
        # self.graphItem.ctrl.fftCheck.setChecked(frequency_state)
        # self.context_menu.x_log_check.setChecked(x_log_check)
        # self.context_menu.y_log_check.setChecked(y_log_check)

    @QtCore.pyqtSlot(int, float, float)
    def newReading(self, id_nr, val, time_val):
        """updates plot by adding provided value to corresponding 
        ``TimePlotDataItem`` object """
        pg.QtGui.QApplication.processEvents()
        t0 = time.time()
        self.update_datapoint(id_nr, val, time_val)
        dt = self.sampling_latency - (time.time() - t0)
        if dt > 0:
            time.sleep(dt)
        else:
            time.sleep(0.001)
#        time.sleep(self.sampling_latency)
# necessary to avoid worker to freeze
        self.cond_table[id_nr].wakeAll()  # wake worker thread up
        return

    # def disable_fft_and_log_mode(func):
    #     def wrapper(tpg, *args, **kwargs):
    #         print("inhere")

    #         # save current state
    #         frequency_state = tpg.frequency_state
    #         x_log_check = tpg.context_menu.x_log_check.isChecked()
    #         y_log_check = tpg.context_menu.y_log_check.isChecked()

    #         # disable FFT, x log, and y log state
    #         tpg.graphItem.ctrl.fftCheck.setChecked(False)
    #         tpg.context_menu.x_log_check.setChecked(False)
    #         tpg.context_menu.y_log_check.setChecked(False)

    #         rtrn = getattr(tpg, func)(*args, **kwargs)

    #         # reinstate FFT, x log, and y log state
    #         tpg.graphItem.ctrl.fftCheck.setChecked(frequency_state)
    #         tpg.context_menu.x_log_check.setChecked(x_log_check)
    #         tpg.context_menu.y_log_check.setChecked(y_log_check)
    #         print("still inhere")
    #         return rtrn
    #     return wrapper

    # ========================================================================
    # closeEvent handling
    # ========================================================================
    def closeEvent(self, event, auto_accept=False):
        """
        By default, this function generates a pop-up confirming you want to 
        close the gui before running closing protocol. This pop-up can be 
        overridden with the auto_accept argument which is espcially useful in 
        avoiding mulitple redundant popups in large gui with multiple 
        TimePlotGui objects.
        """
        if not auto_accept:
            reply = QMessageBox.question(self, 'Message',
                                         "Are you sure to quit?",
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)

            if reply == QMessageBox.Yes:
                self.accept_close_event(event)
            else:
                event.ignore()
                return False
        else:
            self.accept_close_event(event)
            return True

    def accept_close_event(self, event):
        """runs standard protocol for closing the GUI properly"""
        self.save_current_settings()
        self.store_all_data()
        self.stop_thread()
        event.accept()
예제 #17
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-import sys
from PyQt5.QtWidgets import (QApplication, QWidget,QPushButton,
    QLineEdit)
from PyQt5 import QtCore,QtGui, QtWidgets
from PyQt5.QtGui import QPainter, QColor

import sys
from PyQt5.QtWidgets import QApplication, QWidget
app = QApplication(sys.argv)     #这里提供一个重要的进口,基本小部件位于Pyqt5.QtWidgets
w = QWidget()       #窗口小部件
w.resize(250, 250)       #调整部件大小
w.move(300, 300)         #移动部件位置   坐标为(300, 300)
w.setWindowTitle('The first Program')
image = QtGui.QPixmap()
image.load(r"/Users/mohaitao/Desktop/pic1.jpg")
palette1 = QtGui.QPalette()
palette1.setBrush(w.backgroundRole(), QtGui.QBrush(image)) #背景图片
w.setPalette(palette1)
w.setAutoFillBackground(True)

w.show()
sys.exit(app.exec_())
예제 #18
0
파일: pyEfis_v1.py 프로젝트: c310j/pyEfis
    def setupUi(self, MainWindow, test):
        MainWindow.setObjectName("PFD")
        MainWindow.resize(config.screenSize[0], config.screenSize[1])

        w = QWidget(MainWindow)
        w.setGeometry(0, 0, config.screenSize[0], config.screenSize[1])

        p = w.palette()
        if config.screenColor:
            p.setColor(w.backgroundRole(), QColor(config.screenColor))
            w.setPalette(p)
            w.setAutoFillBackground(True)
        instWidth = config.screenSize[0] - 410
        instHeight = config.screenSize[1] - 200
        a = ai.AI(w)
        a.resize(instWidth, instHeight)
        a.move(100, 100)

        alt_tape = altimeter.Altimeter_Tape(w)
        alt_tape.resize(100, instHeight)
        alt_tape.move(instWidth + 100, 100)

        as_tape = airspeed.Airspeed_Tape(w)
        as_tape.resize(100, instHeight)
        as_tape.move(0, 100)

        head_tape = hsi.DG_Tape(w)
        head_tape.resize(instWidth, 100)
        head_tape.move(100, instHeight + 100)

        map = gauges.RoundGauge(w)
        map.name = "MAP"
        map.decimalPlaces = 1
        map.lowRange = 0.0
        map.highRange = 30.0
        map.highWarn = 28.0
        map.highAlarm = 29.0
        map.resize(200, 100)
        map.move(w.width() - 200, 100)

        rpm = gauges.RoundGauge(w)
        rpm.name = "RPM"
        rpm.decimalPlaces = 0
        rpm.lowRange = 0.0
        rpm.highRange = 2800.0
        rpm.highWarn = 2600.0
        rpm.highAlarm = 2760.0
        rpm.resize(200, 100)
        rpm.move(w.width() - 200, 0)
        op = gauges.HorizontalBar(w)
        op.name = "Oil Press"
        op.units = "psi"
        op.decimalPlaces = 1
        op.lowRange = 0.0
        op.highRange = 100.0
        op.highWarn = 90.0
        op.highAlarm = 95.0
        op.lowWarn = 45.0
        op.lowAlarm = 10.0
        op.resize(190, 75)
        op.move(w.width() - 200, 220)
        op.value = 45.2

        ot = gauges.HorizontalBar(w)
        ot.name = "Oil Temp"
        ot.units = "degF"
        ot.decimalPlaces = 1
        ot.lowRange = 160.0
        ot.highRange = 250.0
        ot.highWarn = 210.0
        ot.highAlarm = 230.0
        ot.lowWarn = None
        ot.lowAlarm = None
        ot.resize(190, 75)
        ot.move(w.width() - 200, 300)
        ot.value = 215.2

        fuel = gauges.HorizontalBar(w)
        fuel.name = "Fuel Qty"
        fuel.units = "gal"
        fuel.decimalPlaces = 1
        fuel.lowRange = 0.0
        fuel.highRange = 20.0
        fuel.lowWarn = 2.0
        fuel.resize(190, 75)
        fuel.move(w.width() - 200, 380)
        fuel.value = 15.2

        ff = gauges.HorizontalBar(w)
        ff.name = "Fuel Flow"
        ff.units = "gph"
        ff.decimalPlaces = 1
        ff.lowRange = 0.0
        ff.highRange = 20.0
        ff.highWarn = None
        ff.highAlarm = None
        ff.lowWarn = None
        ff.lowAlarm = None
        ff.resize(190, 75)
        ff.move(w.width() - 200, 460)
        ff.value = 5.2

        cht = gauges.HorizontalBar(w)
        cht.name = "Max CHT"
        cht.units = "degF"
        cht.decimalPlaces = 0
        cht.lowRange = 0.0
        cht.highRange = 500.0
        cht.highWarn = 380
        cht.highAlarm = 400
        cht.resize(190, 75)
        cht.move(w.width() - 200, 540)
        cht.value = 350

        egt = gauges.HorizontalBar(w)
        egt.name = "Avg EGT"
        egt.units = "degF"
        egt.decimalPlaces = 0
        egt.lowRange = 800.0
        egt.highRange = 1500.0
        egt.resize(190, 75)
        egt.move(w.width() - 200, 620)
        egt.value = 1350

        if not test:
            self.flightData.pitchChanged.connect(a.setPitchAngle)
            self.flightData.rollChanged.connect(a.setRollAngle)
            self.flightData.headingChanged.connect(head_tape.setHeading)
        else:
            roll = QSlider(Qt.Horizontal, w)
            roll.setMinimum(-180)
            roll.setMaximum(180)
            roll.setValue(0)
            roll.resize(200, 20)
            roll.move(440, 100)

            pitch = QSlider(Qt.Vertical, w)
            pitch.setMinimum(-90)
            pitch.setMaximum(90)
            pitch.setValue(0)
            pitch.resize(20, 200)
            pitch.move(360, 180)

            smap = QSlider(Qt.Horizontal, w)
            smap.setMinimum(0)
            smap.setMaximum(30)
            smap.setValue(0)
            smap.resize(200, 20)
            smap.move(w.width() - 200, 200)

            srpm = QSlider(Qt.Horizontal, w)
            srpm.setMinimum(0)
            srpm.setMaximum(3000)
            srpm.setValue(0)
            srpm.resize(200, 20)
            srpm.move(w.width() - 200, 100)

            heading = QSpinBox(w)
            heading.move(0, instHeight + 100)
            heading.setRange(0, 360)
            heading.setValue(1)
            heading.valueChanged.connect(head_tape.setHeading)

            #headingBug = QSpinBox(w)
            #headingBug.move(650, 680)
            #headingBug.setRange(0, 360)
            #headingBug.setValue(1)
            #headingBug.valueChanged.connect(h.setHeadingBug)

            alt_gauge = QSpinBox(w)
            alt_gauge.setMinimum(0)
            alt_gauge.setMaximum(10000)
            alt_gauge.setValue(0)
            alt_gauge.setSingleStep(10)
            alt_gauge.move(1100, 100)
            alt_gauge.valueChanged.connect(alt_tape.setAltimeter)

            as_gauge = QSpinBox(w)
            as_gauge.setMinimum(0)
            as_gauge.setMaximum(140)
            as_gauge.setValue(0)
            as_gauge.move(10, 100)
            as_gauge.valueChanged.connect(as_tape.setAirspeed)

            pitch.valueChanged.connect(a.setPitchAngle)
            roll.valueChanged.connect(a.setRollAngle)
            smap.valueChanged.connect(map.setValue)
            srpm.valueChanged.connect(rpm.setValue)
예제 #19
0
class ParameterizedQueryDialog(QDialog):
    def __init__(self, name, parameters=None, connections=None):
        QDialog.__init__(self)

        self.result = []

        self.setWindowTitle("Define query parameters")
        self.setWindowIcon(QIcon(":\plugins\GeODinQGIS\icons\transparent.png"))

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.NoButton
                                          | QDialogButtonBox.Ok)
        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.ok)
        self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(
            self.cancel)

        layout = QVBoxLayout(self)

        l1 = QLabel("Parameters in red are required entries.")
        l1.setStyleSheet('color: red')
        l2 = QLabel(
            "Parameters in blue are optional (empty entry fields are not evaluated in the query)."
        )
        l2.setStyleSheet('color: blue')

        self.w = QWidget()
        self.w.setAutoFillBackground(True)
        p = self.w.palette()
        p.setColor(self.w.backgroundRole(), QColor(255, 221, 161))
        self.w.setPalette(p)

        tableLayout = QGridLayout(self.w)
        j = 0
        for i, parameter in enumerate(parameters):
            label = QLabel(parameter[0])
            le1 = QLineEdit(parameter[1])
            le1.setFixedSize(50, 25)
            le2 = QLineEdit()
            le2.setFixedSize(250, 25)
            tableLayout.addWidget(QLabel(connections[i]), i + j, 0)
            tableLayout.addWidget(label, i + j + 1, 1)
            tableLayout.addWidget(le1, i + j + 1, 2)
            tableLayout.addWidget(le2, i + j + 1, 3)
            j += 1

        layout.addWidget(
            QLabel("Enter the required values of the query '" + name + "'"))
        layout.addWidget(QLabel(""))
        #layout.addWidget(l1)
        #layout.addWidget(l2)
        layout.addWidget(
            QLabel("This operators are available:  <  <=  =  >=  >  <>  like"))
        layout.addWidget(self.w)
        layout.addWidget(self.buttonBox)

        self.exec_()

    def ok(self):
        for i in range(1, len(self.w.children()), 4):
            if not self.w.children()[i + 3].text().isdigit():
                self.w.children()[i +
                                  3].setText("'" +
                                             self.w.children()[i + 3].text() +
                                             "'")
            self.result.append([
                self.w.children()[i + 1].text(),
                self.w.children()[i + 2].text(),
                self.w.children()[i + 3].text()
            ])
        self.accept()

    def cancel(self):
        self.close()
예제 #20
0
class Example(QMainWindow):
    def __init__(self):
        super().__init__()
        self.background = QWidget(self)
        self.background.setGeometry(30, 20, 609, 321)
        self.background.setAutoFillBackground(True)
        p = self.background.palette()
        p.setColor(self.background.backgroundRole(), Qt.cyan)
        self.background.setPalette(p)
        loadUi("untitled.ui", self)
        self.initUI()

    def initUI(self):
        self.resize(1200, 650)
        self.move(300, 200)
        self.setWindowTitle('Map Editor v0.1')
        self.setWindowIcon(QIcon('web.png'))
        self.actualTexture = 0
        self.mapInfo = numpy.zeros(
            4, dtype=int
        )  # Wielkość X mapy, wielkość Y mapy, pozycja X portalu, pozycja Y portalu
        self.mtiles = {}
        self.mtilesHp = {}
        self.mpickups = {}
        self.mtraps = {}
        self.menemies = {}
        self.playerPos = {}

        # MENU
        self.flipButton.hide()
        self.hpLabel.hide()
        self.hpEditor.hide()
        self.armorLabel.hide()
        self.armorEditor.hide()
        self.mhpl.hide()  # max hp label
        self.marl.hide()  # max armor label
        self.mhpe.hide()  # max hp editor
        self.mare.hide()  # max armor editor

        self.hpEditor.valueChanged.connect(self.setMaxParameters)
        self.armorEditor.valueChanged.connect(self.setMaxParameters)

        self.playerInfo = numpy.zeros(6, dtype=int)

        # scrolle do przewijania mapy
        self.scrollX = QScrollBar(Qt.Horizontal, self)
        self.scrollX.setGeometry(30, 341, 609, 16)
        self.scrollY = QScrollBar(Qt.Vertical, self)
        self.scrollY.setGeometry(638, 20, 16, 320)
        self.scrollX.valueChanged.connect(self.prepareMap)
        self.scrollY.valueChanged.connect(self.prepareMap)

        self.checkButton.clicked.connect(self.checkInfo)

        self.button = 1

        self.tiles = [
            self.tile1, self.tile2, self.tile3, self.tile4, self.tile5,
            self.tile6, self.tile7, self.tile8, self.tile9, self.tile10,
            self.tile11, self.tile12, self.tile13, self.tile14, self.tile15,
            self.tile16, self.tile17, self.tile18, self.tile19, self.tile20,
            self.tile21, self.tile22, self.tile23, self.tile24, self.tile25,
            self.tile26, self.tile27, self.tile28, self.tile29, self.tile30,
            self.tile31, self.tile32, self.tile33, self.tile34, self.tile35,
            self.tile36, self.tile37, self.tile38, self.tile39, self.tile40,
            self.tile41, self.tile42, self.tile43, self.tile44, self.tile45,
            self.tile46, self.tile47, self.tile48, self.tile49, self.tile50,
            self.tile51, self.tile52, self.tile53, self.tile54, self.tile55,
            self.tile56, self.tile57, self.tile58, self.tile59, self.tile60,
            self.tile61, self.tile62, self.tile63, self.tile64, self.tile65,
            self.tile66, self.tile67, self.tile68, self.tile69, self.tile70,
            self.tile71, self.tile72, self.tile73, self.tile74, self.tile75,
            self.tile76, self.tile77, self.tile78, self.tile79, self.tile80,
            self.tile81, self.tile82, self.tile83, self.tile84, self.tile85,
            self.tile86, self.tile87, self.tile88, self.tile89, self.tile90,
            self.tile91, self.tile92, self.tile93, self.tile94, self.tile95,
            self.tile96, self.tile97, self.tile98, self.tile99, self.tile100,
            self.tile101, self.tile102, self.tile103, self.tile104,
            self.tile105, self.tile106, self.tile107, self.tile108,
            self.tile109, self.tile110, self.tile111, self.tile112,
            self.tile113, self.tile114, self.tile115, self.tile116,
            self.tile117, self.tile118, self.tile119, self.tile120,
            self.tile121, self.tile122, self.tile123, self.tile124,
            self.tile125, self.tile126, self.tile127, self.tile128,
            self.tile129, self.tile130, self.tile131, self.tile132,
            self.tile133, self.tile134, self.tile135, self.tile136,
            self.tile137, self.tile138, self.tile139, self.tile140,
            self.tile141, self.tile142, self.tile143, self.tile144,
            self.tile145, self.tile146, self.tile147, self.tile148,
            self.tile149, self.tile150, self.tile151, self.tile152,
            self.tile153, self.tile154, self.tile155, self.tile156,
            self.tile157, self.tile158, self.tile159, self.tile160,
            self.tile161, self.tile162, self.tile163, self.tile164,
            self.tile165, self.tile166, self.tile167, self.tile168,
            self.tile169, self.tile170, self.tile171, self.tile172,
            self.tile173, self.tile174, self.tile175, self.tile176,
            self.tile177, self.tile178, self.tile179, self.tile180,
            self.tile181, self.tile182, self.tile183, self.tile184,
            self.tile185, self.tile186, self.tile187, self.tile188,
            self.tile189, self.tile190
        ]

        self.enemies = [
            self.enemy1, self.enemy2, self.enemy3, self.enemy4, self.enemy5,
            self.enemy6, self.enemy7, self.enemy8, self.enemy9, self.enemy10,
            self.enemy11, self.enemy12, self.enemy13, self.enemy14,
            self.enemy15, self.enemy16, self.enemy17, self.enemy18,
            self.enemy19, self.enemy20, self.enemy21, self.enemy22,
            self.enemy23, self.enemy24, self.enemy25, self.enemy26,
            self.enemy27, self.enemy28, self.enemy29, self.enemy30,
            self.enemy31, self.enemy32, self.enemy33, self.enemy34,
            self.enemy35, self.enemy36, self.enemy37, self.enemy38,
            self.enemy39, self.enemy40, self.enemy41, self.enemy42,
            self.enemy43, self.enemy44, self.enemy45, self.enemy46,
            self.enemy47, self.enemy48, self.enemy49, self.enemy50,
            self.enemy51, self.enemy52, self.enemy53, self.enemy54,
            self.enemy55, self.enemy56, self.enemy57, self.enemy58,
            self.enemy59, self.enemy60, self.enemy61, self.enemy62,
            self.enemy63, self.enemy64, self.enemy65, self.enemy66,
            self.enemy67, self.enemy68, self.enemy69, self.enemy70,
            self.enemy71, self.enemy72, self.enemy73, self.enemy74,
            self.enemy75, self.enemy76, self.enemy77, self.enemy78,
            self.enemy79, self.enemy80, self.enemy81, self.enemy82,
            self.enemy83, self.enemy84, self.enemy85, self.enemy86,
            self.enemy87, self.enemy88, self.enemy89, self.enemy90,
            self.enemy91, self.enemy92, self.enemy93, self.enemy94,
            self.enemy95, self.enemy96, self.enemy97, self.enemy98,
            self.enemy99, self.enemy100, self.enemy101, self.enemy102,
            self.enemy103, self.enemy104, self.enemy105, self.enemy106,
            self.enemy107, self.enemy108, self.enemy109, self.enemy110,
            self.enemy111, self.enemy112, self.enemy113, self.enemy114,
            self.enemy115, self.enemy116, self.enemy117, self.enemy118,
            self.enemy119, self.enemy120, self.enemy121, self.enemy122,
            self.enemy123, self.enemy124, self.enemy125, self.enemy126,
            self.enemy127, self.enemy128, self.enemy129, self.enemy130,
            self.enemy131, self.enemy132, self.enemy133, self.enemy134,
            self.enemy135, self.enemy136, self.enemy137, self.enemy138,
            self.enemy139, self.enemy140, self.enemy141, self.enemy142,
            self.enemy143, self.enemy144, self.enemy145, self.enemy146,
            self.enemy147, self.enemy148, self.enemy149, self.enemy150,
            self.enemy151, self.enemy152, self.enemy153, self.enemy154,
            self.enemy155, self.enemy156, self.enemy157, self.enemy158,
            self.enemy159, self.enemy160, self.enemy161, self.enemy162,
            self.enemy163, self.enemy164, self.enemy165, self.enemy166,
            self.enemy167, self.enemy168, self.enemy169, self.enemy170,
            self.enemy171, self.enemy172, self.enemy173, self.enemy174,
            self.enemy175, self.enemy176, self.enemy177, self.enemy178,
            self.enemy179, self.enemy180, self.enemy181, self.enemy182,
            self.enemy183, self.enemy184, self.enemy185, self.enemy186,
            self.enemy187, self.enemy188, self.enemy189, self.enemy190
        ]

        self.pickups = [
            self.pickup1, self.pickup2, self.pickup3, self.pickup4,
            self.pickup5, self.pickup6, self.pickup7, self.pickup8,
            self.pickup9, self.pickup10, self.pickup11, self.pickup12,
            self.pickup13, self.pickup14, self.pickup15, self.pickup16,
            self.pickup17, self.pickup18, self.pickup19, self.pickup20,
            self.pickup21, self.pickup22, self.pickup23, self.pickup24,
            self.pickup25, self.pickup26, self.pickup27, self.pickup28,
            self.pickup29, self.pickup30, self.pickup31, self.pickup32,
            self.pickup33, self.pickup34, self.pickup35, self.pickup36,
            self.pickup37, self.pickup38, self.pickup39, self.pickup40,
            self.pickup41, self.pickup42, self.pickup43, self.pickup44,
            self.pickup45, self.pickup46, self.pickup47, self.pickup48,
            self.pickup49, self.pickup50, self.pickup51, self.pickup52,
            self.pickup53, self.pickup54, self.pickup55, self.pickup56,
            self.pickup57, self.pickup58, self.pickup59, self.pickup60,
            self.pickup61, self.pickup62, self.pickup63, self.pickup64,
            self.pickup65, self.pickup66, self.pickup67, self.pickup68,
            self.pickup69, self.pickup70, self.pickup71, self.pickup72,
            self.pickup73, self.pickup74, self.pickup75, self.pickup76,
            self.pickup77, self.pickup78, self.pickup79, self.pickup80,
            self.pickup81, self.pickup82, self.pickup83, self.pickup84,
            self.pickup85, self.pickup86, self.pickup87, self.pickup88,
            self.pickup89, self.pickup90, self.pickup91, self.pickup92,
            self.pickup93, self.pickup94, self.pickup95, self.pickup96,
            self.pickup97, self.pickup98, self.pickup99, self.pickup100,
            self.pickup101, self.pickup102, self.pickup103, self.pickup104,
            self.pickup105, self.pickup106, self.pickup107, self.pickup108,
            self.pickup109, self.pickup110, self.pickup111, self.pickup112,
            self.pickup113, self.pickup114, self.pickup115, self.pickup116,
            self.pickup117, self.pickup118, self.pickup119, self.pickup120,
            self.pickup121, self.pickup122, self.pickup123, self.pickup124,
            self.pickup125, self.pickup126, self.pickup127, self.pickup128,
            self.pickup129, self.pickup130, self.pickup131, self.pickup132,
            self.pickup133, self.pickup134, self.pickup135, self.pickup136,
            self.pickup137, self.pickup138, self.pickup139, self.pickup140,
            self.pickup141, self.pickup142, self.pickup143, self.pickup144,
            self.pickup145, self.pickup146, self.pickup147, self.pickup148,
            self.pickup149, self.pickup150, self.pickup151, self.pickup152,
            self.pickup153, self.pickup154, self.pickup155, self.pickup156,
            self.pickup157, self.pickup158, self.pickup159, self.pickup160,
            self.pickup161, self.pickup162, self.pickup163, self.pickup164,
            self.pickup165, self.pickup166, self.pickup167, self.pickup168,
            self.pickup169, self.pickup170, self.pickup171, self.pickup172,
            self.pickup173, self.pickup174, self.pickup175, self.pickup176,
            self.pickup177, self.pickup178, self.pickup179, self.pickup180,
            self.pickup181, self.pickup182, self.pickup183, self.pickup184,
            self.pickup185, self.pickup186, self.pickup187, self.pickup188,
            self.pickup189, self.pickup190
        ]

        self.traps = [
            self.trap1, self.trap2, self.trap3, self.trap4, self.trap5,
            self.trap6, self.trap7, self.trap8, self.trap9, self.trap10,
            self.trap11, self.trap12, self.trap13, self.trap14, self.trap15,
            self.trap16, self.trap17, self.trap18, self.trap19, self.trap20,
            self.trap21, self.trap22, self.trap23, self.trap24, self.trap25,
            self.trap26, self.trap27, self.trap28, self.trap29, self.trap30,
            self.trap31, self.trap32, self.trap33, self.trap34, self.trap35,
            self.trap36, self.trap37, self.trap38, self.trap39, self.trap40,
            self.trap41, self.trap42, self.trap43, self.trap44, self.trap45,
            self.trap46, self.trap47, self.trap48, self.trap49, self.trap50,
            self.trap51, self.trap52, self.trap53, self.trap54, self.trap55,
            self.trap56, self.trap57, self.trap58, self.trap59, self.trap60,
            self.trap61, self.trap62, self.trap63, self.trap64, self.trap65,
            self.trap66, self.trap67, self.trap68, self.trap69, self.trap70,
            self.trap71, self.trap72, self.trap73, self.trap74, self.trap75,
            self.trap76, self.trap77, self.trap78, self.trap79, self.trap80,
            self.trap81, self.trap82, self.trap83, self.trap84, self.trap85,
            self.trap86, self.trap87, self.trap88, self.trap89, self.trap90,
            self.trap91, self.trap92, self.trap93, self.trap94, self.trap95,
            self.trap96, self.trap97, self.trap98, self.trap99, self.trap100,
            self.trap101, self.trap102, self.trap103, self.trap104,
            self.trap105, self.trap106, self.trap107, self.trap108,
            self.trap109, self.trap110, self.trap111, self.trap112,
            self.trap113, self.trap114, self.trap115, self.trap116,
            self.trap117, self.trap118, self.trap119, self.trap120,
            self.trap121, self.trap122, self.trap123, self.trap124,
            self.trap125, self.trap126, self.trap127, self.trap128,
            self.trap129, self.trap130, self.trap131, self.trap132,
            self.trap133, self.trap134, self.trap135, self.trap136,
            self.trap137, self.trap138, self.trap139, self.trap140,
            self.trap141, self.trap142, self.trap143, self.trap144,
            self.trap145, self.trap146, self.trap147, self.trap148,
            self.trap149, self.trap150, self.trap151, self.trap152,
            self.trap153, self.trap154, self.trap155, self.trap156,
            self.trap157, self.trap158, self.trap159, self.trap160,
            self.trap161, self.trap162, self.trap163, self.trap164,
            self.trap165, self.trap166, self.trap167, self.trap168,
            self.trap169, self.trap170, self.trap171, self.trap172,
            self.trap173, self.trap174, self.trap175, self.trap176,
            self.trap177, self.trap178, self.trap179, self.trap180,
            self.trap181, self.trap182, self.trap183, self.trap184,
            self.trap185, self.trap186, self.trap187, self.trap188,
            self.trap189, self.trap190
        ]

        self.names = [
            "Brick", "Box", "AK", "Pistol", "Rock", "Shield", "Heart", "Dog",
            "Soldier", "Spikes", "Shooter", "Shooter", "Shooter", "Shooter",
            "Player", "Portal"
        ]

        self.pixmaps = [
            "./textures/blank.png", "./textures/brick.png",
            "./textures/box.png", "./textures/ak.png", "./textures/pistol.png",
            "./textures/rock.png", "./textures/armor.png",
            "./textures/heart.png", "./textures/dog.png",
            "./textures/enemy.png", "./textures/spikes.png",
            "./textures/shooter1.png", "./textures/shooter2.png",
            "./textures/shooter3.png", "./textures/shooter4.png",
            "./textures/spawn.png", "./textures/portal.png"
        ]

        self.bpixmaps = [
            "./textures/brick.png", "./textures/box.png", "./textures/ak.png",
            "./textures/pistol.png", "./textures/rock.png",
            "./textures/armor.png", "./textures/heart.png",
            "./textures/dog.png", "./textures/enemy.png",
            "./textures/spikes.png", "./textures/shooter1.png",
            "./textures/shooter2.png", "./textures/shooter3.png",
            "./textures/shooter4.png", "./textures/player.png",
            "./textures/portal.png"
        ]

        # obrót shootera
        self.flip = 0
        self.shooterFlip = [
            "./textures/shooter1.png", "./textures/shooter2.png",
            "./textures/shooter3.png", "./textures/shooter4.png"
        ]
        self.flipButton.clicked.connect(self.changeShooterFlip)

        self.buttons = [
            self.l1, self.l2, self.l3, self.l4, self.l5, self.l6, self.l7,
            self.l8, self.l9, self.l10, self.l11, self.spawnpointButton,
            self.endMapButton
        ]
        self.l8.setIconSize(QSize(64, 64))
        self.l9.setIconSize(QSize(64, 64))
        self.confirmSizeButton.clicked.connect(self.makeArray)

        self.saveButton.clicked.connect(self.save)

        for button, pixmap, i in zip(self.buttons, self.bpixmaps,
                                     range(1,
                                           len(self.buttons) + 1)):
            if i < 12:
                button.setIcon(QIcon(QPixmap(pixmap)))
                button.setIconSize(QSize(32, 32))
                if i > 8:
                    button.setIconSize(QSize(64, 64))
                button.clicked.connect(partial(self.makeMenu, i))
            else:
                button.clicked.connect(partial(self.makeMenu, i + 3))

        self.makeArray()

        self.show()

    def changeShooterFlip(self):
        self.flip = (self.flip + 1) % 4
        self.makeMenu(11 + self.flip)

    def makeMenu(self, i):
        print(i)
        self.infoLabel.setText('')
        self.actualTexture = i

        self.nameLabel.setText(self.names[i - 1])
        self.podglad.setPixmap(QPixmap(self.pixmaps[i]))

        self.hpLabel.hide()
        self.hpEditor.hide()
        self.flipButton.hide()
        self.armorLabel.hide()
        self.armorEditor.hide()
        self.mhpl.hide()
        self.marl.hide()
        self.mhpe.hide()
        self.mare.hide()
        if i == 2:
            self.hpLabel.show()
            self.hpEditor.show()
        if i == 11:
            self.flip = 0
        if 11 <= i < 15:
            self.flipButton.show()
        if i == 8 or i == 9:
            self.hpLabel.show()
            self.hpEditor.show()
            self.armorLabel.show()
            self.armorEditor.show()
        if i == 15:
            self.hpLabel.show()
            self.hpEditor.show()
            self.armorLabel.show()
            self.armorEditor.show()
            self.mhpl.show()
            self.marl.show()
            self.mhpe.show()
            self.mare.show()

    def setMaxParameters(self):
        self.mare.setMinimum(self.armorEditor.value())
        self.mhpe.setMinimum(self.hpEditor.value())

    def makeArray(self):
        allOk = 0
        sizeX = self.sizeX.toPlainText()
        sizeY = self.sizeY.toPlainText()
        try:
            self.mapInfo[0] = (int)(sizeX)
            self.mapInfo[1] = (int)(sizeY)
            allOk = 1
        except ValueError:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle("Information")
            msg.setText("Entered data must be numbers!")
            msg.show()

        if allOk:
            if self.mapInfo[0] >= 19 and self.mapInfo[1] >= 10:

                self.mtiles = numpy.zeros((self.mapInfo[0], self.mapInfo[1]),
                                          dtype=int)
                self.mtilesHp = numpy.zeros((self.mapInfo[0], self.mapInfo[1]),
                                            dtype=int)
                self.mpickups = numpy.zeros((self.mapInfo[0], self.mapInfo[1]),
                                            dtype=int)
                self.mtraps = numpy.zeros((self.mapInfo[0], self.mapInfo[1]),
                                          dtype=int)
                self.menemies = numpy.zeros((self.mapInfo[0], self.mapInfo[1]),
                                            dtype=int)
                self.playerPos = numpy.zeros(
                    (self.mapInfo[0], self.mapInfo[1]), dtype=int)

                self.scrollX.setMaximum(self.mapInfo[0] - 19)
                self.scrollY.setMaximum(self.mapInfo[1] - 10)

                msg = QMessageBox(self)
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle("Information")
                msg.setText("Current dimensions: " + sizeX + "x" + sizeY)
                msg.show()
                self.prepareMap()
            else:
                msg = QMessageBox(self)
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle("Information")
                msg.setText("Dimensions must be >= 19x10")
                msg.show()

    def prepareMap(self):
        for i in range(19):
            for j in range(10):
                self.tiles[19 * j + i].setPixmap(
                    QPixmap(self.pixmaps[self.mtiles[i + self.scrollX.value()][
                        j + self.scrollY.value()]]))
                self.pickups[19 * j + i].setPixmap(
                    QPixmap(self.pixmaps[self.mpickups[
                        i + self.scrollX.value()][j + self.scrollY.value()]]))
                self.traps[19 * j + i].setPixmap(
                    QPixmap(self.pixmaps[self.mtraps[i + self.scrollX.value()][
                        j + self.scrollY.value()]]))

                pom = self.menemies[i + self.scrollX.value()][
                    j + self.scrollY.value()] / 100
                self.enemies[19 * j + i].setPixmap(
                    QPixmap(self.pixmaps[int(pom)]).scaled(
                        32, 32, Qt.KeepAspectRatio))
                if self.playerPos[i + self.scrollX.value()][
                        j + self.scrollY.value()] > 0:
                    self.enemies[19 * j + i].setPixmap(
                        QPixmap(self.pixmaps[self.playerPos[
                            i + self.scrollX.value()][j +
                                                      self.scrollY.value()]]))

    def mouseMoveEvent(self, event):
        self.addItem(event)

    def save(self):
        if self.mapInfo[2] == 0 and self.mapInfo[3] == 0:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle("Information")
            msg.setText("Set portal(end of the map)!")
            msg.show()
        elif self.playerInfo[3] == 0:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle("Information")
            msg.setText("Set spawnpoint!")
            msg.show()
        else:
            path = QInputDialog.getText(self, "Save map",
                                        "Please input map name:")
            if path[1]:
                if not os.path.exists("./levels/" + path[0]):
                    os.makedirs("./levels/" + path[0])

                    text = " ".join(str(x) for x in self.mtiles)
                    text = text.translate({ord('['): ''})
                    text = text.translate({ord(']'): ''})
                    text = re.sub('0', '00', text).strip()
                    text = re.sub('1', '01', text).strip()
                    text = re.sub('2', '02', text).strip()
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/map.map", text)

                    text = " ".join(str(x) for x in self.mtilesHp)
                    text = text.translate({ord('['): ''})
                    text = text.translate({ord(']'): ''})
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/map.hp", text)

                    text = " ".join(str(x) for x in self.mtraps)
                    text = text.translate({ord('['): ''})
                    text = text.translate({ord(']'): ''})
                    text = re.sub('10', '1', text).strip()
                    text = re.sub('11', '2', text).strip()
                    text = re.sub('12', '3', text).strip()
                    text = re.sub('13', '4', text).strip()
                    text = re.sub('14', '5', text).strip()
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/map.trap", text)

                    text = " ".join(str(x) for x in self.mpickups)
                    text = text.translate({ord('['): ''})
                    text = text.translate({ord(']'): ''})
                    text = re.sub('7', '1', text).strip()
                    text = re.sub('6', '2', text).strip()
                    text = re.sub('3', '7', text).strip()
                    text = re.sub('5', '3', text).strip()
                    text = re.sub('7', '5', text).strip()
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/map.pck", text)

                    text = " ".join(str(x) for x in self.menemies)
                    #text = re.sub('0', '000', text).strip()
                    text = re.sub('   ', ' ', text).strip()
                    text = re.sub('   ', ' ', text).strip()
                    text = text.translate({ord('['): ''})
                    text = text.translate({ord(']'): ''})
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/map.enm", text)

                    text = " ".join(str(x) for x in self.playerInfo)
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/player.info", text)

                    text = " ".join(str(x) for x in self.mapInfo)
                    text = text.translate({ord('['): ''})
                    text = text.translate({ord(']'): ''})
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("  ", " ")
                    text = text.replace("\n", "")

                    self.saveFile("./levels/" + path[0] + "/map.info", text)

                    msg = QMessageBox(self)
                    msg.setIcon(QMessageBox.Information)
                    msg.setWindowTitle("Information")
                    msg.setText("Map created successfully!")
                    msg.show()
                else:
                    msg = QMessageBox(self)
                    msg.setIcon(QMessageBox.Information)
                    msg.setWindowTitle("Information")
                    msg.setText("A map with this name exists!")
                    msg.show()

    def saveFile(self, fileName, text):
        f = open(fileName, "a")
        f.write(text)

    def mousePressEvent(self, event):
        if event.button() == 1:
            self.button = 1
        else:
            self.button = 0
        self.addItem(event)

    def addItem(self, event):
        for i in range(19):
            for j in range(10):
                if (i + 1) * 32 + 30 >= event.x() >= i * 32 + 30 and (
                        j + 1) * 32 + 20 >= event.y() >= j * 32 + 20:
                    if (self.button):
                        if 3 > self.actualTexture > 0:
                            self.mtiles[i + self.scrollX.value()][
                                j + self.scrollY.value()] = self.actualTexture
                            if self.actualTexture == 2:
                                pom = self.hpEditor.value() / 100.0
                                self.mtilesHp[i + self.scrollX.value()][
                                    j + self.scrollY.value()] = int(pom)
                        if 8 > self.actualTexture > 2:
                            self.mpickups[i + self.scrollX.value()][
                                j + self.scrollY.value()] = self.actualTexture
                        if 10 > self.actualTexture > 7:
                            self.menemies[i + self.scrollX.value(
                            )][j + self.scrollY.value(
                            )] = 100 * self.actualTexture + self.hpEditor.value(
                            ) / 10 + self.armorEditor.value() / 100
                            if self.playerPos[i + self.scrollX.value()][
                                    j + self.scrollY.value()] != 0:
                                self.playerPos[i + self.scrollX.value()][
                                    j + self.scrollY.value()] = 0
                                self.playerInfo = numpy.zeros(6, dtype=int)
                        if 15 > self.actualTexture > 9:
                            self.mtraps[i + self.scrollX.value()][
                                j + self.scrollY.value()] = self.actualTexture
                        if self.actualTexture == 15:
                            self.playerPos[self.playerInfo[0]][
                                self.playerInfo[1]] = 0
                            self.playerInfo[0] = i + self.scrollX.value()
                            self.playerInfo[1] = j + self.scrollY.value()
                            self.playerInfo[2] = self.hpEditor.value() / 100
                            self.playerInfo[3] = self.mhpe.value() / 100
                            self.playerInfo[4] = self.armorEditor.value() / 100
                            self.playerInfo[5] = self.mare.value() / 100
                            self.playerPos[self.playerInfo[0]][
                                self.playerInfo[1]] = 0
                            self.playerPos[i + self.scrollX.value()][
                                j + self.scrollY.value()] = self.actualTexture
                            self.menemies[i + self.scrollX.value()][
                                j + self.scrollY.value()] = 0
                            self.prepareMap()

                        if self.actualTexture == 16:
                            self.playerPos[self.mapInfo[2]][
                                self.mapInfo[3]] = 0
                            self.mapInfo[2] = i + self.scrollX.value()
                            self.mapInfo[3] = j + self.scrollY.value()
                            self.playerPos[i + self.scrollX.value()][
                                j + self.scrollY.value()] = self.actualTexture
                            self.menemies[i + self.scrollX.value()][
                                j + self.scrollY.value()] = 0
                            self.prepareMap()

                        if self.actualTexture == 0:
                            if (self.playerPos[i + self.scrollX.value()][
                                    j + self.scrollY.value()]) != 0:
                                text = "HP: " + str(
                                    self.playerInfo[2] *
                                    100) + "  Max HP: " + str(
                                        self.playerInfo[3] *
                                        100) + "\nArmor: " + str(
                                            self.playerInfo[4] *
                                            100) + "  Max Armor: " + str(
                                                self.playerInfo[5] * 100)
                                self.infoLabel.setText(text)
                            if (self.mtilesHp[i + self.scrollX.value()][
                                    j + self.scrollY.value()]) != 0:
                                text = "HP: " + str(
                                    self.mtilesHp[i + self.scrollX.value()][
                                        j + self.scrollY.value()] * 100)
                                self.infoLabel.setText(text)
                            if (self.menemies[i + self.scrollX.value()][
                                    j + self.scrollY.value()]) != 0:
                                pom = str(
                                    self.menemies[i + self.scrollX.value()][
                                        j + self.scrollY.value()])
                                text = "HP: " + str(
                                    int(pom[1]) * 100) + "\nArmor: " + str(
                                        int(pom[2]) * 100)
                                self.infoLabel.setText(text)
                    else:
                        self.mtiles[i + self.scrollX.value()][
                            j + self.scrollY.value()] = 0
                        self.mpickups[i + self.scrollX.value()][
                            j + self.scrollY.value()] = 0
                        self.mtraps[i + self.scrollX.value()][
                            j + self.scrollY.value()] = 0
                        self.menemies[i + self.scrollX.value()][
                            j + self.scrollY.value()] = 0
                        if self.playerPos[i + self.scrollX.value()][
                                j + self.scrollY.value()] != 0:
                            self.playerPos[i + self.scrollX.value()][
                                j + self.scrollY.value()] = 0
                            self.playerInfo = numpy.zeros(6, dtype=int)

        self.prepareMap()
        self.update()

    def checkInfo(self):
        self.makeMenu(0)
예제 #21
0
class ValueLabelGui(QWidget):
    
    start_signal = QtCore.pyqtSignal()
    stop_signal = QtCore.pyqtSignal()
    
    def __init__(self, parent=None, window=None, devicewrapper=None):
        """ """
        super(ValueLabelGui, self).__init__(parent=parent)
        self._init_ui(window)
        self._init_worker_thread(devicewrapper)
        
    
    def _init_ui(self, mainwindow):

        self.central_wid = QWidget(mainwindow)
        self._set_central_wid_properties()
        self.mainwindow = mainwindow
        self.mainwindow.setCentralWidget(self.central_wid)  
        
        

        # grid layout to put all widgets
        self.wid_layout = QGridLayout()
           
        
        # =====================================================================
        # control panel
        # =====================================================================
        self.graphics_layout = QGridLayout()
        self.vl = pg.ValueLabel(formatStr='{avgValue:0.2f} {suffix}')
        self.vl.setValue(-1)
        self.graphics_layout.addWidget(self.vl, 0, 0, 4, 4)
        
        
        # =====================================================================
        # control panel
        # =====================================================================
        self.controls_layout = QGridLayout()


        # =====================================================================
        # control buttons - layout
        # =====================================================================
        self.startBtn = QPushButton('START')
        self.controls_layout.addWidget(self.startBtn, 0, 0, 1, 1)
        self.stopBtn = QPushButton('STOP')
        self.controls_layout.addWidget(self.stopBtn, 1, 0, 1, 1)
        
        
        # =====================================================================
        # control buttons - connections
        # =====================================================================
        self.startBtn.clicked.connect(self.start_thread)
        self.stopBtn.clicked.connect(self.stop_thread)

       # ============================================================
        # put everything together
        # ============================================================
        self.wid_layout.addItem(self.graphics_layout, 0, 0, 2, 2)
        self.wid_layout.addItem(self.controls_layout, 0, 2, 2, 2)     
        # self.wid_layout.setColumnStretch(0, 10)
        # self.wid_layout.setColumnStretch(8, 2)
        
        self.central_wid.setLayout(self.wid_layout)


    def _set_central_wid_properties(self):
        """ """
        self.central_wid.setAutoFillBackground(True)
        p = self.central_wid.palette()
        p.setColor(self.central_wid.backgroundRole(), QtCore.Qt.darkGray)
        self.central_wid.setPalette(p)    
        
  
    def _init_worker_thread(self, devicewrapper):
        """ """
        
        # Setup QWaitCondition
        self.mutex = QMutex()
        self.cond = QWaitCondition()
        
        # Setup the measurement engine        
#        self.mthread = QtCore.QThread()
        self.worker = TimePlotWorker(devicewrapper, self.mutex, self.cond)        
        
        
        # connect signal and slots
        self.start_signal.connect(self.worker.start)
        self.stop_signal.connect(self.worker.stop)
        
        
        self.worker.reading.connect(self.newReading)
        
        return


    def start_thread(self):
        self.start_signal.emit()
        
    def stop_thread(self):
        self.stop_signal.emit()
        
    def update_ValueLabel(self, val):
        """ """
        self.vl.setValue(val)
        


    @QtCore.pyqtSlot(float)
    def newReading(self, val):
        """ """
        pg.QtGui.QApplication.processEvents()
        
        self.update_ValueLabel(val)
        time.sleep(0.1)         # necessary to avoid worker to freeze
        self.cond.wakeAll()     # wake worker thread up 
        return



    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QMessageBox.Yes | 
            QMessageBox.No, QMessageBox.Yes)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()  
예제 #22
0
class Ui_SubMonitor(object):
    def __init__(self):
        self.messagelist = []
        self.sub = M_SubStatusController.SubStatuController()

    def setupUi(self, MainWindow):
        self.reflashTimer = QTimer()
        self.reflashTimer.setInterval(2000)
        self.reflashTimer.timeout.connect(self.updateData)
        self.reflashTimer.start()

        self.SubMonitor = QWidget(MainWindow)
        self.SubMonitor.setObjectName("SubMonitor")
        self.SubMonitor.resize(1200, 590)
        self.SubMonitor.setGeometry(QtCore.QRect(0, 70, 1200, 590))
        jpeg = QtGui.QPixmap()
        jpeg.load("pictures/MonitorBg.png")
        palette1 = QtGui.QPalette()
        palette1.setBrush(self.SubMonitor.backgroundRole(), QtGui.QBrush(jpeg))
        self.SubMonitor.setPalette(palette1)
        self.SubMonitor.setAutoFillBackground(True)

        self.stack = QtWidgets.QStackedWidget(self.SubMonitor)
        self.stack.setGeometry(QtCore.QRect(100, 100, 1000, 390))

        # self.showWidget=QWidget(self.SubMonitor)
        # self.showWidget.setObjectName("showWidget")
        # self.showWidget.resize(800,400)
        # self.showWidget.setGeometry(QtCore.QRect(30,30,800,400))

        # self.monitorWidget = QtWidgets.QWidget(self.centralwidget)
        # self.monitorWidget.setGeometry(QtCore.QRect(30, 30, 991, 501))
        # self.monitorWidget.setObjectName("monitorWidget")

        # self.labeltest = QtWidgets.QLabel(self.SubMonitor)
        # self.labeltest.setGeometry(QtCore.QRect(20, 30, 81, 18))
        # self.labeltest.setObjectName("labeltest")

        self.updateData()
        ''''
        self.listlayout1 = QtWidgets.QVBoxLayout(self.showWidget)  ##垂直排列
        ###加for循环,room数####
        x=0
        self.messagelist=self.sub.showSub()
        #print(self.messagelist)
        while x<len(self.messagelist):
        ###while x <3:
            #print("a")
            self.roomnoLabel = QtWidgets.QLabel()
            self.idLabel=QtWidgets.QLabel()
            self.statuLabel = QtWidgets.QLabel()
            self.tempLabel = QtWidgets.QLabel()
            self.veloLabel = QtWidgets.QLabel()

            ###test过后删除###
            self.roomnoLabel.setText("No.1")
            self.idLabel.setText("xx")
            self.statuLabel.setText("工作中")
            self.tempLabel.setText("33℃")
            self.veloLabel.setText("中速")


            self.roomnoLabel.setNum(self.messagelist[x][0])
            self.idLabel.setText(self.messagelist[x][1])
            self.statuLabel.setNum(self.messagelist[x][2])
            self.tempLabel.setNum(self.messagelist[x][3])
            self.veloLabel.setNum(self.messagelist[x][4])



            self.rowlayout = QtWidgets.QHBoxLayout()
            self.rowlayout.addWidget(self.roomnoLabel)
            self.rowlayout.addWidget(self.idLabel)
            self.rowlayout.addWidget(self.statuLabel)
            self.rowlayout.addWidget(self.tempLabel)
            self.rowlayout.addWidget(self.veloLabel)

            self.listlayout1.addLayout(self.rowlayout)
            x+=1

        self.showWidget.setLayout(self.listlayout1)
        '''

        self.retranslateUi(self.SubMonitor)
        QtCore.QMetaObject.connectSlotsByName(self.SubMonitor)

    def retranslateUi(self, SubMonitor):
        _translate = QtCore.QCoreApplication.translate
        SubMonitor.setWindowTitle(_translate("SubMonitor", "Form"))
        # self.labeltest.setText(_translate("SubMonitor", "监视界面"))
########刷新数据#########

    def updateData(self):
        del self.messagelist[:]
        x = self.stack.count()
        #print("xxxxxxx", x)
        if (x != 0):
            i = 0
            while i < x:
                test = self.stack.widget(i)
                self.stack.removeWidget(test)
                test.destroy()
                #print("enenene")
                i += 1
                x = self.stack.count()
                #print("xxxxxxx", x)
        x = self.stack.count()
        #print("xxxxxxx", x)
        showWidget = QWidget(self.SubMonitor)
        showWidget.resize(800, 400)
        self.messagelist = [['房间号', '用户名', '送风中', '房间温度', '目标风速']]
        self.messagelist.extend(self.sub.showSub())

        listlayout1 = QtWidgets.QVBoxLayout(showWidget)  ##垂直排列
        ###加for循环,room数####
        x = 0
        # self.messagelist = self.sub.showSub()
        # #print(self.messagelist)
        while x < len(self.messagelist):
            ###while x <3:
            #print("a")
            roomnoLabel = QtWidgets.QLabel()
            roomnoLabel.setStyleSheet(
                "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
            idLabel = QtWidgets.QLabel()
            idLabel.setStyleSheet(
                "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
            statuLabel = QtWidgets.QLabel()
            statuLabel.setStyleSheet(
                "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
            tempLabel = QtWidgets.QLabel()
            tempLabel.setStyleSheet(
                "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
            veloLabel = QtWidgets.QLabel()
            veloLabel.setStyleSheet(
                "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")

            roomnoLabel.setText(self.messagelist[x][0])
            idLabel.setText(self.messagelist[x][1])
            statuLabel.setText(self.messagelist[x][2])
            tempLabel.setText(self.messagelist[x][3])
            veloLabel.setText(self.messagelist[x][4])

            rowlayout = QtWidgets.QHBoxLayout()
            rowlayout.addWidget(roomnoLabel)
            rowlayout.addWidget(idLabel)
            rowlayout.addWidget(statuLabel)
            rowlayout.addWidget(tempLabel)
            rowlayout.addWidget(veloLabel)

            listlayout1.addLayout(rowlayout)
            x += 1

        showWidget.setLayout(listlayout1)
        self.stack.addWidget(showWidget)
        # self.stack.setCurrentWidget(showWidget)
        x = self.stack.count()
예제 #23
0
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# This applications brings up a maximized window and fills it with magenta.

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QColor

app = QApplication(sys.argv)
w = QWidget()

# TODO(crbug.com/994009): Prefer to use maximize, which doesn't work currently.
# This workaround will break if tast tests start running on multi-monitor.
s = app.primaryScreen().size()
w.setGeometry(0, 0, s.width(), s.height())

p = w.palette()
p.setColor(w.backgroundRole(), QColor(255, 0, 255))
w.setPalette(p)

w.show()
sys.exit(app.exec_())
예제 #24
0
class Ui_S_Login(QWidget):
    #告知主窗口登录完成的信号
    _haslogged = pyqtSignal(int, str, str, int)

    def setupUi(self, parent):
        #继承在主窗口上
        self.parent = parent

        #子界面上的作画区
        self.Form = QWidget(parent)  #生成在父界面上
        self.Form.setGeometry(QtCore.QRect(0, 70, 1200, 590))
        self.Form.setObjectName("Form")
        self.Form.resize(1200, 590)
        jpeg = QtGui.QPixmap()
        jpeg.load("pictures/servent/LoginBg.jpg")
        palette1 = QtGui.QPalette()
        palette1.setBrush(self.Form.backgroundRole(), QtGui.QBrush(jpeg))
        self.Form.setPalette(palette1)
        self.Form.setAutoFillBackground(True)

        #标题栏
        # self.label = QtWidgets.QLabel(self.Form)
        # self.label.setGeometry(QtCore.QRect(60, 18, 301, 41))
        # self.label.setStyleSheet("border-bottom:1px groove  rgb(255, 85, 0);background-color: rgb(255, 255, 255,160);")
        # self.label.setObjectName("label")
        # 输入框-房间号
        self.widget_room = QtWidgets.QWidget(self.Form)
        self.widget_room.setGeometry(QtCore.QRect(430, 160, 370, 50))
        self.widget_room.setStyleSheet("background-color: rgba(0,0,0,0);")
        self.widget_room.setObjectName("widget_room")
        # lable_房间号
        # self.label_room = QtWidgets.QLabel(self.widget_room)
        # self.label_room.setGeometry(QtCore.QRect(0, 0, 80, 50))
        # self.label_room.setStyleSheet("border-right:1px groove  rgb(255, 85, 0);")
        # self.label_room.setAlignment(QtCore.Qt.AlignCenter)
        # self.label_room.setObjectName("label_room")
        # input_房间号
        self.lineEdit_room = QtWidgets.QLineEdit(self.widget_room)
        self.lineEdit_room.setGeometry(QtCore.QRect(0, 0, 370, 50))
        self.lineEdit_room.setStyleSheet(
            "border-color: rgba(0, 0, 0, 0);font: 11pt 'Adobe Hebrew';")
        self.lineEdit_room.setStyleSheet(
            "QLineEdit{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
        self.lineEdit_room.setObjectName("lineEdit_room")

        #输入框-登录名
        self.widget = QtWidgets.QWidget(self.Form)
        self.widget.setGeometry(QtCore.QRect(430, 260, 370, 50))
        self.widget.setStyleSheet("background-color: rgba(0,0,0,0);")
        self.widget.setObjectName("widget")
        #lable_登录名
        # self.label_id = QtWidgets.QLabel(self.widget)
        # self.label_id.setGeometry(QtCore.QRect(0, 0, 80, 50))
        # self.label_id.setStyleSheet("border-right:1px groove  rgb(255, 85, 0);")
        # self.label_id.setAlignment(QtCore.Qt.AlignCenter)
        # self.label_id.setObjectName("label_id")
        #input_登录名
        self.lineEdit_id = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_id.setGeometry(QtCore.QRect(0, 0, 370, 50))
        self.lineEdit_id.setStyleSheet(
            "border-color: rgba(0, 0, 0, 0);font: 11pt 'Adobe Hebrew';")
        self.lineEdit_id.setStyleSheet(
            "QLineEdit{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
        self.lineEdit_id.setObjectName("lineEdit")

        # 输入框-身份证号
        self.widget_2 = QtWidgets.QWidget(self.Form)
        self.widget_2.setGeometry(QtCore.QRect(430, 360, 370, 50))
        self.widget_2.setStyleSheet("background-color: rgba(0,0,0,0);")
        self.widget_2.setObjectName("widget_2")
        # lable_身份证号
        # self.label_card = QtWidgets.QLabel(self.widget_2)
        # self.label_card.setGeometry(QtCore.QRect(0, 0, 80, 50))
        # self.label_card.setStyleSheet("border-right:1px groove  rgb(255, 85, 0);")
        # self.label_card.setAlignment(QtCore.Qt.AlignCenter)
        # self.label_card.setObjectName("label_card")
        # input_身份证号
        self.lineEdit_card = QtWidgets.QLineEdit(self.widget_2)
        self.lineEdit_card.setGeometry(QtCore.QRect(0, 0, 370, 50))
        self.lineEdit_card.setStyleSheet(
            "border-color: rgba(0, 0, 0, 0);font: 11pt 'Adobe Hebrew';")
        self.lineEdit_card.setStyleSheet(
            "QLineEdit{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")
        self.lineEdit_card.setObjectName("lineEdit_2")

        #登录按钮

        self.pushButton = QtWidgets.QPushButton(self.Form)
        self.pushButton.setGeometry(QtCore.QRect(325, 470, 550, 50))
        # self.pushButton.setStyleSheet("border-radius:10px;background-color: rgb(255, 255, 255);")
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setStyleSheet(
            "QPushButton{border-style:outset;border-radius: 10px;border-color: beige;font: bold 14px;}"
            "QPushButton{background-image: url(pictures/servent/LoginButton.png);}"
            "QPushButton:hover{background-image: url(pictures/servent/LoginButton.png);}"
            "QPushButton:pressed{background-image: url(pictures/servent/LoginButton.png);}"
        )
        self.pushButton.clicked.connect(self.checkInp)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self.Form)
        self.logincontroller = S_LoginController()
        self.logincontroller._haslogged.connect(self.loginRes)
        self.logincontroller._inputFailed.connect(self.showMessageBox)

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.Form.setWindowTitle(_translate("Form", "Form"))
        # self.label_room.setText(_translate("Form", "房间号"))
        # self.label_id.setText(_translate("Form", "用户名"))
        # self.pushButton.setText(_translate("Form", "登录"))
        # self.label.setText(_translate("Form", "从机用户登录"))
        # self.label_card.setText(_translate("Form", "身份证号"))

    def hide(self):
        self.Form.hide()

    def show(self):
        self.Form.show()
        self.Form.raise_()

    #交互请求:登录
    def checkInp(self):
        #取输入的用户名与身份证号
        roomNo = self.lineEdit_room.text()
        userName = self.lineEdit_id.text()
        id_card = self.lineEdit_card.text()

        #调用控制器的登录认证函数
        self.logincontroller.Login(roomNo, userName, id_card)

    def showMessageBox(self, res, Msg):
        #根据认证结果弹窗,执行下一步
        Message = QMessageBox()  #一个消息框
        #消息框的类型(内置了五种好像)(本体,标题,正文,按键组)
        if res == True:
            QMessageBox.information(Message, "Message", Msg, QMessageBox.Ok)
        else:
            QMessageBox.information(Message, "Message", Msg, QMessageBox.Ok)

    def loginRes(self, roomNo, res, Name, Password, Mode):
        #根据认证结果弹窗,执行下一步
        if res == 1:
            self.showMessageBox(True, "登录成功!")
            self.hide()
            self._haslogged.emit(roomNo, Name, Password, Mode)
        else:
            self.showMessageBox(False, "登录失败,请检查输入,或确定房间是否已被登录")
예제 #25
0
class Ui_StatusDisplay(QWidget):

    _changedFreq = pyqtSignal(int)

    mtemp = 0.00
    mvelocity = 0
    controller = M_StatusController.StatusController()
    mfreq = 0
    mstrat = 0
    mconnec = []
    mstatus = ""

    def setupUi(self, MainWindow):
        self.reflashTimer = QTimer()
        self.reflashTimer.setInterval(2000)
        self.reflashTimer.timeout.connect(self.showCurrentRoom)
        self.reflashTimer.start()

        self.StatusDisplay = QWidget(MainWindow)
        self.StatusDisplay.setObjectName("StatusDisplay")
        self.StatusDisplay.resize(1200, 590)
        self.StatusDisplay.setGeometry(QtCore.QRect(0, 70, 1200, 590))
        jpeg = QtGui.QPixmap()
        jpeg.load("pictures/StatusBg.png")
        palette1 = QtGui.QPalette()
        palette1.setBrush(self.StatusDisplay.backgroundRole(),
                          QtGui.QBrush(jpeg))
        self.StatusDisplay.setPalette(palette1)
        self.StatusDisplay.setAutoFillBackground(True)

        self.tempLabel = QtWidgets.QLabel(self.StatusDisplay)
        self.tempLabel.setGeometry(QtCore.QRect(650, 150, 200, 100))
        self.tempLabel.setObjectName("tempLabel")
        self.tempLabel.setStyleSheet(
            "QLabel{color:rgb(255,255,255);font: 75 30pt \"微软雅黑\";}")

        self.veloLabel = QtWidgets.QLabel(self.StatusDisplay)
        self.veloLabel.setGeometry(QtCore.QRect(950, 150, 150, 90))
        self.veloLabel.setObjectName("veloLabel")
        self.veloLabel.setStyleSheet(
            "QLabel{color:rgb(255,255,255);font: 75 24pt \"微软雅黑\";}")

        self.statuLabel = QtWidgets.QLabel(self.StatusDisplay)
        self.statuLabel.setGeometry(QtCore.QRect(220, 195, 200, 40))
        self.statuLabel.setObjectName("statuLabel")
        self.statuLabel.setStyleSheet(
            "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")

        self.statuWidget = QtWidgets.QWidget(self.StatusDisplay)
        self.statuWidget.setGeometry(QtCore.QRect(75, 260, 440, 40))
        self.statuWidget.setObjectName("statuWidget")

        self.modelRadioButton = QtWidgets.QRadioButton(self.statuWidget)
        self.modelRadioButton.setGeometry(QtCore.QRect(0, 0, 132, 34))
        self.modelRadioButton.setObjectName("radioButton")
        self.modelRadioButton.setText("制冷")
        self.modelRadioButton.setStyleSheet(
            "QRadioButton{color:rgb(255,255,255);font: 75 9pt \"微软雅黑\";}")

        self.modelRadioButton_2 = QtWidgets.QRadioButton(self.statuWidget)
        self.modelRadioButton_2.setGeometry(QtCore.QRect(160, 0, 132, 34))
        self.modelRadioButton_2.setObjectName("radioButton_2")
        self.modelRadioButton_2.setText("制热")
        self.modelRadioButton_2.setStyleSheet(
            "QRadioButton{color:rgb(255,255,255);font: 75 9pt \"微软雅黑\";}")

        self.ModelStraconfButton = QtWidgets.QPushButton(self.statuWidget)
        self.ModelStraconfButton.setGeometry(QtCore.QRect(325, 0, 112, 34))
        self.ModelStraconfButton.setObjectName("straconfButton")
        self.ModelStraconfButton.setStyleSheet(
            "QPushButton{border-style:outset;border-radius: 10px;border-color: beige;font: bold 14px;}"
            "QPushButton{background-image: url(pictures/statuButton.png);}"
            "QPushButton:hover{background-image: url(pictures/statuButton.png);}"
            "QPushButton:pressed{background-image: url(pictures/statuButton3.png);}"
        )
        self.ModelStraconfButton.clicked.connect(self.on_ModelButton_clicked)

        self.roomWidget = QtWidgets.QWidget(self.StatusDisplay)
        self.roomWidget.setGeometry(QtCore.QRect(650, 390, 450, 100))
        self.roomWidget.setObjectName("roomWidget")

        self.roomLabel = QtWidgets.QLabel(self.roomWidget)
        self.roomLabel.setGeometry(QtCore.QRect(0, 0, 450, 100))
        self.roomLabel.setObjectName("roomLabel")
        self.roomLabel.setStyleSheet(
            "QLabel{color:rgb(255,255,255);font: 75 14pt \"微软雅黑\";}")

        ##############获取频率——spinbox############
        self.freqSpinbox = QtWidgets.QSpinBox(self.StatusDisplay)
        self.freqSpinbox.setGeometry(QtCore.QRect(145, 120, 100, 40))
        self.freqSpinbox.setObjectName("freqSpinbox")
        self.freqSpinbox.setRange(1, 20)
        self.freqSpinbox.setStyleSheet(
            "border-radius:3px;padding:2px 4px;background-color: rgb(91,155,213,190);color:rgb(255,255,255);font: 8pt '微软雅黑'}"
        )

        self.freqButton = QtWidgets.QPushButton(self.StatusDisplay)
        self.freqButton.setGeometry(QtCore.QRect(330, 123, 112, 34))
        self.freqButton.setObjectName("freqButton")
        self.freqButton.setStyleSheet(
            "QPushButton{border-style:outset;border-radius: 10px;border-color: beige;font: bold 14px;}"
            "QPushButton{background-image: url(pictures/freqButton.png);}"
            "QPushButton:hover{background-image: url(pictures/freqButton.png);}"
            "QPushButton:pressed{background-image: url(pictures/freqButton3.png);}"
        )

        self.freqLabel = QtWidgets.QLabel(self.StatusDisplay)
        self.freqLabel.setGeometry(QtCore.QRect(220, 55, 200, 40))
        self.freqLabel.setObjectName("freqLabel")
        self.freqLabel.setStyleSheet(
            "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")

        # self.freqButton.clicked.connect(self.freqChanged)
        ##############获取策略——RadioButton#################
        self.stratWidget = QtWidgets.QWidget(self.StatusDisplay)
        self.stratWidget.setGeometry(QtCore.QRect(75, 410, 452, 22))
        self.stratWidget.setObjectName("stratWidget")

        self.radioButton = QtWidgets.QRadioButton(self.stratWidget)
        self.radioButton.setGeometry(QtCore.QRect(0, 0, 132, 22))
        self.radioButton.setObjectName("radioButton")
        self.radioButton.setStyleSheet(
            "QRadioButton{color:rgb(255,255,255);font: 75 9pt \"微软雅黑\";}")

        self.radioButton_2 = QtWidgets.QRadioButton(self.stratWidget)
        self.radioButton_2.setGeometry(QtCore.QRect(160, 0, 132, 22))
        self.radioButton_2.setObjectName("radioButton_2")
        self.radioButton_2.setStyleSheet(
            "QRadioButton{color:rgb(255,255,255);font: 75 9pt \"微软雅黑\";}")

        self.radioButton_3 = QtWidgets.QRadioButton(self.stratWidget)
        self.radioButton_3.setGeometry(QtCore.QRect(320, 0, 132, 22))
        self.radioButton_3.setObjectName("radioButton_3")
        self.radioButton_3.setStyleSheet(
            "QRadioButton{color:rgb(255,255,255);font: 75 9pt \"微软雅黑\";}")
        self.radioButton_3.hide()

        self.stratLabel = QtWidgets.QLabel(self.StatusDisplay)
        self.stratLabel.setGeometry(QtCore.QRect(220, 331, 200, 40))
        self.stratLabel.setObjectName("stratLabel")
        self.stratLabel.setStyleSheet(
            "QLabel{color:rgb(255,255,255);font: 75 12pt \"微软雅黑\";}")

        self.straconfButton = QtWidgets.QPushButton(self.StatusDisplay)
        self.straconfButton.setGeometry(QtCore.QRect(250, 470, 112, 34))
        self.straconfButton.setObjectName("straconfButton")
        self.straconfButton.setStyleSheet(
            "QPushButton{border-style:outset;border-radius: 10px;border-color: beige;font: bold 14px;}"
            "QPushButton{background-image: url(pictures/stratButton.png);}"
            "QPushButton:hover{background-image: url(pictures/stratButton.png);}"
            "QPushButton:pressed{background-image: url(pictures/stratButton3.png);}"
        )

        self.showMes()

        self.straconfButton.clicked.connect(self.on_tellmeButton_clicked)

        # ################频率微调和滑块信号槽#############
        # self.freqSlider.valueChanged.connect(self.freqSpinbox.setValue)
        self.freqButton.clicked.connect(self.freqChanged)

        self.retranslateUi(self.StatusDisplay)
        QtCore.QMetaObject.connectSlotsByName(self.StatusDisplay)

    def on_tellmeButton_clicked(self):
        #print("radio changed")
        if (self.radioButton.isChecked()):
            self.controller.strat = 1
        if (self.radioButton_2.isChecked()):
            self.controller.strat = 2
        if (self.radioButton_3.isChecked()):
            self.controller.strat = 3
        self.controller.changeStrat()
        self.showMes()

    def on_ModelButton_clicked(self):
        if (self.modelRadioButton.isChecked()):
            self.controller.changeStatus(0)
        if (self.modelRadioButton_2.isChecked()):
            self.controller.changeStatus(1)
        self.showMes()

    def freqChanged(self):
        self.controller.freq = int(self.freqSpinbox.value())
        print("to change freq as %d" % (self.controller.freq))
        self._changedFreq.emit(self.controller.freq)
        self.controller.changeFreq()
        self.showMes()

    def retranslateUi(self, StatusDisplay):
        _translate = QtCore.QCoreApplication.translate
        StatusDisplay.setWindowTitle(_translate("StatusDisplay", "Form"))
        # self.straconfButton.setText(_translate("StatusDisplay", "确认"))
        # self.freqButton.setText(_translate("StatusDisplay", "确认"))
        # self.label.setText(_translate("StatusDisplay", "温度:"))
        # self.label_2.setText(_translate("StatusDisplay", "风速:"))
        # self.label_3.setText(_translate("StatusDisplay", "工作模式:"))
        self.radioButton.setText(_translate("StatusDisplay", "时间片轮询"))
        self.radioButton_2.setText(_translate("StatusDisplay", "高速风优先"))
        self.radioButton_3.setText(_translate("StatusDisplay", "先来先服务"))
        # self.label_4.setText(_translate("StatusDisplay", "当前连接房间:"))

    def showMes(self):
        del self.mconnec[:]
        self.controller.getFreq()
        self.controller.getStrat()
        print("status is ", self.controller.getStatu())
        if (self.controller.getStatu() == 0):
            self.mtemp = 22.0
            self.modelRadioButton.setChecked(True)
            self.modelRadioButton_2.setChecked(False)
            self.statuLabel.setText("制冷")
        else:
            self.mtemp = 28.0
            self.modelRadioButton.setChecked(False)
            self.modelRadioButton_2.setChecked(True)
            self.statuLabel.setText("制热")

        self.tempLabel.setText(str(self.mtemp) + '℃')
        self.showCurrentRoom()
        #####刷新测试
        #self.roomLabel.setNum(time.clock())

        if self.controller.strat == 1:
            self.radioButton.setChecked(True)
            self.radioButton_2.setChecked(False)
            self.radioButton_3.setChecked(False)
            self.stratLabel.setText("时间片轮询")
        elif self.controller.strat == 2:
            self.radioButton.setChecked(False)
            self.radioButton_2.setChecked(True)
            self.radioButton_3.setChecked(False)
            self.stratLabel.setText("高速风优先抢占")
        elif self.controller.strat == 3:
            self.radioButton.setChecked(False)
            self.radioButton_2.setChecked(False)
            self.radioButton_3.setChecked(True)
            self.stratLabel.setText("先来先服务")

        self.freqSpinbox.setValue(self.controller.freq)
        self.freqLabel.setNum(self.controller.freq)

    def showCurrentRoom(self):
        list = self.controller.getConnec()
        x = 0
        connecstr = ""
        while x < len(list):
            connecstr += str(list[x])
            if (x == 2):
                connecstr += "\n"
            else:
                connecstr += "\t"
            x += 1
        self.roomLabel.setText(connecstr)

        if connecstr == "":
            self.veloLabel.setText("待机中")
        else:
            self.veloLabel.setText("工作中")
예제 #26
0
        recordingBtn.move(370, 350)
        recordingBtn.setStyleSheet("background:red;")
        recording = True


# 创建应用
app = QApplication(sys.argv)

# 创建各个窗体
## 创建起始窗体
startWindow = QWidget()
startWindow.setWindowTitle("VoiceTracker")
startWindow.resize(790, 440)
startWindow.move(300, 300)
palette = QPalette()
palette.setBrush(startWindow.backgroundRole(), QBrush(QPixmap('start.jpg')))
startWindow.setPalette(palette)
## 创建主窗体
mainWindow = QWidget()
mainWindow.setWindowTitle("VoiceTracker")
mainWindow.resize(790, 440)
mainWindow.move(300, 300)
palette = QPalette()
palette.setBrush(mainWindow.backgroundRole(), QBrush(QPixmap('main.jpg')))
mainWindow.setPalette(palette)
mainWindow.closeEvent = lambda x: showStart()
## 创建语音库窗体
modelWindow = QWidget()
modelWindow.setWindowTitle("VoiceTracker")
modelWindow.resize(790, 440)
modelWindow.move(300, 300)
예제 #27
0
    opt1.move(1080, 100)
    opt1.setStyleSheet(
        'QPushButton {background-color: #b41bf2 ; color: black;}')
    opt1.show()
    opt1.clicked.connect(option1)
    opt2 = QPushButton("Option 2", w7)
    opt2.move(1180, 100)
    opt2.setStyleSheet(
        'QPushButton {background-color: #b41bf2 ; color: black;}')
    opt2.show()
    opt2.clicked.connect(option2)
    opt3 = QPushButton("Option 3", w7)
    opt3.move(1080, 150)
    opt3.setStyleSheet(
        'QPushButton {background-color: #b41bf2 ; color: black;}')
    opt3.show()
    opt3.clicked.connect(option3)
    opt4 = QPushButton("Option 4", w7)
    opt4.move(1180, 150)
    opt4.setStyleSheet(
        'QPushButton {background-color: #b41bf2 ; color: black;}')
    opt4.show()
    opt4.clicked.connect(option4)
    w7.show()
    parent.resize(1500, 1000)
    pt = parent.palette()
    pt.setColor(parent.backgroundRole(), QColor(245, 183, 5))
    parent.setPalette(pt)
    parent.show()
    sys.exit(app.exec_())
예제 #28
0
from PyQt5 import QtGui, Qt, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout
import sys


from PyQt5.QtWidgets import QApplication, QWidget

if __name__ == '__main__':
    app = QApplication(sys.argv)

    w = QWidget()
    w.resize(700, 600)
    w.move(200, 200)
    p = w.palette()
    p.setColor(w.backgroundRole(), QtCore.Qt.lightGray)
    w.setPalette(p)
    w.setWindowTitle('Simple')

    tableWidget = QTableWidget()
    tableWidget.setRowCount(5)
    tableWidget.setColumnCount(3)
    tableWidget.setItem(0, 0, QTableWidgetItem("Nome"))
    tableWidget.setItem(0, 1, QTableWidgetItem("Telefone"))
    tableWidget.setItem(0, 2, QTableWidgetItem("Email"))

    w.show()

    sys.exit(app.exec_())
예제 #29
0
파일: qtplayer.py 프로젝트: filnet/player
    def create_window(self, args):
        self.window = QWidget()
        self.window.setWindowTitle("Player")
        self.window.setGeometry(100, 100, 640, 580)

        # video window
        self.video_widget = VideoWidget()

        size_policy = self.video_widget.sizePolicy()
        size_policy.setHorizontalPolicy(QSizePolicy.Expanding)
        size_policy.setVerticalPolicy(QSizePolicy.Expanding)
        self.video_widget.setSizePolicy(size_policy)

        # tracker
        self.tracker = TrackerWidget()
        self.tracker.setTracking(args.tracking)
        #self.tracker.valueChanged.connect(lambda value: print("%s / %s" % (value, self.tracker.maximum())))
        #self.tracker.sliderMoved.connect(lambda value: print("*** %s / %s" % (value, self.tracker.maximum())))

        # buttons
        self.play_button = self.create_button("media-playback-start")
        self.pause_button = self.create_button("media-playback-pause")
        self.stop_button = self.create_button("media-playback-stop")
        self.seek_backward_button = self.create_button("media-seek-backward")
        self.seek_forward_button = self.create_button("media-seek-forward")
        self.skip_backward_button = self.create_button("media-skip-backward")
        self.skip_forward_button = self.create_button("media-skip-forward")
        self.media_previous_button = self.create_button("go-previous")
        self.media_next_button = self.create_button("go-next")

        # buttons window
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(QMargins(5, 5, 2, 2))
        button_layout.setSpacing(5)

        button_layout.addWidget(self.play_button)
        button_layout.addWidget(self.pause_button)
        button_layout.addWidget(self.stop_button)
        button_layout.addWidget(self.seek_backward_button)
        button_layout.addWidget(self.seek_forward_button)
        button_layout.addStretch(1)
        button_layout.addWidget(self.media_previous_button)
        button_layout.addWidget(self.media_next_button)

        buttons_window = QWidget()
        buttons_window.setLayout(button_layout)

        palette = buttons_window.palette()
        palette.setColor(buttons_window.backgroundRole(), Qt.black)
        buttons_window.setPalette(palette)
        buttons_window.setAutoFillBackground(True)

        # layout
        layout = QVBoxLayout()
        layout.setContentsMargins(QMargins(0, 0, 0, 0))
        layout.setSpacing(0)

        layout.addWidget(self.video_widget)
        layout.addWidget(self.tracker)
        layout.addWidget(buttons_window)

        self.window.setLayout(layout)
예제 #30
0
class Window(QWidget):
    BorderWidth = 5

    def __init__(self):
        super().__init__()
        # get the available resolutions without taskbar
        self._rect = QApplication.instance().desktop().availableGeometry(self)
        self.resize(800, 600)
        self.setWindowFlags(Qt.Window
                            | Qt.FramelessWindowHint
                            | Qt.WindowSystemMenuHint
                            | Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        # Create a thin frame
        style = win32gui.GetWindowLong(int(self.winId()), win32con.GWL_STYLE)
        win32gui.SetWindowLong(int(self.winId()), win32con.GWL_STYLE,
                               style | win32con.WS_THICKFRAME)

        if QtWin.isCompositionEnabled():
            # Aero Shadow
            QtWin.extendFrameIntoClientArea(self, -1, -1, -1, -1)
        else:
            QtWin.resetExtendedFrame(self)

        # Window Widgets
        self._layout = QVBoxLayout()
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self.controlWidget = AnotherWidget()
        self.controlWidget.setObjectName("controlWidget")

        # main widget is here
        self.mainWidget = QWidget()
        self.mainWidgetLayout = QVBoxLayout()
        self.mainWidgetLayout.setContentsMargins(0, 0, 0, 0)
        self.mainWidget.setLayout(self.mainWidgetLayout)
        self.mainWidget.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)

        # set background color
        self.mainWidget.setAutoFillBackground(True)
        p = self.mainWidget.palette()
        p.setColor(self.mainWidget.backgroundRole(), QColor("#272727"))
        self.mainWidget.setPalette(p)

        self._layout.addWidget(self.controlWidget)
        self._layout.addWidget(self.mainWidget)
        self.setLayout(self._layout)
        self.show()

    def nativeEvent(self, eventType, message):
        retval, result = super().nativeEvent(eventType, message)

        # if you use Windows OS
        if eventType == "windows_generic_MSG":
            msg = ctypes.wintypes.MSG.from_address(message.__int__())
            # Get the coordinates when the mouse moves.
            x = win32api.LOWORD(ctypes.c_long(
                msg.lParam).value) - self.frameGeometry().x()
            y = win32api.HIWORD(ctypes.c_long(
                msg.lParam).value) - self.frameGeometry().y()

            # Determine whether there are other controls(i.e. widgets etc.) at the mouse position.
            if self.childAt(x, y) is not None and self.childAt(
                    x, y) is not self.findChild(QWidget, "controlWidget"):
                # passing
                if self.width() - 5 > x > 5 and y < self.height() - 5:
                    return retval, result

            if msg.message == win32con.WM_NCCALCSIZE:
                # Remove system title
                return True, 0
            if msg.message == win32con.WM_GETMINMAXINFO:
                # This message is triggered when the window position or size changes.
                info = ctypes.cast(msg.lParam,
                                   ctypes.POINTER(MINMAXINFO)).contents
                # Modify the maximized window size to the available size of the main screen.
                info.ptMaxSize.x = self._rect.width()
                info.ptMaxSize.y = self._rect.height()
                # Modify the x and y coordinates of the placement point to (0,0).
                info.ptMaxPosition.x, info.ptMaxPosition.y = 0, 0

            if msg.message == win32con.WM_NCHITTEST:
                w, h = self.width(), self.height()
                lx = x < self.BorderWidth
                rx = x > w - self.BorderWidth
                ty = y < self.BorderWidth
                by = y > h - self.BorderWidth
                if lx and ty:
                    return True, win32con.HTTOPLEFT
                if rx and by:
                    return True, win32con.HTBOTTOMRIGHT
                if rx and ty:
                    return True, win32con.HTTOPRIGHT
                if lx and by:
                    return True, win32con.HTBOTTOMLEFT
                if ty:
                    return True, win32con.HTTOP
                if by:
                    return True, win32con.HTBOTTOM
                if lx:
                    return True, win32con.HTLEFT
                if rx:
                    return True, win32con.HTRIGHT
                # Title
                return True, win32con.HTCAPTION

        return retval, result
예제 #31
0
class MultiPanelGui(QWidget):
    def __init__(self, parent=None, window=None, devicewrapper_lst1=None, devicewrapper_lst2 = None):
        """ """
        print(window)
        super(MultiPanelGui, self).__init__(parent=parent)
        self._init_ui(mainwindow = window, devicewrapper_lst1 = devicewrapper_lst1, devicewrapper_lst2 =devicewrapper_lst2)

    def _init_ui(self, mainwindow, devicewrapper_lst1, devicewrapper_lst2):
        """
        Creates and Loads the widgets in the GUI
        """
        # =====================================================================
        # Creates and configures central widget for window
        # =====================================================================
        print(mainwindow)
        self.central_wid = QWidget(mainwindow)
        self._set_central_wid_properties()
        self.mainwindow = mainwindow
        print(self.mainwindow)
        self.mainwindow.setCentralWidget(self.central_wid)
        # =====================================================================
        # control panel - initializes layout item to put widgets
        # =====================================================================
        self.graphics_layout = QGridLayout()

        self.mainwindow.create_subwindow(500, 200)
        print(self.mainwindow.subwindow)
        # self.graphics_layout.addWidget(self.subwindow, 0, 0, 1, 1)
        print(devicewrapper_lst1)
        print(devicewrapper_lst2)
        # self.sub_gui_1 = TimePlotGui(
        #     parent=None,
        #     window=mainwindow,
        #     devicewrapper_lst = devicewrapper_lst1
        # )
        # print('created sub 1 but not sub 2')
        # print(self.subwindow)
        self.sub_gui_2 = TimePlotGui(
            parent=None,
            window= self.mainwindow.subwindow,
            devicewrapper_lst = devicewrapper_lst2
        )
        #self.sub_gui_2.show()
        print('created sub 2')
        # self.sub_gui_1.setFixedSize(QSize(10, 10))
        #self.sub_gui_2.setFixedSize(QSize(500, 30))
        # self.graphics_layout.addWidget(self.sub_gui_1, 0, 0, 1, 1)
        #self.graphics_layout.addWidget(self.sub_gui_2, 1, 1, 1, 1)
        # =====================================================================
        # control buttons - Non-plot widgets (stop/start buttons and spacers) created
        # =====================================================================
        # self.playBtn = QPushButton()
        # self.playBtn.setFixedSize(QSize(30, 30))
        # self.playBtn.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        # points = [QPoint(0, 0), QPoint(0, self.playBtn.height()), QPoint(self.playBtn.width(), self.playBtn.height()/2)]
        # self.playBtn.setMask(QRegion(QPolygon(points)))
        # self.playBtn.setStyleSheet("background-color: rgb(120,120,120);")
        #
        # self.squarestopBtn = QPushButton()
        # self.squarestopBtn.setFixedSize(QSize(110, 30))
        # self.squarestopBtn.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        # points = [QPoint((self.squarestopBtn.width()+50)/2, 0), \
        #         QPoint((self.squarestopBtn.width()+50)/2, self.squarestopBtn.height()), \
        #         QPoint(self.squarestopBtn.width(), self.squarestopBtn.height()), \
        #         QPoint(self.squarestopBtn.width(), 0)]
        # self.squarestopBtn.setMask(QRegion(QPolygon(points)))
        # self.squarestopBtn.setStyleSheet("background-color: rgb(120,120,120);")
        #
        # self.graphics_layout.addWidget(self.squarestopBtn, 0, 1, 1, 1)
        # self.graphics_layout.addWidget(self.playBtn, 1, 0, 1, 1)

        self.central_wid.setLayout(self.graphics_layout)


    def _set_central_wid_properties(self):
        """ """
        self.central_wid.setAutoFillBackground(True)
        p = self.central_wid.palette()
        p.setColor(self.central_wid.backgroundRole(), QtCore.Qt.darkGray)
        self.central_wid.setPalette(p)