Exemplo n.º 1
0
 def setupUi(self, Form):
     Form.setObjectName("Form")
     Form.resize(700, 367)
     Form.setMinimumSize(QtCore.QSize(700, 367))
     Form.setMaximumSize(QtCore.QSize(700, 367))
     palette = QPalette()
     palette.setBrush(QPalette.Background,
                      QBrush(QPixmap('userInterface/haoche.jpg')))
     self.setPalette(palette)
     Form.setStyleSheet("#Form{\n"
                        "\n"
                        "border-image:url(:/mainwindow/haoche.jpg)\n"
                        "}")
     self.agentfile = QtWidgets.QPushButton(Form)
     self.agentfile.setGeometry(QtCore.QRect(280, 90, 51, 51))
     self.agentfile.setStyleSheet(
         "border-image:url(:/mainwindow/filepath.jpg)")
     self.agentfile.setText("")
     self.agentfile.setObjectName("agentfile")
     self.label = QtWidgets.QLabel(Form)
     self.label.setGeometry(QtCore.QRect(30, 80, 251, 71))
     font = QtGui.QFont()
     font.setFamily("华文隶书")
     font.setPointSize(24)
     self.label.setFont(font)
     self.label.setStyleSheet("color:rgb(255, 255, 255);")
     self.label.setObjectName("label")
     self.label_2 = QtWidgets.QLabel(Form)
     self.label_2.setGeometry(QtCore.QRect(40, 180, 191, 71))
     font = QtGui.QFont()
     font.setFamily("华文隶书")
     font.setPointSize(24)
     self.label_2.setFont(font)
     self.label_2.setStyleSheet("color:rgb(255, 255, 255);")
     self.label_2.setObjectName("label_2")
     self.lineEdit = QtWidgets.QLineEdit(Form)
     self.lineEdit.setGeometry(QtCore.QRect(240, 200, 411, 41))
     font = QtGui.QFont()
     font.setFamily("华文隶书")
     font.setPointSize(14)
     self.lineEdit.setFont(font)
     self.lineEdit.setText("")
     self.lineEdit.setObjectName("lineEdit")
     self.lineEdit_2 = QtWidgets.QLineEdit(Form)
     self.lineEdit_2.setGeometry(QtCore.QRect(340, 100, 311, 41))
     font = QtGui.QFont()
     font.setFamily("华文隶书")
     font.setPointSize(14)
     self.lineEdit_2.setFont(font)
     self.lineEdit_2.setObjectName("lineEdit_2")
     self.pushButton_2 = QtWidgets.QPushButton(Form)
     self.pushButton_2.setGeometry(QtCore.QRect(500, 280, 131, 51))
     self.pushButton_2.setStyleSheet(
         "QPushButton{\n"
         "    border-radius:25px;\n"
         "    background-color:rgb(255, 255, 255); \n"
         "    color: rgb(0, 170, 255)\n"
         "}\n"
         "\n"
         "QPushButton:pressed{\n"
         "  background-color:rgb(173, 115, 0)\n"
         "}")
     self.pushButton_2.setObjectName("pushButton_2")
     self.pushButton_2.clicked.connect(self.close)
     self.retranslateUi(Form)
     QtCore.QMetaObject.connectSlotsByName(Form)
Exemplo n.º 2
0
 def __spawnColor():
     """spawns a random color"""
     palette = QPalette()
     palette.setColor(QPalette.Background, QtGui.QColor(*random.choice(possible_colors)))
     return palette
Exemplo n.º 3
0
    def initUI(self):

        # ==================== FRAME ENCABEZADO ====================

        paleta = QPalette()
        paleta.setColor(QPalette.Background, QColor(51, 0, 102))

        frame = QFrame(self)
        frame.setFrameShape(QFrame.NoFrame)
        frame.setFrameShadow(QFrame.Sunken)
        frame.setAutoFillBackground(True)
        frame.setPalette(paleta)
        frame.setFixedWidth(400)
        frame.setFixedHeight(84)
        frame.move(0, 0)

        labelIcono = QLabel(frame)
        labelIcono.setFixedWidth(40)
        labelIcono.setFixedHeight(40)
        labelIcono.setPixmap(
            QPixmap("./assets/icono.png").scaled(40, 40, Qt.KeepAspectRatio,
                                                 Qt.SmoothTransformation))
        labelIcono.move(37, 22)

        fuenteTitulo = QFont()
        fuenteTitulo.setPointSize(20)
        fuenteTitulo.setBold(True)

        labelTitulo = QLabel("<font color='white'>Proyección</font>", frame)
        labelTitulo.setFont(fuenteTitulo)
        labelTitulo.move(90, 20)

        fuenteSubtitulo = QFont()
        fuenteSubtitulo.setPointSize(12)

        labelSubtitulo = QLabel(
            "<font color='white'>Pronósticos de ventas"
            ".</font>", frame)
        labelSubtitulo.setFont(fuenteSubtitulo)
        labelSubtitulo.move(115, 50)

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

        labelUsuario = QLabel("Usuario", self)
        labelUsuario.move(60, 170)

        frameUsuario = QFrame(self)
        frameUsuario.setFrameShape(QFrame.StyledPanel)
        frameUsuario.setFixedWidth(280)
        frameUsuario.setFixedHeight(28)
        frameUsuario.move(60, 196)

        imagenUsuario = QLabel(frameUsuario)
        imagenUsuario.setPixmap(
            QPixmap("./assets/usuario.png").scaled(20, 20, Qt.KeepAspectRatio,
                                                   Qt.SmoothTransformation))
        imagenUsuario.move(10, 4)

        self.lineEditUsuario = QLineEdit(frameUsuario)
        self.lineEditUsuario.setFrame(False)
        self.lineEditUsuario.setTextMargins(8, 0, 4, 1)
        self.lineEditUsuario.setFixedWidth(238)
        self.lineEditUsuario.setFixedHeight(26)
        self.lineEditUsuario.move(40, 1)

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

        labelContrasenia = QLabel("Contraseña", self)
        labelContrasenia.move(60, 224)

        frameContrasenia = QFrame(self)
        frameContrasenia.setFrameShape(QFrame.StyledPanel)
        frameContrasenia.setFixedWidth(280)
        frameContrasenia.setFixedHeight(28)
        frameContrasenia.move(60, 250)

        imagenContrasenia = QLabel(frameContrasenia)
        imagenContrasenia.setPixmap(
            QPixmap("./assets/contrasena.png").scaled(20, 20,
                                                      Qt.KeepAspectRatio,
                                                      Qt.SmoothTransformation))
        imagenContrasenia.move(10, 4)

        self.lineEditContrasenia = QLineEdit(frameContrasenia)
        self.lineEditContrasenia.setFrame(False)
        self.lineEditContrasenia.setEchoMode(QLineEdit.Password)
        self.lineEditContrasenia.setTextMargins(8, 0, 4, 1)
        self.lineEditContrasenia.setFixedWidth(238)
        self.lineEditContrasenia.setFixedHeight(26)
        self.lineEditContrasenia.move(40, 1)

        # ================== WIDGETS QPUSHBUTTON ===================

        buttonLogin = QPushButton("Iniciar sesión", self)
        buttonLogin.setFixedWidth(135)
        buttonLogin.setFixedHeight(28)
        buttonLogin.move(60, 286)

        buttonCancelar = QPushButton("Cancelar", self)
        buttonCancelar.setFixedWidth(135)
        buttonCancelar.setFixedHeight(28)
        buttonCancelar.move(205, 286)

        # ==================== MÁS INFORMACIÓN =====================

        labelInformacion = QLabel(
            "<a href='https://github.com/liluisjose1'>Más información</a>.",
            self)
        labelInformacion.setOpenExternalLinks(True)
        labelInformacion.setToolTip("Help")
        labelInformacion.move(15, 344)

        # ==================== SEÑALES BOTONES =====================

        buttonLogin.clicked.connect(self.Login)
        buttonCancelar.clicked.connect(self.close)
Exemplo n.º 4
0
    def __init__(self, show_automatic_box=False):
        super().__init__(show_automatic_box=show_automatic_box,
                         show_view_box=False)

        self.general_options_box.setVisible(False)

        button_box = oasysgui.widgetBox(self.controlArea,
                                        "",
                                        addSpace=False,
                                        orientation="horizontal")

        button = gui.button(button_box,
                            self,
                            "Calculate Radiation",
                            callback=self.calculateRadiation)
        font = QFont(button.font())
        font.setBold(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Blue'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)

        button = gui.button(button_box,
                            self,
                            "Reset Fields",
                            callback=self.callResetSettings)
        font = QFont(button.font())
        font.setItalic(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Red'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)
        button.setFixedWidth(150)

        gui.separator(self.controlArea)

        self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH)

        self.tabs_setting = oasysgui.tabWidget(self.controlArea)
        self.tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)
        self.tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5)

        # INTENSITY/POWER  -------------------------------------------

        tab_convolution = oasysgui.createTabPage(self.tabs_setting,
                                                 "Radiation")

        int_box = oasysgui.widgetBox(tab_convolution,
                                     "Wavefront Parameters",
                                     addSpace=True,
                                     orientation="vertical")

        oasysgui.lineEdit(int_box,
                          self,
                          "int_photon_energy_min",
                          "Photon Energy Min [eV]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_photon_energy_max",
                          "Photon Energy Max [eV]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_photon_energy_points",
                          "Photon Energy Points",
                          labelWidth=260,
                          valueType=int,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_h_slit_gap",
                          "H Slit Gap [m]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_v_slit_gap",
                          "V Slit Gap [m]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_h_slit_points",
                          "H Slit Points",
                          labelWidth=260,
                          valueType=int,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_v_slit_points",
                          "V Slit Points",
                          labelWidth=260,
                          valueType=int,
                          orientation="horizontal")
        oasysgui.lineEdit(int_box,
                          self,
                          "int_distance",
                          "Propagation Distance [m]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")

        pre_box = oasysgui.widgetBox(tab_convolution,
                                     "Precision Parameters",
                                     addSpace=False,
                                     orientation="vertical")

        tabs_precision = oasysgui.tabWidget(pre_box)

        tab_prop = oasysgui.createTabPage(tabs_precision, "Propagation")

        gui.comboBox(tab_prop,
                     self,
                     "int_sr_method",
                     label="Calculation Method",
                     items=["Manual", "Auto"],
                     labelWidth=260,
                     sendSelectedValue=False,
                     orientation="horizontal")

        oasysgui.lineEdit(tab_prop,
                          self,
                          "int_relative_precision",
                          "Relative Precision",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(tab_prop,
                          self,
                          "int_start_integration_longitudinal_position",
                          "Longitudinal pos. to start integration [m]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(tab_prop,
                          self,
                          "int_end_integration_longitudinal_position",
                          "Longitudinal pos. to finish integration [m]",
                          labelWidth=260,
                          valueType=float,
                          orientation="horizontal")
        oasysgui.lineEdit(tab_prop,
                          self,
                          "int_number_of_points_for_trajectory_calculation",
                          "Number of points for trajectory calculation",
                          labelWidth=260,
                          valueType=int,
                          orientation="horizontal")

        gui.comboBox(tab_prop,
                     self,
                     "int_use_terminating_terms",
                     label="Use \"terminating terms\"or not",
                     items=["No", "Yes"],
                     labelWidth=260,
                     sendSelectedValue=False,
                     orientation="horizontal")

        oasysgui.lineEdit(tab_prop,
                          self,
                          "int_sampling_factor_for_adjusting_nx_ny",
                          "Sampling factor for adjusting nx/ny",
                          labelWidth=260,
                          valueType=int,
                          orientation="horizontal")

        gui.rubber(self.controlArea)
Exemplo n.º 5
0
 def changeBack(self, pic):
     oImage = QImage(pic)
     sImage = oImage.scaled(self.width(), self.height())  # resize Image to widgets size
     palette = QPalette()
     palette.setBrush(QPalette.Window, QBrush(sImage))
     self.setPalette(palette)
Exemplo n.º 6
0
    def __init__(self, snapshot, common_settings, parent=None, **kw):
        super().__init__(parent, **kw)
        self.snapshot = snapshot
        self.common_settings = common_settings

        # ----------- PV Table -------------
        # PV table consist of:
        #     self.model: holding the data, values, being updated by PV callbacks, etc
        #     self._proxy: a proxy model implementing the filter functionality
        #     self.view: visual representation of the PV table

        self.view = SnapshotPvTableView(self)
        self.view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.view.restore_requested.connect(self._handle_restore_request)

        self.model = SnapshotPvTableModel(snapshot, self)
        self.model.file_parse_errors.connect(self._show_snapshot_parse_errors)
        self._proxy = SnapshotPvFilterProxyModel(self)
        self._proxy.setSourceModel(self.model)
        self._proxy.filtered.connect(self.pvs_filtered)

        # Build model and set default visualization on view (column widths, etc)
        self.model.set_pvs(snapshot.pvs.values())
        self.view.setModel(self._proxy)

        # ---------- Filter control elements ---------------
        # - text input to filter by name
        # - drop down to filter by compare status
        # - check box to select if showing pvs with incomplete data

        if SnapshotCompareWidget.rgx_icon is None:
            SnapshotCompareWidget.rgx_icon = QIcon(
                os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             "images/rgx.png"))

        # #### PV name filter
        pv_filter_label = QLabel("Filter:", self)
        pv_filter_label.setAlignment(Qt.AlignCenter | Qt.AlignRight)

        self.pv_filter_sel = QComboBox(self)
        self.pv_filter_sel.setEditable(True)
        self.pv_filter_sel.setIconSize(QtCore.QSize(35, 15))
        self.pv_filter_inp = self.pv_filter_sel.lineEdit()
        self.pv_filter_inp.setPlaceholderText("Filter by PV name")

        policy = self.pv_filter_sel.sizePolicy()
        policy.setHorizontalPolicy(policy.Expanding)
        self.pv_filter_sel.setSizePolicy(policy)

        self.pv_filter_sel.currentIndexChanged.connect(
            self._predefined_filter_selected)
        self.pv_filter_inp.textChanged.connect(self._create_name_filter)

        self._populate_filter_list()

        # Prepare pallets to color the pv name filter input if rgx not valid
        self._inp_palette_ok = self.pv_filter_inp.palette()
        self._inp_palette_err = QPalette()
        self._inp_palette_err.setColor(QPalette.Base, QColor("#F39292"))

        # Create a PV name filter layout and add items
        pv_filter_layout = QHBoxLayout()
        pv_filter_layout.setSpacing(10)
        pv_filter_layout.addWidget(pv_filter_label)
        pv_filter_layout.addWidget(self.pv_filter_sel)

        # #### Regex selector
        self.regex = QCheckBox("Regex", self)
        self.regex.stateChanged.connect(self._handle_regex_change)

        # #### Selector for comparison filter
        self.compare_filter_inp = QComboBox(self)
        self.compare_filter_inp.addItems(
            ["Show all", "Different only", "Equal only"])

        self.compare_filter_inp.currentIndexChanged.connect(
            self._proxy.set_eq_filter)
        self.compare_filter_inp.setMaximumWidth(200)

        # ### Show disconnected selector
        self.show_disconn_inp = QCheckBox("Show disconnected PVs.", self)
        self.show_disconn_inp.setChecked(True)
        self.show_disconn_inp.stateChanged.connect(
            self._proxy.set_disconn_filter)
        self.show_disconn_inp.setMaximumWidth(500)

        # Tolerance setting
        tol_label = QLabel("Tolerance:")
        tol = QSpinBox()
        tol.setRange(1, 1000000)
        tol.setValue(1)
        tol.valueChanged[int].connect(self.model.change_tolerance)
        self.model.change_tolerance(tol.value())

        # ### Put all tolerance and filter selectors in one layout
        filter_layout = QHBoxLayout()
        filter_layout.addWidget(tol_label)
        filter_layout.addWidget(tol)
        filter_layout.addWidget(make_separator(self, 'vertical'))

        filter_layout.addLayout(pv_filter_layout)
        filter_layout.addWidget(self.regex)

        filter_layout.addWidget(make_separator(self, 'vertical'))

        filter_layout.addWidget(self.compare_filter_inp)

        filter_layout.addWidget(self.show_disconn_inp)
        filter_layout.setAlignment(Qt.AlignLeft)
        filter_layout.setSpacing(10)

        # ------- Build main layout ---------
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.addLayout(filter_layout)
        layout.addWidget(self.view)
        self.setLayout(layout)
Exemplo n.º 7
0
 def init_ui(self):
     self.resize(self.window_width, self.window_height)
     self.test_button.setPixmap(
         QPixmap(":/resources/start_leave.png").scaled(
             QSize(self.window_width // 8, self.window_height // 8),
             Qt.KeepAspectRatio))
     self.test_button.setCursor(QCursor(Qt.PointingHandCursor))
     self.test_button.setMouseTracking(True)
     self.test_button.installEventFilter(self)
     palette = QPalette()
     palette.setBrush(
         self.backgroundRole(),
         QBrush(
             QPixmap(":/resources/bg.png").scaled(
                 QSize(self.window_width, self.window_height),
                 Qt.KeepAspectRatio)))
     self.setPalette(palette)
     help_btn = QPushButton(self)
     help_btn.setObjectName("help_btn")
     help_btn.setToolTip("点击此处查看使用帮助")
     help_btn.setStyleSheet("""#help_btn{
                 height:%s;
                 width:%s;
                 border: 0;
                 border-image: url(:/resources/help.png);
     }""" % (self.window_height // 12, self.window_height // 12))
     help_btn.setCursor(QCursor(Qt.PointingHandCursor))
     help_btn.clicked.connect(self.get_help)
     widget_title1 = QLabel(self)
     widget_title2 = QLabel(self)
     widget_title1.setText("文件列表")
     widget_title1.setFont(QFont("仿宋", 10))
     widget_title1.setObjectName("widget_title_files_list")
     widget_title2.setText("日志")
     widget_title2.setFont(QFont("仿宋", 10))
     widget_title2.setObjectName("widget_title_log")
     open_files_btn = QPushButton(self)
     open_files_btn.setText("选择文件夹")
     open_files_btn.setFont(QFont("楷体", 15))
     open_files_btn.setObjectName("select_files_btn")
     open_files_btn.setCursor(QCursor(Qt.PointingHandCursor))
     open_files_btn.clicked.connect(self.select_files)
     h_layout = QHBoxLayout()
     v_layout = QVBoxLayout()
     h_layout2 = QHBoxLayout()
     h_layout3 = QHBoxLayout()
     h_layout4 = QHBoxLayout()
     h_layout.addWidget(self.test_button)
     h_layout.addStretch(1)
     h_layout.addWidget(help_btn)
     h_layout2.addWidget(open_files_btn)
     h_layout2.addStretch(1)
     h_layout3.addWidget(widget_title1)
     h_layout3.addStretch(2)
     h_layout3.addWidget(widget_title2, stretch=8)
     h_layout4.addWidget(self.files_list)
     h_layout4.addWidget(self.log_box, stretch=1)
     v_layout.addLayout(h_layout)
     v_layout.addLayout(h_layout2)
     v_layout.addLayout(h_layout3)
     v_layout.addLayout(h_layout4)
     self.setLayout(v_layout)
Exemplo n.º 8
0
    def __init__(self, parent=None):
        self.Shooted = False
        super(Widget, self).__init__(parent=parent)
        self.plot_mask = False
        self.secondChannel = False

        # Image selection
        self.fold = QFileDialog.getOpenFileNames(
            self, "Select files containing images (tiff or png).",
            os.path.join(os.getcwd(), 'Data'), "*.png *.tiff *.tif")
        dir_file = self.fold[0][0][:self.fold[0][0].rfind(os.sep)]
        file_name = self.fold[0][0][self.fold[0][0].rfind(os.sep) + 1:]
        file_name = file_name[:-4]

        # Check size of the data and format
        if len(self.fold[0]) != 0:
            if self.fold[0][0].endswith('tiff') or self.fold[0][0].endswith(
                    'tif'):
                TIFF = True
            elif not (self.fold[0][0].endswith('png')):
                TIFF = False
                raise ValueError("Format not supported.")
            else:
                TIFF = False
        else:
            TIFF = False
            raise ValueError("Error - no file found.")

        # load images in shape (TIME,nx,ny)
        if TIFF:
            imgs = self.fold[0][0]
            print("Warning: only one tiff can be process.")
            tmp = np.array(imageio.mimread(imgs, memtest=False))

            if tmp.dtype != 'uint8':
                # from scipy.misc import bytescale
                tmp = bytescale(tmp)
            self.im = np.squeeze(np.array(tmp, dtype=np.uint8))
            self.im_nn = np.squeeze(np.array(tmp, dtype=type_im))
            self.start = 0
            self.finish = self.im.shape[0] - 1
            path_fold = self.fold[0][0]
        else:
            from skimage import color
            pictList = self.fold[0]
            path_fold = self.fold[0]
            tmp = np.array(imageio.imread(pictList[0]))
            if tmp.dtype != 'uint8':
                # from scipy.misc import bytescale
                tmp = bytescale(tmp)
            self.im = np.array(tmp, dtype=np.uint8)
            self.im = np.zeros(
                (len(pictList), self.im.shape[0], self.im.shape[1]))
            self.im_nn = np.zeros(
                (len(pictList), self.im.shape[1], self.im.shape[2]),
                dtype=type_im)
            for i in range(len(pictList)):
                tmp = color.rgb2gray(imageio.imread(pictList[i]))
                self.im_nn[i] = np.array(tmp, dtype=type_im)
                tmp = bytescale(tmp)
                self.im[i] = np.array(tmp, dtype=np.uint8)
            self.start = 0
            self.finish = len(pictList) - 1
        self.im_original = self.im.copy()
        self.nx = self.im[0].shape[0]
        self.ny = self.im[0].shape[1]
        self.data = self.im[0]
        self.maskLoaded = False

        # Set up environnement
        self.Shooted = False
        pal = QPalette()
        pal.setColor(QPalette.Background, Qt.black)
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self.horizontalLayout = QVBoxLayout(self)
        self.w1 = Slider(self.start, self.finish)
        self.horizontalLayout.addWidget(self.w1)
        self.win = pg.GraphicsWindow(title="Basic plotting examples")
        p1 = self.win.addPlot()
        self.horizontalLayout.addWidget(self.win)
        self.w2 = BottomBut()
        self.horizontalLayout.addWidget(self.w2)
        self.progress = QProgressBar(self)
        self.progress.setGeometry(0, 0, 300, 25)
        self.progress.setMaximum(self.finish)
        self.horizontalLayout.addWidget(self.progress)
        self.speed = 60
        self.volume = 0.5
        self.step = 20

        def quitProcedure():
            sys.exit()

        """
		Load second channel from tif or png images. 
		If shape is not eqaul to the original image, and error is raised and the second channel is not loaded.
		"""

        def newChannelProcedure():
            # Image selection
            fold_ = QFileDialog.getOpenFileNames(
                self, "Select files containing other channel (tiff or png).",
                os.path.join(os.getcwd(), 'Data'), "*.png *.tiff *.tif")
            # Check size of the data and format
            if len(fold_[0]) != 0:
                if fold_[0][0].endswith('tiff') or fold_[0][0].endswith('tif'):
                    TIFF = True
                elif not (fold_[0][0].endswith('png')):
                    TIFF = False
                    raise ValueError("Format not supported.")
                else:
                    TIFF = False
            else:
                TIFF = False
                raise ValueError("Error - no file found.")
            if TIFF:
                imgs = fold_[0][0]
                print("Warning: only one tiff can be process.")
                tmp = np.array(imageio.mimread(imgs, memtest=False))
                from scipy.misc import bytescale
                tmp = bytescale(tmp)
                im_channel = np.squeeze(np.array(tmp, dtype=np.uint8))
            else:
                from skimage import color
                pictList = fold_[0]
                # path_fold = fold_[0]
                tmp = np.array(imageio.imread(pictList[0]))
                from scipy.misc import bytescale
                tmp = bytescale(tmp)
                im_channel = np.array(tmp, dtype=np.uint8)
                im_channel = np.zeros(
                    (len(pictList), im_channel.shape[0], im_channel.shape[1]))
                for i in range(len(pictList)):
                    tmp = bytescale(tmp)
                    im_channel[i] = np.array(tmp, dtype=np.uint8)
            self.im_channel = im_channel.copy()
            if self.im_channel.shape == self.im.shape:
                self.secondChannel = True
            else:
                raise ValueError(
                    'Channel not with same shape as original images.')

        def shootingProcedure():
            if self.plot_mask and not (self.Shooted):
                print('Detection mode, Biolpase working...')
                if self.secondChannel:
                    phase_pred, im_crop_list, im_crop_list2, im_final = im2phase(
                        self.im_nn,
                        self.im_channel,
                        self.masks,
                        max_speed_disp=self.speed,
                        max_volume_var=self.volume,
                        minimalSize=100,
                        nx_crop=128,
                        ny_crop=128,
                        save_out=True,
                        step=self.step)
                else:
                    phase_pred, im_crop_list, _, im_final = im2phase(
                        self.im_nn,
                        np.zeros(1),
                        self.masks,
                        max_speed_disp=self.speed,
                        max_volume_var=self.volume,
                        minimalSize=100,
                        nx_crop=128,
                        ny_crop=128,
                        save_out=True,
                        step=self.step)
                self.im = im_final
                updateImage()
                tmp_fold = 'Data'  # dir_file
                for i in range(len(im_crop_list)):
                    for j in range(len(im_crop_list[i])):
                        tmp = im_crop_list[i][j]
                        tmpim = np.array(255 * (tmp - np.min(tmp)) /
                                         (np.max(tmp) - np.min(tmp)),
                                         dtype=np.uint8)
                        if self.secondChannel:
                            tmp = im_crop_list2[i][j]
                            tmpim2 = np.array(255 * (tmp - np.min(tmp)) /
                                              (np.max(tmp) - np.min(tmp)),
                                              dtype=np.uint8)
                        if phase_pred[i][j] == 0:
                            if not os.path.exists(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'G', file_name,
                                                 str(i).zfill(5))):
                                os.makedirs(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'G', file_name,
                                                 str(i).zfill(5)))
                            imageio.imsave(
                                os.path.join(
                                    tmp_fold, 'Biolapse', 'outputs', 'G',
                                    file_name,
                                    str(i).zfill(5),
                                    'image_' + str(j).zfill(5) + '.png'),
                                tmpim)
                            if self.secondChannel:
                                imageio.imsave(
                                    os.path.join(
                                        tmp_fold, 'Biolapse', 'outputs', 'G',
                                        file_name,
                                        str(i).zfill(5),
                                        'image2_' + str(j).zfill(5) + '.png'),
                                    tmpim2)
                        if phase_pred[i][j] == 1:
                            if not os.path.exists(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'earlyS',
                                                 file_name,
                                                 str(i).zfill(5))):
                                os.makedirs(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'earlyS',
                                                 file_name,
                                                 str(i).zfill(5)))
                            imageio.imsave(
                                os.path.join(
                                    tmp_fold, 'Biolapse', 'outputs', 'earlyS',
                                    file_name,
                                    str(i).zfill(5),
                                    'image_' + str(j).zfill(5) + '.png'),
                                tmpim)
                            if self.secondChannel:
                                imageio.imsave(
                                    os.path.join(
                                        tmp_fold, 'Biolapse', 'outputs',
                                        'earlyG', file_name,
                                        str(i).zfill(5),
                                        'image2_' + str(j).zfill(5) + '.png'),
                                    tmpim2)
                        if phase_pred[i][j] == 2:
                            if not os.path.exists(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'midS', file_name,
                                                 str(i).zfill(5))):
                                os.makedirs(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'midS', file_name,
                                                 str(i).zfill(5)))
                            imageio.imsave(
                                os.path.join(
                                    tmp_fold, 'Biolapse', 'outputs', 'midS',
                                    file_name,
                                    str(i).zfill(5),
                                    'image_' + str(j).zfill(5) + '.png'),
                                tmpim)
                            if self.secondChannel:
                                imageio.imsave(
                                    os.path.join(
                                        tmp_fold, 'Biolapse', 'outputs',
                                        'midS', file_name,
                                        str(i).zfill(5),
                                        'image2_' + str(j).zfill(5) + '.png'),
                                    tmpim2)
                        if phase_pred[i][j] == 3:
                            if not os.path.exists(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'lateS', file_name,
                                                 str(i).zfill(5))):
                                os.makedirs(
                                    os.path.join(tmp_fold, 'Biolapse',
                                                 'outputs', 'lateS', file_name,
                                                 str(i).zfill(5)))
                            imageio.imsave(
                                os.path.join(
                                    tmp_fold, 'Biolapse', 'outputs', 'lateS',
                                    file_name,
                                    str(i).zfill(5),
                                    'image_' + str(j).zfill(5) + '.png'),
                                tmpim)
                            if self.secondChannel:
                                imageio.imsave(
                                    os.path.join(
                                        tmp_fold, 'Biolapse', 'outputs',
                                        'lateS', file_name,
                                        str(i).zfill(5),
                                        'image2_' + str(j).zfill(5) + '.png'),
                                    tmpim2)

                print('Classification finished')
            elif not (self.plot_mask):
                print('Error: load or compute mask first.')
                return 0
            elif self.Shooted:
                print('Error: already in shooting procedure.')
                return 0

        def Speed():
            self.speed = self.getInt(
                'Maximum speed in one time step (in pixels)')

        def Volume():
            tmp = self.getInt('Maximum volume increase (in %)')
            self.volume = float(tmp) / 100.

        def Step():
            self.step = self.getInt('Time between two detection of cells.')

        """
		Load masks from tiff or png file. User should select a tiff image containing a time sequence of mask, or several png files refered as masks.
		"""

        def loadMasks():
            loadsuccesfull = False
            self.masks_path = QFileDialog.getOpenFileNames(
                self, "Select file(s) where masks are.",
                os.path.join(os.getcwd(), 'Data'), "*.png *.tiff *.tif")
            if len(self.masks_path[0]) != 0:
                if self.masks_path[0][0].endswith(
                        'tiff') or self.masks_path[0][0].endswith('tif'):
                    TIFF_masks = True
                elif not (self.masks_path[0][0].endswith('png')):
                    TIFF_masks = False
                else:
                    TIFF_masks = False
                loadsuccesfull = True
            else:
                TIFF_masks = False
                print("Error - no file found.")
                return False
            # load images
            if TIFF_masks:
                masks_path = self.masks_path[0][0]
                print("Warning: only one tiff can be process.")
                mask = np.squeeze(
                    np.array(imageio.mimread(masks_path, memtest=False),
                             dtype=np.uint8))
            else:
                pictList = self.masks_path[0]
                tmp = imageio.imread(pictList[0])
                mask = np.array(bytescale(tmp), dtype=np.uint8)
                mask = np.zeros((len(pictList), mask.shape[0], mask.shape[1]))
                for i in range(len(pictList)):
                    tmp = imageio.imread(pictList[i])
                    mask[i] = np.array(bytescale(tmp), dtype=np.uint8)
            self.masks_original = mask.copy()
            self.masks = np.array(self.masks_original > 0, dtype=np.uint8)
            if mask.shape[0] != self.finish + 1:
                print('Not same number of masks than images.')
                loadsuccesfull = False
            if loadsuccesfull:
                if self.plot_mask != True:
                    self.plot_mask = True
                    self.p2 = self.win.addPlot(colspan=2)
                    self.img_m = pg.ImageItem(None, border="w")
                    self.p2.addItem(self.img_m)
                    self.maskLoaded = True
                    self.win.show()
                    self.w1_m = Slider_thresh(0, 1)
                    self.horizontalLayout.addWidget(self.w1_m)
                    p1.setAspectLocked(ratioKept)
                    p1.autoRange()
                    self.img_m.setImage(np.rot90(self.masks[self.w1.x], 3))
                    self.p2.setAspectLocked(ratioKept)
                    self.p2.autoRange()
                    self.p2.setAspectLocked()
                    self.p2.autoRange()
                    self.w1_m.valueChangedX.connect(updateThresh)
                    updateThresh()
                else:
                    self.img_m.setImage(np.rot90(self.masks[self.w1.x], 3))
                    self.p2.setAspectLocked(ratioKept)
                    self.p2.autoRange()
                    self.p2.setAspectLocked()
                    self.p2.autoRange()

        """
		Compute masks based on neural network model.
		User should select 'h5' or 'hdf5' file. 
		Custom loss is implemented (binary cross entropy + dice coefficient). If any other custom loss 
		should be use, modify in the following function.
		Images are put in [0,1] and then convert to the format needed by the neural network (usually uint16). 
		Masks are saved into 'Outputs' into the folder containing image 
		"""

        def computeMasks():
            from keras.models import load_model
            from tensorflow.python.client import device_lib
            from skimage.transform import resize
            from keras import backend as K
            from keras.losses import binary_crossentropy
            import tensorflow as tf
            import keras

            MODE = "GPU" if "GPU" in [
                k.device_type for k in device_lib.list_local_devices()
            ] else "CPU"
            print(MODE)
            print('########### Computing masks - please wait... ###########')

            # def dice_coef_K(y_true, y_pred, smooth=1):
            # 	y_true_f = K.flatten(y_true)
            # 	y_pred_f = K.flatten(y_pred)
            # 	intersection = K.sum(y_true_f * y_pred_f)
            # 	return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
            # def dice_coef_loss_K(y_true, y_pred):
            # 	return 1-dice_coef_K(y_true, y_pred)
            self.model = QFileDialog.getOpenFileName(
                self, "Select h5 file defining the AI model.",
                os.path.join(os.getcwd(), 'Data', 'Segmentation', 'Model'),
                "*.h5 *.hdf5")

            # Custom IoU metric
            def mean_iou(y_true, y_pred):
                prec = []
                for t in np.arange(0.5, 1.0, 0.05):
                    y_pred_ = tf.to_int32(y_pred > t)
                    score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
                    K.get_session().run(tf.local_variables_initializer())
                    with tf.control_dependencies([up_opt]):
                        score = tf.identity(score)
                    prec.append(score)
                return K.mean(K.stack(prec), axis=0)

            # Custom loss function
            def dice_coef(y_true, y_pred):
                smooth = 1.
                y_true_f = K.flatten(y_true)
                y_pred_f = K.flatten(y_pred)
                intersection = K.sum(y_true_f * y_pred_f)
                return (2. * intersection +
                        smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)

            def bce_dice_loss(y_true, y_pred):
                return 0.5 * keras.losses.binary_crossentropy(
                    y_true, y_pred) - dice_coef(y_true, y_pred)

            # Load model and parameters
            # l1 = 1.
            # l2 = -1.
            # loss1 = binary_crossentropy
            # loss2 = dice_coef_loss_K
            # def custom_loss(y_true,y_pred):
            # 	return l1*loss1(y_true,y_pred)+l2*loss2(y_true,y_pred)
            # # net = load_model(self.model[0],custom_objects={'custom_loss':custom_loss}) #v0
            net = load_model(self.model[0],
                             custom_objects={
                                 'bce_dice_loss': bce_dice_loss,
                                 'mean_iou': mean_iou
                             })  #v1
            nx = int(net.input.get_shape()[1])
            ny = int(net.input.get_shape()[2])
            TIME = int(net.input.get_shape()[3])
            if LSTM:
                nx = int(net.input.get_shape()[2])
                ny = int(net.input.get_shape()[3])
                TIME = int(net.input.get_shape()[1])
            else:
                nx = int(net.input.get_shape()[1])
                ny = int(net.input.get_shape()[2])
                TIME = int(net.input.get_shape()[3])
            if TIME > self.im.shape[0]:
                raise ValueError(
                    'Require at least {0} images, {1} given. This is important since the segmentation used teporal information.'
                    .format(TIME, self.im.shape[0]))

            # Make data in time batch
            nb_serie = int(self.finish + 1) // TIME
            im_batch = np.zeros((nb_serie, nx, ny, TIME), dtype=np.float32)
            masks = np.zeros((nx, ny, self.finish + 1), dtype=np.float32)
            for i in range(nb_serie):
                tmp = np.array(self.im_nn[i * TIME:(i + 1) * TIME].copy(),
                               dtype=np.float32)
                for t in range(TIME):
                    im_batch[i, :, :, t] = resize(tmp[t], (nx, ny),
                                                  mode='constant',
                                                  preserve_range=True)
                # im_batch[i] = np.array(np.iinfo(type_im).max*(np.array(im_batch[i],dtype=np.float64)-np.min(im_batch[i]))/(np.max(im_batch[i])-np.min(im_batch[i])),dtype=type_im)
            # if nb_serie >0:
            # 	im_batch = np.iinfo(type_im).max*(im_batch- np.min(im_batch))/(np.max(im_batch)-np.min(im_batch))
            im_batch = np.expand_dims(np.array(im_batch, dtype=np.float32), 4)
            if LSTM:
                im_batch = np.rollaxis(im_batch, 3, 1)

            # Compute mask for the first time batchs
            masks = np.zeros(
                (self.finish + 1, self.im.shape[1], self.im.shape[2]))
            for i in range(nb_serie):
                print("Neural network progress : {0}%.".format(
                    int(100 * i / nb_serie)))
                tmp = np.array(np.expand_dims(im_batch[i], 0),
                               dtype=np.float32) / np.iinfo(type_im).max
                masks_ = np.array(np.squeeze(net.predict(tmp)),
                                  dtype=np.float32)
                # masks_ = np.squeeze(tmp)
                if LSTM:
                    # TODO: check this part
                    for t in range(TIME):
                        masks[i * TIME + t] = resize(
                            masks_[t], (self.im.shape[1], self.im.shape[2]),
                            mode='constant',
                            preserve_range=True)
                else:
                    for t in range(TIME):
                        # masks[i*TIME+t] = np.squeeze(self.im[TIME*i+t])
                        masks[i * TIME +
                              t] = resize(masks_[:, :, t],
                                          (self.im.shape[1], self.im.shape[2]),
                                          mode='constant',
                                          preserve_range=True)

            # Compute mask for the remaining images
            if self.finish != TIME * nb_serie:
                tmp = np.array(self.im_nn[self.finish + 1 - TIME:].copy(),
                               dtype=np.float32)
                im_tmp = np.zeros((1, nx, ny, TIME, 1))
                for t in range(TIME):
                    im_tmp[0, :, :, t, 0] = resize(tmp[t], (nx, ny),
                                                   mode='constant',
                                                   preserve_range=True)
                # im_tmp[0] = np.array(np.iinfo(type_im).max*(np.array(im_tmp[0],dtype=np.float64)-np.min(im_tmp[0]))/(np.max(im_tmp[0])-np.min(im_tmp[0])),dtype=type_im)
                im_tmp = np.array(im_tmp,
                                  dtype=np.float32) / np.iinfo(type_im).max
                tmp = np.array(np.squeeze(net.predict(im_tmp)),
                               dtype=np.float32)
                for t in range((self.finish + 1 - nb_serie * TIME)):
                    masks[nb_serie * TIME + t] = resize(
                        tmp[:, :,
                            TIME - (self.finish - nb_serie * TIME) - 1 + t],
                        (self.im.shape[1], self.im.shape[2]),
                        mode='constant',
                        preserve_range=True)

            # Save masks in same folder than images
            if not os.path.exists(
                    os.path.join(dir_file, 'Outputs', file_name, 'masks')):
                os.makedirs(
                    os.path.join(dir_file, 'Outputs', file_name, 'masks'))
            for i in range(self.finish + 1):
                tmp = np.array(np.iinfo(type_save).max * (masks[i] > 1e-7),
                               dtype=type_save)
                imageio.imsave(
                    os.path.join(dir_file, 'Outputs', file_name, 'masks',
                                 str(i).zfill(10) + '.png'), tmp)
            print('Masks computed.')
            self.masks_original = masks.copy()
            self.masks = (self.masks_original > 0).astype(np.uint8)

            if self.plot_mask != True:
                self.plot_mask = True
                self.p2 = self.win.addPlot(colspan=2)
                self.img_m = pg.ImageItem(None, border="w")
                self.p2.addItem(self.img_m)
                self.maskLoaded = True
                self.win.show()
                self.w1_m = Slider_thresh(0, 1)
                self.horizontalLayout.addWidget(self.w1_m)
                p1.setAspectLocked(ratioKept)
                p1.autoRange()
                self.p2.setAspectLocked(ratioKept)
                self.p2.autoRange()
                self.img_m.setImage(np.rot90(self.masks[self.w1.x], 3))
                self.p2.setAspectLocked()
                self.p2.autoRange()
                self.w1_m.valueChangedX.connect(updateThresh)
                updateThresh()
            else:
                self.p2.setAspectLocked(ratioKept)
                self.p2.autoRange()
                self.img_m.setImage(np.rot90(self.masks[self.w1.x], 3))
                self.p2.setAspectLocked()
                self.p2.autoRange()
                self.w1_m.valueChangedX.connect(updateThresh)

        def updateThresh():
            self.masks = np.array(self.masks_original > self.w1_m.x,
                                  dtype=np.uint8)
            updateImage()

        # Get action of user
        self.w2.isShooted.connect(shootingProcedure)
        self.w2.iscomputeSpeed.connect(Speed)
        self.w2.iscomputeVolume.connect(Volume)
        self.w2.iscomputeStep.connect(Step)
        self.w2.isloadMasks.connect(loadMasks)
        self.w2.iscomputeMasks.connect(computeMasks)
        self.img = pg.ImageItem(None, border="w")
        # self.img.setRect(QRect(100, 200, 11, 16))
        p1.addItem(self.img)

        # Custom ROI for selecting an image region (axis swaped)
        self.roi = pg.ROI([20, 20], [int(self.ny / 10), int(self.nx / 10)])
        self.roi.addScaleHandle([0.5, 1], [0.5, 0.001])
        self.roi.addScaleHandle([0, 0.5], [0.999, 0.5])
        self.roi.addScaleHandle([0.5, 0], [0.5, 0.999])
        self.roi.addScaleHandle([1, 0.5], [0.001, 0.5])

        # update when user change view
        def updateImage():
            self.data = self.im[self.w1.x]
            self.img.setImage(np.rot90(self.data, 3))
            if self.maskLoaded:
                self.img_m.setImage(np.rot90(self.masks[self.w1.x], 3))

        self.w1.valueChangedX.connect(updateImage)
        p1.addItem(self.roi)
        self.roi.setZValue(10)  # make sure ROI is drawn above image

        # Contrast/color control
        hist = pg.HistogramLUTItem(fillHistogram=False)
        hist.setImageItem(self.img)
        self.win.addItem(hist)
        self.img.setImage(np.rot90(self.data, 3))
        hist.setLevels(self.data.min(), self.data.max())
        p1.setAspectLocked()
        p1.autoRange()

        self.boundingBox = [None, None]

        # Callbacks for handling user interaction
        def updatePlot():
            global img, roi, data
            selected = self.roi.getArrayRegion(self.data, self.img)
            self.boundingBox = [[int(self.roi.pos().x()),int(self.roi.pos().y())],\
            [int(self.roi.pos().x()+self.roi.size().x()),int(self.roi.pos().y()+self.roi.size().y())]]

        self.roi.sigRegionChanged.connect(updatePlot)
        updatePlot()

        def trackingProcedure():
            self.start_tracking = self.w1.x

        def endTrackingProcedure():
            if self.Shooted:
                self.end_tracking = self.w1.x
                if not os.path.exists(
                        os.path.join(dir_file, 'Outputs', file_name, 'track',
                                     str(self.shootID))):
                    os.makedirs(
                        os.path.join(dir_file, 'Outputs', file_name, 'track',
                                     str(self.shootID)))
                for k in range(self.start_tracking, self.end_tracking):
                    tmp = np.array(self.im_focus[k] * self.mask_crop[k],
                                   dtype=np.float32)
                    tmp = np.array(np.iinfo(type_save).max *
                                   (tmp - tmp.min()) / (tmp.max() - tmp.min()),
                                   dtype=type_save)
                    imageio.imsave(
                        os.path.join(dir_file, 'Outputs', file_name, 'track',
                                     str(self.shootID),
                                     'image_' + str(k).zfill(10) + '.png'),
                        tmp)
                    if self.secondChannel:
                        tmp = np.array(self.im_channel_focus[k],
                                       dtype=np.float32)
                        tmp = np.array(np.iinfo(type_save).max *
                                       (tmp - tmp.min()) /
                                       (tmp.max() - tmp.min()),
                                       dtype=type_save)
                        imageio.imsave(
                            os.path.join(dir_file,
                                         'Outputs', file_name, 'track',
                                         str(self.shootID), 'image2_' +
                                         str(k).zfill(10) + '.png'), tmp)
            else:
                print('Not in shooting mode.')

        self.w3 = InterfaceManagerButton()
        self.horizontalLayout.addWidget(self.w3)
        self.w3.isQuit.connect(quitProcedure)
        self.w3.isChannel.connect(newChannelProcedure)
        self.w3.isTrack.connect(trackingProcedure)
        self.w3.isTrackEnd.connect(endTrackingProcedure)
    def __init__(self):
        super().__init__()

        #/ Make GUI ----------------------------------------------------------------------------------------------------
        self.runaction = OWAction("Import Simulated Array", self)
        self.runaction.triggered.connect(self.selectFile)
        self.addAction(self.runaction)

        self.runaction = OWAction("Generate Height Profile File", self)
        self.runaction.triggered.connect(self.interp_save)
        self.addAction(self.runaction)

        geom = QApplication.desktop().availableGeometry()
        self.setGeometry(
            QRect(round(geom.width() * 0.05), round(geom.height() * 0.05),
                  round(min(geom.width() * 0.98, self.MAX_WIDTH)),
                  round(min(geom.height() * 0.95, self.MAX_HEIGHT))))

        self.setMaximumHeight(self.geometry().height())
        self.setMaximumWidth(self.geometry().width())

        gui.separator(self.controlArea)

        button_box = oasysgui.widgetBox(self.controlArea,
                                        "",
                                        addSpace=False,
                                        orientation="horizontal")

        button = gui.button(button_box,
                            self,
                            "Import Simulated\nArray",
                            callback=self.selectFile)
        button.setFixedHeight(45)

        button = gui.button(button_box,
                            self,
                            "Generate Height\nProfile File",
                            callback=self.interp_save)
        font = QFont(button.font())
        font.setBold(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        button.setFixedHeight(45)
        button.setFixedWidth(150)

        button = gui.button(button_box,
                            self,
                            "Reset Fields",
                            callback=self.call_reset_settings)
        button.setFixedHeight(45)

        #/ Control area ------------------------------------------------------------------------------------------------

        gui.separator(self.controlArea)

        tabs_setting = oasysgui.tabWidget(self.controlArea)
        tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)
        tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5)

        tab_input = oasysgui.createTabPage(tabs_setting, "Input Parameters")
        tab_out = oasysgui.createTabPage(tabs_setting, "Output")
        tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget")
        tab_usa.setStyleSheet("background-color: white;")

        usage_box = oasysgui.widgetBox(tab_usa,
                                       "",
                                       addSpace=True,
                                       orientation="horizontal")

        label = QLabel("")
        label.setAlignment(Qt.AlignCenter)
        label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        label.setPixmap(QPixmap(self.get_usage_path()))

        usage_box.layout().addWidget(label)

        #/ ---------------------------------------

        select_file_box_1 = oasysgui.widgetBox(tab_input,
                                               "",
                                               addSpace=True,
                                               orientation="horizontal")
        self.wi_simFE_fname = oasysgui.lineEdit(select_file_box_1,
                                                self,
                                                "simFE_fname",
                                                "Input Array Path",
                                                labelWidth=120,
                                                valueType=str,
                                                orientation="horizontal")

        input_box = oasysgui.widgetBox(tab_input,
                                       "Transformation settings",
                                       addSpace=True,
                                       orientation="vertical")

        gui.comboBox(input_box,
                     self,
                     "unit",
                     label="Unit",
                     labelWidth=260,
                     items=["m", "cm"],
                     callback=None,
                     sendSelectedValue=False,
                     orientation="horizontal")

        gui.separator(input_box)
        gui.separator(input_box)

        gui.comboBox(input_box,
                     self,
                     "method",
                     label="Select method",
                     labelWidth=260,
                     items=["Spacing", "Number of points"],
                     callback=self.set_Method,
                     sendSelectedValue=False,
                     orientation="horizontal")

        self.method_box_1 = oasysgui.widgetBox(input_box,
                                               "",
                                               addSpace=True,
                                               orientation="vertical",
                                               height=70)

        self.method_box_1_1 = oasysgui.widgetBox(self.method_box_1,
                                                 "",
                                                 addSpace=True,
                                                 orientation="vertical")
        self.wi_spacing_value = oasysgui.lineEdit(self.method_box_1_1,
                                                  self,
                                                  "spacing_value",
                                                  "Spacing size",
                                                  labelWidth=260,
                                                  valueType=float,
                                                  orientation="horizontal")

        self.method_box_1_2 = oasysgui.widgetBox(self.method_box_1,
                                                 "",
                                                 addSpace=True,
                                                 orientation="vertical")
        self.wi_noPts_x = oasysgui.lineEdit(self.method_box_1_2,
                                            self,
                                            "noPts_x",
                                            "X",
                                            labelWidth=260,
                                            valueType=int,
                                            orientation="horizontal")
        self.wi_noPts_y = oasysgui.lineEdit(self.method_box_1_2,
                                            self,
                                            "noPts_y",
                                            "Y",
                                            labelWidth=260,
                                            valueType=int,
                                            orientation="horizontal")

        self.set_Method()

        output_box = oasysgui.widgetBox(tab_input,
                                        "Output settings",
                                        addSpace=True,
                                        orientation="vertical")
        select_file_box_2 = oasysgui.widgetBox(output_box,
                                               "",
                                               addSpace=True,
                                               orientation="horizontal")
        self.wi_save_height_profile_file_name = oasysgui.lineEdit(
            select_file_box_2,
            self,
            "save_height_profile_file_name",
            "Output Array Path",
            labelWidth=120,
            valueType=str,
            orientation="horizontal")
        gui.button(select_file_box_2,
                   self,
                   "Browse",
                   callback=self.selectFile_save)

        gui.rubber(self.controlArea)

        self.shadow_output = oasysgui.textArea()

        out_box = oasysgui.widgetBox(tab_out,
                                     "System Output",
                                     addSpace=True,
                                     orientation="horizontal",
                                     height=580)
        out_box.layout().addWidget(self.shadow_output)

        gui.rubber(self.controlArea)

        self.figure, (self.axis, self.cax) = subplots(
            1, 2, gridspec_kw={'width_ratios': [95, 5]}, figsize=(600, 600))
        self.cax.grid()

        self.figure_canvas = FigureCanvasQTAgg(self.figure)
        self.mainArea.layout().addWidget(self.figure_canvas)

        gui.rubber(self.mainArea)
Exemplo n.º 10
0
    def initUI(self):
        # set LeftPanel size
        self.setFixedSize(self.width, self.hight)

        # set LeftPanel background color
        self.setAutoFillBackground(True)
        palette = QPalette()
        palette.setColor(self.backgroundRole(), QColor(40, 42, 45))
        self.setPalette(palette)

        # set pic
        self.setpic(self.unknownUser)
        # set pic size
        self.pic.setFixedSize(self.width - 20, self.width - 20)
        # add pic to LeftPanel
        self.pic.move(10, 10)

        # set stackWidget size
        self.controlPanel.setFixedSize(self.width, self.hight - 250)
        # add visitor page to controlPanel
        v = QWidget()
        vly = QFormLayout()
        vly.addRow(self.homeB0)
        vly.addRow(self.searchB0)
        v.setLayout(vly)
        self.controlPanel.addWidget(v)
        # add dev has no transaction to controlpanel
        dnt = QWidget()
        dntly = QFormLayout()
        dntly.addRow(self.homeB1)
        dntly.addRow(self.searchB1)
        dntly.addRow(self.ProjectB1)
        dntly.addRow(self.messageB1)
        dntly.addRow(self.historyB1)
        dntly.addRow(self.manageTeam1)
        dnt.setLayout(dntly)
        self.controlPanel.addWidget(dnt)
        # add dev has transaction to controlPanel
        dt = QWidget()
        dtly = QFormLayout()
        dtly.addRow(self.homeB2)
        dtly.addRow(self.searchB2)
        dtly.addRow(self.ProjectB2)
        dtly.addRow(self.messageB2)
        dtly.addRow(self.historyB2)
        dtly.addRow(self.manageTeam2)
        dt.setLayout(dtly)
        self.controlPanel.addWidget(dt)
        # add client has no transaction
        cnt = QWidget()
        cntly = QFormLayout()
        cntly.addRow(self.homeB3)
        cntly.addRow(self.searchB3)
        cntly.addRow(self.ProjectB3)
        cntly.addRow(self.messageB3)
        cntly.addRow(self.historyB3)
        cnt.setLayout(cntly)
        self.controlPanel.addWidget(cnt)
        # add client has transaction
        ct = QWidget()
        ctly = QFormLayout()
        ctly.addRow(self.homeB4)
        ctly.addRow(self.searchB4)
        ctly.addRow(self.ProjectB4)
        ctly.addRow(self.messageB4)
        ctly.addRow(self.historyB4)
        ct.setLayout(ctly)
        self.controlPanel.addWidget(ct)
        # add super user
        su = QWidget()
        suly = QFormLayout()
        suly.addRow(self.manage)
        suly.addRow(self.messageB5)
        su.setLayout(suly)
        self.controlPanel.addWidget(su)
        # add new user
        new = QWidget()
        newly = QFormLayout()
        newly.addRow(self.homeB5)
        newly.addRow(self.searchB5)
        new.setLayout(newly)
        self.controlPanel.addWidget(new)
        # add controlPanel to LeftPanel
        self.controlPanel.setCurrentIndex(0)
        self.controlPanel.move(0, 180)

        # set funcbutt menu
        self.setFuncMenu(False)
        self.funcbutt.setPopupMode(QToolButton.InstantPopup)
        self.funcbutt.setMenu(self.mu)
        # set image for funcbutt
        self.funcbutt.setIcon(QIcon(self.menuIcon))
        self.funcbutt.setIconSize(QSize(60, 30))
        # add funcbutt to LeftPanel
        self.funcbutt.setFixedSize(61, 31)
        self.funcbutt.move(39, self.hight - 43)
Exemplo n.º 11
0
    def __init__(self, theParent):

        self.mainConf   = nw.CONFIG
        self.theParent  = theParent
        self.theIcons   = GuiIcons(self.theParent)
        self.guiPalette = QPalette()
        self.guiPath    = "gui"
        self.fontPath   = "fonts"
        self.syntaxPath = "syntax"
        self.cssName    = "style.qss"
        self.confName   = "theme.conf"
        self.themeList  = []
        self.syntaxList = []

        # Loaded Theme Settings

        ## Theme
        self.themeName        = ""
        self.themeDescription = ""
        self.themeAuthor      = ""
        self.themeCredit      = ""
        self.themeUrl         = ""
        self.themeLicense     = ""
        self.themeLicenseUrl  = ""

        ## GUI
        self.treeWCount  = [0,   0,   0]
        self.statNone    = [120, 120, 120]
        self.statUnsaved = [120, 120, 40]
        self.statSaved   = [40,  120, 0]
        self.helpText    = [0,   0,   0]

        # Loaded Syntax Settings

        ## Main
        self.syntaxName        = ""
        self.syntaxDescription = ""
        self.syntaxAuthor      = ""
        self.syntaxCredit      = ""
        self.syntaxUrl         = ""
        self.syntaxLicense     = ""
        self.syntaxLicenseUrl  = ""

        ## Colours
        self.colBack   = [255, 255, 255]
        self.colText   = [0, 0, 0]
        self.colLink   = [0, 0, 0]
        self.colHead   = [0, 0, 0]
        self.colHeadH  = [0, 0, 0]
        self.colEmph   = [0, 0, 0]
        self.colDialN  = [0, 0, 0]
        self.colDialD  = [0, 0, 0]
        self.colDialS  = [0, 0, 0]
        self.colHidden = [0, 0, 0]
        self.colKey    = [0, 0, 0]
        self.colVal    = [0, 0, 0]
        self.colSpell  = [0, 0, 0]
        self.colTagErr = [0, 0, 0]
        self.colRepTag = [0, 0, 0]
        self.colMod    = [0, 0, 0]

        # Changeable Settings
        self.guiTheme   = None
        self.guiSyntax  = None
        self.themeRoot  = None
        self.themePath  = None
        self.syntaxFile = None
        self.confFile   = None
        self.cssFile    = None
        self.guiFontDB  = QFontDatabase()

        self.loadFonts()
        self.updateFont()
        self.updateTheme()
        self.theIcons.updateTheme()

        self.getIcon = self.theIcons.getIcon
        self.getPixmap = self.theIcons.getPixmap
        self.loadDecoration = self.theIcons.loadDecoration

        # Extract Other Info
        self.guiDPI = qApp.primaryScreen().logicalDotsPerInchX()
        self.guiScale = qApp.primaryScreen().logicalDotsPerInchX()/96.0
        self.mainConf.guiScale = self.guiScale
        logger.verbose("GUI DPI: %.1f" % self.guiDPI)
        logger.verbose("GUI Scale: %.2f" % self.guiScale)

        # Fonts
        self.guiFont = qApp.font()

        qMetric = QFontMetrics(self.guiFont)
        self.fontPointSize = self.guiFont.pointSizeF()
        self.fontPixelSize = int(round(qMetric.height()))
        self.baseIconSize = int(round(qMetric.ascent()))
        self.textNHeight = qMetric.boundingRect("N").height()
        self.textNWidth = qMetric.boundingRect("N").width()

        # Monospace Font
        self.guiFontFixed = QFont()
        self.guiFontFixed.setPointSizeF(0.95*self.fontPointSize)
        self.guiFontFixed.setFamily(QFontDatabase.systemFont(QFontDatabase.FixedFont).family())

        logger.verbose("GUI Font Family: %s" % self.guiFont.family())
        logger.verbose("GUI Font Point Size: %.2f" % self.fontPointSize)
        logger.verbose("GUI Font Pixel Size: %d" % self.fontPixelSize)
        logger.verbose("GUI Base Icon Size: %d" % self.baseIconSize)
        logger.verbose("Text 'N' Height: %d" % self.textNHeight)
        logger.verbose("Text 'N' Width: %d" % self.textNWidth)

        return
Exemplo n.º 12
0
    def initUI(self):
        # プレイヤー下部のステータス部分
        self.hbox = QHBoxLayout()
        # 再生ボタン追加
        self.playButton = QPushButton("PLAY")
        self.playButton.setFixedWidth(100)
        self.playButton.clicked.connect(self.__parent.playButton_clicked)
        self.hbox.addWidget(self.playButton)
        # 再生位置表示
        self.timerLabel = QLabel(self)
        self.timerLabel.setAutoFillBackground(True)
        qp = QPalette()
        qp.setColor(QPalette.Background, QColor("#000000"))
        qp.setColor(QPalette.Foreground, QColor("#FFFFFF"))
        self.timerLabel.setPalette(qp)
        self.timerLabel.setFixedWidth(45)
        self.timerLabel.setAlignment(QtCore.Qt.AlignRight
                                     | QtCore.Qt.AlignVCenter)
        self.update_timerLabel(0)
        self.hbox.addWidget(self.timerLabel)
        # 再生時間表示
        self.playTimeLabel = QLabel(self)
        self.playTimeLabel.setAutoFillBackground(True)
        self.playTimeLabel.setPalette(qp)
        self.playTimeLabel.setFixedWidth(65)
        self.hbox.addWidget(self.playTimeLabel)
        # シークバー
        self.seekbar = QSlider(Qt.Horizontal)
        self.seekbar.setRange(0, 100)
        self.seekbar.setValue(0)
        self.seekbar.setStyleSheet('QSlider::groove:horizontal {'
                                   'border: 1px solid #999999;'
                                   'height: 18px;'
                                   '}'
                                   'QSlider::handle:horizontal {'
                                   'background: silver;'
                                   'border: 1px solid #333333;'
                                   'border-radius: 8px;'
                                   'width: 16px;'
                                   '}'
                                   'QSlider::add-page:horizontal {'
                                   'background: white;'
                                   '}'
                                   'QSlider::sub-page:horizontal {'
                                   'background: blue;'
                                   '}')
        self.seekbar.sliderReleased.connect(self.seekbar_released)
        self.seekbar.sliderPressed.connect(self.seekbar_pressed)
        self.seekbar.sliderMoved.connect(self.seekbar_moved)
        self.seekbar.setEnabled(False)
        self.hbox.addWidget(self.seekbar)

        # 再生画面とステータス部分
        self.vbox = QVBoxLayout()
        self.vbox.addStretch(1)
        self.vbox.addLayout(self.hbox)
        self.setLayout(self.vbox)

        # 背景を透明にする
        self.setAutoFillBackground(True)
        palette = QPalette()
        brush = QBrush(QColor(0, 0, 0, 0))
        palette.setBrush(QPalette.Background, brush)
        self.setPalette(palette)
Exemplo n.º 13
0
    def initUI(self,  sce_name=''):
        # 用例信息存放list
        self.feature_steps_info = []
        self.feature_info = {}

        self.setGeometry(10, 10, 900, 600)
        self.setWindowTitle('编辑用例')
        self.setWindowIcon(QIcon('./images/icon.jpg'))
        self.setWindowFlags(Qt.Qt.SubWindow)
        # self.setMaximumSize()

        grid = QGridLayout()

        featureLabel = QLabel('用例名称:')
        self.featureName = QLineEdit()
        self.featureName.setMinimumHeight(50)
        self.featureName.setPlaceholderText('用例名称保持唯一性')

        if not sce_name == '':
            self.featureName.setText(sce_name)
            self.featureName.setDisabled(True)

        self.featureName.textChanged[str].connect(self.chk_sce_name)

        self.flagLabel = QLabel(self)
        self.flagLabel.setFont(QFont("Roman times", 16, QFont.Bold))

        self.pe_red = QPalette()
        self.pe_red.setColor(QPalette.WindowText, Qt.Qt.red)
        self.pe_green = QPalette()
        self.pe_green.setColor(QPalette.WindowText, Qt.Qt.green)


        appLabel = QLabel('所属模块:', self)

        self.appCombo = QComboBox()
        self.appCombo.addItem('--请选择--')
        self.appCombo.addItem('电台')
        self.appCombo.addItem('音乐')
        self.appCombo.addItem('语音')
        self.appCombo.addItem('视频')

        self.appCombo.activated[str].connect(self.add_module_to_feature)

        tagLabel = QLabel('用例类型:', self)

        self.tagCombo = QComboBox()
        self.tagCombo.addItem('--请选择--')
        self.tagCombo.addItem('基本场景')
        self.tagCombo.addItem('复杂场景')
        self.tagCombo.addItem('蓝牙场景')
        self.tagCombo.addItem('语音场景')

        self.tagCombo.activated[str].connect(self.add_tags_to_feature)

        self.tipLabel = QLabel(self)
        self.tipLabel.setFont(QFont("Roman times", 12))

        self.stepCombo = QComboBox()
        self.stepCombo.addItem('所有')
        self.stepCombo.addItem('操作')
        self.stepCombo.addItem('验证')
        self.stepCombo.setCurrentIndex(0)
        self.stepCombo.currentTextChanged.connect(self.show_steps)

        self.search_step = QLineEdit()
        self.search_step.setPlaceholderText('请输入关键字')
        self.search_step.textChanged.connect(self.show_steps)
        self.step_list = QListWidget()

        upBtn = QPushButton('上移')
        downBtn = QPushButton('下移')
        delBtn = QPushButton('删除')


        upBtn.clicked.connect(self.up_step_in_feature)
        downBtn.clicked.connect(self.down_step_in_feature)
        delBtn.clicked.connect(self.del_step_from_feature)
        # saveStepBtn.clicked.connect(self.save_step_to_feature)

        # 创建用例步骤列表
        self.featureview = QTableWidget()
        self.featureview.setColumnCount(1)
        self.featureview.setHorizontalHeaderLabels(['用例步骤'])
        self.featureview.horizontalHeader().setStretchLastSection(True)
        self.featureview.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.featureview.clicked.connect(self.get_step_params)

         # 创建用例步骤参数列表
        self.stepParamview = QTableWidget()
        self.stepParamview.setColumnCount(2)
        self.stepParamview.setHorizontalHeaderLabels(['参数名', '参数值'])
        self.stepParamview.setColumnWidth(0, 180)
        self.stepParamview.horizontalHeader().setStretchLastSection(True)
        # 单元格发生变化就触发保存操作
        self.stepParamview.cellChanged.connect(self.save_step_to_feature)

        # 保存和取消按钮
        saveBtn = QPushButton('保存')
        cancelBtn = QPushButton('取消')
        cancelBtn.clicked.connect(self.close)
        saveBtn.clicked.connect(self.save_feature)

        grid.addWidget(featureLabel, 0 ,0)
        grid.addWidget(self.featureName, 0, 1, 1, 8)
        grid.addWidget(self.flagLabel, 0, 9)
        grid.addWidget(appLabel, 1, 3)

        grid.addWidget(self.appCombo, 1, 4)

        grid.addWidget(tagLabel, 1, 0)
        grid.addWidget(self.tagCombo, 1, 1)

        grid.addWidget(self.tipLabel, 1, 6)

        grid.addWidget(self.stepCombo,2, 0)
        grid.addWidget(self.search_step, 2, 1, 1, 2)
        grid.addWidget(self.step_list, 3, 0, 20, 3)
        grid.addWidget(upBtn, 2, 3)
        grid.addWidget(downBtn, 2, 4)
        grid.addWidget(delBtn, 2, 5)
        # grid.addWidget(saveStepBtn, 2, 9)

        grid.addWidget(self.featureview, 3, 3, 20, 3)
        grid.addWidget(self.stepParamview, 3, 6, 20, 4)

        grid.addWidget(saveBtn, 24, 8)
        grid.addWidget(cancelBtn, 24, 9)
        grid.setRowMinimumHeight(25, 30)

        # 设置数据展示
        try:
            self.show_steps()
        except:
            pass

        self.step_list.doubleClicked.connect(self.insert_step_to_feature)
        self.step_list.setCurrentRow(0)

        self.setLayout(grid)


        self.feature_info['module'] = ''
        self.feature_info['tags'] = ''
        try:
            self.show_feature_info(sce_name)
        except:
            pass

        self.show()
Exemplo n.º 14
0
    def cb_mouse_motion(self, event):
        """
        Callback to process a mouse movement event.

        If a point is hit by the mouse cursor, we query its index and notify
        the parent object. The parent object must then notify the fanchart (or
        any plot with a time based X axis) in order to highlight the time.

        Parameters
        ----------
        event: matplotlib.backend_bases.MouseEvent
            Data about the event.
        """
        # Restoting the original parameters.
        if self.plot_points:
            for art in self.axes.collections:
                art.set_sizes([self.point_plot_params['s']])
        if self.plot_lines:
            for art in self.axes.lines:
                art.set_linewidth(self.line_plot_params['linewidth'])

        # If the event is outside the axes, we call the timestep callback to
        # notify anyone.
        if event.xdata is None or event.ydata is None:
            if self._cb_notify_timestep:
                self._cb_notify_timestep(self.name, None)
            return False

        if not self._tree:
            return False

        _, idx = self._tree.query(np.array([event.xdata, event.ydata]))

        # Since we need only the time-step, we just take the remainder of the
        # index / number_of_curves, which gives us the timestep selected.
        pidx = math.ceil(idx / self.curves.shape[1]) - 1
        timestep = idx % self.curves.shape[1]

        art = None
        if self.plot_lines:
            art = self.axes.lines
        elif self.plot_points:
            art = self.axes.collections
        if not art:
            return True

        contains, _ = art[pidx].contains(event)

        if contains:
            if self.curvenames:
                if self.plot_points:
                    art = self.axes.collections[pidx]
                    art.set_sizes([self.point_plot_params['s'] * 3])
                if self.plot_lines:
                    art = self.axes.lines[pidx]
                    art.set_linewidth(self.line_plot_params['linewidth'] * 2)

                palette = QPalette()
                palette.setColor(QPalette.ToolTipBase, QColor(252, 243, 207))
                palette.setColor(QPalette.ToolTipText, QColor(0, 0, 0))
                QToolTip.setPalette(palette)
                QToolTip.setFont(QFont('Arial', 14, QFont.Bold))
                pos = self.mapToGlobal(QPoint(event.x,
                                              self.height() - event.y))
                QToolTip.showText(pos, '{}'.format(self.curvenames[pidx]))

                if self._cb_notify_tooltip:
                    self._cb_notify_tooltip(self.name, pidx)

            if self._cb_notify_timestep:
                self._cb_notify_timestep(self.name, timestep + 1)
        else:
            if self._cb_notify_tooltip:
                self._cb_notify_tooltip(self.name, None)
            if self._cb_notify_timestep:
                self._cb_notify_timestep(self.name, None)
            QToolTip.hideText()

        self.draw()
    def paintEvent(self, event: QPaintEvent) -> None:
        """
        Render the custom widget
        """

        painter = QStylePainter()
        painter.begin(self)

        x = 0
        y = 0
        width = self.width()

        rect = self.rect()  # type: QRect
        palette = QPalette()
        backgroundColor = palette.base().color()

        if (self.display_type == DestinationDisplayType.usage_only
                and QSplitter().lineWidth()):
            pen = painter.pen()
            painter.setPen(backgroundColor)
            painter.drawLine(rect.topLeft(), rect.topRight())
            painter.setPen(self.midPen)
            painter.drawLine(rect.bottomLeft(), rect.bottomRight())
            painter.drawLine(rect.topLeft(), rect.bottomLeft())
            if (self.container_vertical_scrollbar_visible is None
                    or not self.container_vertical_scrollbar_visible):
                painter.drawLine(rect.topRight(), rect.bottomRight())
            painter.setPen(pen)

            w = QSplitter().lineWidth()
            rect.adjust(w, w, -w, -w)

        painter.fillRect(rect, backgroundColor)

        if self.storage_space is None:
            painter.end()
            return

        highlight_menu = self.mouse_pos == DestinationDisplayMousePos.menu

        if self.display_type != DestinationDisplayType.usage_only:
            # Render the folder icon, folder name, and the menu icon
            self.deviceDisplay.paint_header(
                painter=painter,
                x=x,
                y=y,
                width=width,
                display_name=self.display_name,
                icon=self.icon,
                highlight_menu=highlight_menu,
            )
            y = y + self.deviceDisplay.dc.device_name_height

        if self.display_type != DestinationDisplayType.folder_only:
            # Render the projected storage space
            if self.display_type == DestinationDisplayType.usage_only:
                y += self.deviceDisplay.dc.padding

            photos_size_to_download, videos_size_to_download = adjusted_download_size(
                photos_size_to_download=self.photos_size_to_download,
                videos_size_to_download=self.videos_size_to_download,
                os_stat_device=self.os_stat_device,
                downloading_to=self._downloading_to,
            )

            details = make_body_details(
                bytes_total=self.storage_space.bytes_total,
                bytes_free=self.storage_space.bytes_free,
                files_to_display=self.files_to_display,
                marked=self.marked,
                photos_size_to_download=photos_size_to_download,
                videos_size_to_download=videos_size_to_download,
            )

            self.deviceDisplay.paint_body(painter=painter,
                                          x=x,
                                          y=y,
                                          width=width,
                                          details=details)

        painter.end()
Exemplo n.º 16
0
    def _toggle_stylesheet(self):
        """
        swtich between dark and normal theme
        """
        palette = QPalette()
        if self.app is not None:
            if self.normal_theme:
                # set dark theme colors
                palette.setColor(QPalette.Window, QColor(53, 53, 53))
                palette.setColor(QPalette.WindowText, Qt.white)
                palette.setColor(QPalette.Base, QColor(25, 25, 25))
                palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
                palette.setColor(QPalette.ToolTipBase, Qt.white)
                palette.setColor(QPalette.ToolTipText, Qt.white)
                palette.setColor(QPalette.Text, Qt.white)
                palette.setColor(QPalette.Button, QColor(53, 53, 53))
                palette.setColor(QPalette.ButtonText, Qt.white)
                palette.setColor(QPalette.BrightText, Qt.red)
                palette.setColor(QPalette.Link, QColor(42, 130, 218))
                palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
                palette.setColor(QPalette.HighlightedText, Qt.black)
                self.app.setPalette(palette)
                # set attributes
                self.normal_theme = False
                self.ui.menu_view_theme.setText("Normal Theme")
                # set matplotlib properties
                self.PlotCanvas_object.axes.set_facecolor((0.25, 0.25, 0.25))
                self.PlotCanvas_object.fig.set_facecolor((0.25, 0.25, 0.25))
                self.PlotCanvas_object.points.figure.canvas.draw_idle()
                self.PlotCanvas_object.fig.canvas.flush_events()
                # player buttons
                self.ui.first_icon = QIcon(module_dir +
                                           'gui_imgs/first_dt.png')
                self.ui.button_first.setIcon(self.ui.first_icon)
                self.ui.prev_icon = QIcon(module_dir + 'gui_imgs/prev_dt.png')
                self.ui.button_prev.setIcon(self.ui.prev_icon)
                if self.player_mode == "play":
                    self.ui.button_play_pause_icon = QIcon(
                        module_dir + 'gui_imgs/pause_dt.png')
                else:
                    self.ui.button_play_pause_icon = QIcon(
                        module_dir + 'gui_imgs/play_dt.png')
                self.ui.button_play_pause.setIcon(
                    self.ui.button_play_pause_icon)
                self.ui.next_icon = QIcon(module_dir + 'gui_imgs/next_dt.png')
                self.ui.button_next.setIcon(self.ui.next_icon)
                self.ui.last_icon = QIcon(module_dir + 'gui_imgs/last_dt.png')
                self.ui.button_last.setIcon(self.ui.last_icon)
                # main icon
                self.ui.MainWindow.setWindowIcon(
                    QIcon(module_dir + 'gui_imgs/NoviZ5.png'))

            else:
                # set default theme colors saved in _save_palette()
                palette.setColor(QPalette.Window, self.window_color)
                palette.setColor(QPalette.WindowText, self.window_text_color)
                palette.setColor(QPalette.Base, self.base_color)
                palette.setColor(QPalette.AlternateBase,
                                 self.alternate_base_color)
                palette.setColor(QPalette.ToolTipBase,
                                 self.tool_tip_base_color)
                palette.setColor(QPalette.ToolTipText,
                                 self.tool_tip_text_color)
                palette.setColor(QPalette.Text, self.text_color)
                palette.setColor(QPalette.Button, self.button_color)
                palette.setColor(QPalette.ButtonText, self.button_text_color)
                palette.setColor(QPalette.BrightText, self.bright_text_color)
                palette.setColor(QPalette.Link, self.link_color)
                palette.setColor(QPalette.Highlight, self.highlight_color)
                palette.setColor(QPalette.HighlightedText,
                                 self.highlighted_text_color)
                self.app.setPalette(palette)
                # set attributes
                self.normal_theme = True
                self.ui.menu_view_theme.setText("Dark Theme")
                # set matplotlib properties
                self.PlotCanvas_object.axes.set_facecolor((0.94, 0.94, 0.94))
                self.PlotCanvas_object.fig.set_facecolor((0.94, 0.94, 0.94))
                self.PlotCanvas_object.points.figure.canvas.draw_idle()
                self.PlotCanvas_object.fig.canvas.flush_events()
                # player buttons
                self.ui.first_icon = QIcon(module_dir + 'gui_imgs/first.png')
                self.ui.button_first.setIcon(self.ui.first_icon)
                self.ui.prev_icon = QIcon(module_dir + 'gui_imgs/prev.png')
                self.ui.button_prev.setIcon(self.ui.prev_icon)
                if self.player_mode == "play":
                    self.ui.button_play_pause_icon = QIcon(
                        module_dir + 'gui_imgs/pause.png')
                else:
                    self.ui.button_play_pause_icon = QIcon(module_dir +
                                                           'gui_imgs/play.png')
                self.ui.button_play_pause.setIcon(
                    self.ui.button_play_pause_icon)
                self.ui.next_icon = QIcon(module_dir + 'gui_imgs/next.png')
                self.ui.button_next.setIcon(self.ui.next_icon)
                self.ui.last_icon = QIcon(module_dir + 'gui_imgs/last.png')
                self.ui.button_last.setIcon(self.ui.last_icon)
                # main icon
                self.ui.MainWindow.setWindowIcon(
                    QIcon(module_dir + 'gui_imgs/NoviZ4.png'))

            # redraw pseudocode lines
            if self.PlotCanvas_object.algorithm is not None:
                self._fill_pseudocode_lines()
            # function string color
            if self.function_string_plain is not None:
                self.ui.label_function_parameters_show.setPixmap(
                    mathtex_to_qpixmap(self.function_string_plain,
                                       normal_theme=self.normal_theme))
            # redraw start point
            if self.PlotCanvas_object.start_point_click:
                txt = "$x=" + str(
                    round(self.PlotCanvas_object.start_point_click, 2)) + "$"
            else:
                txt = "$x=" + str(self.startpoint) + "$"
            self.ui.label_start_point.setPixmap(
                mathtex_to_qpixmap(txt, normal_theme=self.normal_theme))
Exemplo n.º 17
0
    def init_ui(self):
        #button that launches the mod
        self.launch_btn = Button(
            "Play",
            QPixmap(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             'launcher_files/launcher_play_button.png')), self)
        self.launch_btn.resize(177, 70)
        self.launch_btn.move(162, 111)
        self.launch_btn.clicked.connect(self.launch)
        self.generate_shadow(self.launch_btn)

        #button that updates the mod
        self.update_btn = Button(
            "Update",
            QPixmap(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "launcher_files/launcher_update_button.png")),
            self)
        self.update_btn.resize(177, 70)
        self.update_btn.move(162, 207)
        self.update_btn.clicked.connect(self.update)
        self.generate_shadow(self.update_btn)

        #button that opens a webbrowser to invite you to the aotr community server
        self.discord_btn = Button(
            "Discord",
            QPixmap(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             'launcher_files/launcher_discord_button.png')),
            self)
        self.discord_btn.resize(87, 34)
        self.discord_btn.move(207, 303)
        self.discord_btn.clicked.connect(
            lambda: webbrowser.open_new(self.url_discord))
        self.generate_shadow(self.discord_btn)

        #button that oppens a webbrowser to the moddb page for support help
        self.support_btn = Button(
            "Support",
            QPixmap(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             'launcher_files/launcher_support_button.png')),
            self)
        self.support_btn.resize(87, 34)
        self.support_btn.move(207, 363)
        self.support_btn.clicked.connect(
            lambda: webbrowser.open_new(self.url_support))
        self.generate_shadow(self.support_btn)

        #about box containing disaclaimer, hidden at the start
        self.about_window = QMessageBox()
        self.about_window.setIcon(QMessageBox.Information)
        self.about_window.setTextFormat(Qt.RichText)
        self.about_window.setText(self.about_text_intro)
        self.about_window.setInformativeText(self.about_text_full)
        self.about_window.setStandardButtons(QMessageBox.Ok)
        self.about_window.setWindowTitle("About")
        self.about_window.setWindowIcon(
            QIcon(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "launcher_files/aotr.ico")))
        self.about_window.buttonClicked.connect(self.about_window.close)

        self.gameranger_help = QMessageBox()
        self.gameranger_help.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.gameranger_help.setIcon(QMessageBox.Information)
        self.gameranger_help.setTextFormat(Qt.RichText)
        self.gameranger_help.setText(self.gameranger_help_intro)
        self.gameranger_help.setInformativeText(self.gameranger_help_full)
        self.gameranger_help.setStandardButtons(QMessageBox.Ok)
        self.gameranger_help.setWindowTitle("About")
        self.gameranger_help.setWindowIcon(
            QIcon(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "launcher_files/aotr.ico")))
        self.gameranger_help.buttonClicked.connect(self.gameranger_help.close)

        #progress bar for update progress, hidden at the start
        self.progress_bar = ProgressBar(self)
        self.progress_bar.hide()

        #menu containing the rest of the buttons
        bar = self.menuBar()
        # bar.setStyleSheet("QMenuBar {background-color: white;}")
        about_act = bar.addAction('About')  # about box
        about_act.triggered.connect(self.about)
        self.repair_act = bar.addAction(
            'Repair')  #basically an update but named repair for users
        self.repair_act.triggered.connect(self.repair)
        wiki_act = bar.addAction('Wiki')  #webbrowser link to the wiki
        wiki_act.triggered.connect(lambda: webbrowser.open_new(self.url_wiki))
        forums_act = bar.addAction('Forums')  #webbrowser link to the forums
        forums_act.triggered.connect(
            lambda: webbrowser.open_new(self.url_forums))

        options_menu = bar.addMenu(
            "Options...")  #submenue for uninstall and launcher flags
        flags_act = options_menu.addAction(
            "Launch Flags")  #launcher flags (-win, -scriptdebug2, ect...)
        flags_act.triggered.connect(self.flags_dialog)
        uninstall_act = options_menu.addAction('Uninstall')  #uninstall
        uninstall_act.triggered.connect(self.uninstall_dialog)
        gameranger_act = options_menu.addAction("Gameranger")
        gameranger_act.triggered.connect(self.gameranger)

        self.setFixedSize(500, 500)
        self.setWindowTitle('Age of the Ring')
        self.setWindowIcon(
            QIcon(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "launcher_files/aotr.ico")))

        #background image
        oImage = QImage(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "launcher_files/launcherBG.jpg"))
        sImage = oImage.scaled(QSize(500, 500))
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))
        self.setPalette(palette)

        self.show()

        #look for ROTWK installation
        self.path_rotwk = "GAME NOT FOUND"
        try:
            reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
            key = winreg.OpenKey(
                reg,
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\lotrbfme2ep1.exe"
            )
            self.path_rotwk = winreg.EnumValue(key, 5)[1]

            #in case the user has installed a weird version of ROTWK
            if os.path.isfile(self.path_rotwk):
                self.path_rotwk = os.path.dirname(self.path_rotwk)
        except FileNotFoundError:
            QMessageBox.critical(
                self, "Base Error",
                "Could not locate ROTWK installation. Make sure ROTWK is installed",
                QMessageBox.Ok, QMessageBox.Ok)

        #make sure the file where the flags are stored exists.
        Path(self.path_flags).touch(exist_ok=True)

        # check if a new version is available online by comparing to the version of the tree.json, if we can't find a tree.json
        # we assume that a new version is available
        if not self.is_gr:
            if os.path.exists(os.path.join(self.path_aotr, "tree.json")):
                try:
                    file_info = self.project.files.get(file_path="tree.json",
                                                       ref="master")
                    content = base64.b64decode(file_info.content)
                    version_online = json.loads(content)["version"]
                except IndexError:
                    QMessageBox.critical(
                        self, "Base Error",
                        "Did not find tree.json, you cannot currently update but can still play. Please report this bug to the discord.",
                        QMessageBox.Ok, QMessageBox.Ok)
                    return

                with open(os.path.join(self.path_aotr, "tree.json"),
                          "r") as file:
                    version = json.load(file)["version"]
                    self.mod_version = version

                    if version != version_online:
                        QMessageBox.information(
                            self, "Update Available",
                            "An update is available, click the update button to begin updating.",
                            QMessageBox.Ok, QMessageBox.Ok)
            else:
                QMessageBox.information(
                    self, "Update Available",
                    "An update is available, click the update button to begin updating.",
                    QMessageBox.Ok, QMessageBox.Ok)

        try:
            logging.basicConfig(level=logging.DEBUG,
                                filename=os.path.join(
                                    os.path.dirname(os.path.abspath(__file__)),
                                    "launcher_files/launcher.log"),
                                filemode="w")
        except:
            pass
Exemplo n.º 18
0
def main():
    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    t = time.time()
    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            urh_dir = os.path.abspath(
                os.path.join(os.path.dirname(sys.argv[0]), "..", ".."))
            sys.path.append(urh_dir)
            sys.path.append(os.path.join(urh_dir, "src"))

            import generate_ui

            generate_ui.gen()

            print("Time for generating UI: %.2f seconds" % (time.time() - t))
        except (ImportError, FileNotFoundError):
            print(
                "Will not regenerate UI, because script can't be found. This is okay in release."
            )

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..",
                           "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith(
            "/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed
        print(
            "Adding {0} to pythonpath. This is only important when running URH from source."
            .format(src_dir))
        sys.path.insert(0, src_dir)

    from urh.util import util
    util.set_windows_lib_path()

    try:
        import urh.cythonext.signalFunctions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.curdir
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(":/icons/data/icons/appicon.png"))

    if sys.platform != "linux":
        # noinspection PyUnresolvedReferences
        import urh.ui.xtra_icons_rc
        QIcon.setThemeName("oxy")

    constants.SETTINGS.setValue("default_theme", app.style().objectName())

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if constants.SETTINGS.value("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText,
                             Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    main_window = MainController()

    if sys.platform == "darwin":
        menu_bar = main_window.menuBar()
        menu_bar.setNativeMenuBar(False)
        import multiprocessing as mp
        mp.set_start_method(
            "spawn")  # prevent errors with forking in native RTL-SDR backend

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    # use system colors for painting
    widget = QWidget()
    bgcolor = widget.palette().color(QPalette.Background)
    fgcolor = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bgcolor
    constants.LINECOLOR = fgcolor
    constants.SELECTION_COLOR = selection_color
    constants.SEND_INDICATOR_COLOR = selection_color

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(
        return_code
    )  # sys.exit() is not enough on Windows and will result in crash on exit
Exemplo n.º 19
0
    def beautify(self,Form):
        # 利用qtawesome设置图标
        Form.setWindowOpacity(0.95)
        palette = QPalette()
        path = os.path.join('tools', 'timg1.jpg')
        palette.setBrush(QPalette.Background, QBrush(QPixmap(path)))
        Form.setPalette(palette)

        # icon
        iconpath = os.path.join('tools', 'amg.jpg')
        Form.setWindowIcon(QIcon(iconpath))

        #spin_icon = qtawesome.icon('fa5s.microphone-alt', color='black')
        spin_icon2 = qtawesome.icon('fa.question', color='black')
        spin_icon4 = qtawesome.icon('fa.comment', color='black')
        spin_icon5 = qtawesome.icon('fa5s.ban', color='black')
        spin_icon3 = qtawesome.icon('fa.sellsy', color='black')
        spin_icon6 = qtawesome.icon('fa.book', color='black')
        self.pushButton.setIcon(spin_icon6)
        self.pushButton_2.setIcon(spin_icon3)
        self.pushButton_3.setIcon(spin_icon2)
        self.pushButton_4.setIcon(spin_icon4)
        self.pushButton_5.setIcon(spin_icon5)
        #self.pushButton_6.setIcon(spin_icon6)

        # 设置pushbutton格式
        self.pushButton.setStyleSheet('''QPushButton{border:none;}
                                QPushButton:hover{color:white;
                                            border:2px solid #F3F3F5;
                                            border-radius:35px;
                                            background:darkGray;}''')

        self.pushButton_2.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_3.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_4.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_5.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_6.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_7.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_8.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_9.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_10.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_11.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')

        self.pushButton_12.setStyleSheet('''QPushButton{border:none;}
                                        QPushButton:hover{color:white;
                                                    border:2px solid #F3F3F5;
                                                    border-radius:35px;
                                                    background:darkGray;}''')
Exemplo n.º 20
0
    HEALTH_CHECKING,
    HEALTH_DEAD,
    HEALTH_ERROR,
    HEALTH_GOOD,
    HEALTH_MOOT,
    HEALTH_UNCHECKED,
)
from tribler_gui.utilities import format_votes, get_health, get_image_path
from tribler_gui.widgets.tablecontentmodel import Column
from tribler_gui.widgets.tableiconbuttons import DownloadIconButton

PROGRESS_BAR_BACKGROUND = QColor("#444444")
PROGRESS_BAR_FOREGROUND = QColor("#BBBBBB")
TRIBLER_NEUTRAL = QColor("#B5B5B5")
TRIBLER_ORANGE = QColor("#e67300")
TRIBLER_PALETTE = QPalette()
TRIBLER_PALETTE.setColor(QPalette.Highlight, TRIBLER_ORANGE)

DARWIN = sys.platform == 'darwin'
WINDOWS = sys.platform == 'win32'


def draw_text(painter,
              rect,
              text,
              color=TRIBLER_NEUTRAL,
              font=None,
              text_flags=Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine):
    painter.save()
    text_box = painter.boundingRect(rect, text_flags, text)
    painter.setPen(QPen(color, 1, Qt.SolidLine, Qt.RoundCap))
Exemplo n.º 21
0
    def initUI(self):
        menu = self.menuBar()  # create menu bar
        file_menu = menu.addMenu('File')  # create file button
        options_menu = menu.addMenu('Options')  # create options button
        wid = QWidget()
        self.setCentralWidget(wid)

        # create 'Open FIle' actions, add to 'File' button
        open_file = QAction('Open File', self)
        open_file.triggered.connect(self.openFile)
        open_file.setShortcut("Ctrl+O")
        file_menu.addAction(open_file)

        # create 'Close File' action, add to 'File' button
        close_file = QAction('Close File', self)
        close_file.triggered.connect(self.exit)
        close_file.setShortcut("Ctrl+W")
        file_menu.addAction(close_file)

        # create 'Exit' action, add to 'File' button
        exit_file = QAction('Close File', self)
        exit_file.triggered.connect(self.exit)
        exit_file.setShortcut("Ctrl+W")
        file_menu.addAction(exit_file)

        # create 'Color' action, add to 'Options' button
        color_option = QAction('Color', self)
        color_option.triggered.connect(self.show_color_dialog)
        color_option.setShortcut("Ctrl+2")
        options_menu.addAction(color_option)

        # create 'Shape' action, add to 'Options' button
        shape_option = QAction('Shape', self)
        # shape_option.triggered.connect()
        shape_option.setShortcut("Ctrl+3")
        options_menu.addAction(shape_option)

        # create 'Foliage' action, add to 'Options' button
        foliage_option = QAction('Foliage', self)
        # foliage_option.triggered.connect()
        foliage_option.setShortcut("Ctrl+3")
        options_menu.addAction(foliage_option)

        # Creating button for pause/play
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        videoWidget = QVideoWidget()
        self.pal = QPalette()
        self.pal.setColor(QPalette.Foreground, Qt.green)
        videoWidget.setPalette(self.pal)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Maximum)

        self.songLabel = QLabel()
        self.songLabel.setSizePolicy(QSizePolicy.Preferred,
                                     QSizePolicy.Maximum)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        self.playButton.setShortcut("Space")
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.songLabel)
        layout.addWidget(self.errorLabel)

        # Set widget to contain window contents
        wid.setLayout(layout)

        # self.mediaPlayer.setVideoOutput(videoWidget)
        self.player.stateChanged.connect(self.mediaStateChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.durationChanged.connect(self.durationChanged)
        self.player.error.connect(self.handleError)
Exemplo n.º 22
0
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletIMUV3, *args)

        self.setupUi(self)

        self.imu = self.device

        self.cbe_all_data = CallbackEmulator(self, self.imu.get_all_data, None,
                                             self.cb_all_data,
                                             self.increase_error_count)

        self.imu_gl = IMUV33DWidget(self)
        self.imu_gl.setFixedSize(200, 200)

        self.imu_gl_wrapper = None
        self.state = None

        self.data_plot_widget = []

        self.sensor_data = [CurveValueWrapper() for i in range(23)]

        self.data_labels = [
            self.label_acceleration_x, self.label_acceleration_y,
            self.label_acceleration_z, self.label_magnetic_field_x,
            self.label_magnetic_field_y, self.label_magnetic_field_z,
            self.label_angular_velocity_x, self.label_angular_velocity_y,
            self.label_angular_velocity_z, self.label_euler_angle_heading,
            self.label_euler_angle_roll, self.label_euler_angle_pitch,
            self.label_quaternion_w, self.label_quaternion_x,
            self.label_quaternion_y, self.label_quaternion_z,
            self.label_linear_acceleration_x, self.label_linear_acceleration_y,
            self.label_linear_acceleration_z, self.label_gravity_vector_x,
            self.label_gravity_vector_y, self.label_gravity_vector_z,
            self.label_temperature
        ]

        self.data_rows = [
            [
                self.label_acceleration_11, self.label_acceleration_21,
                self.label_acceleration_22, self.label_acceleration_23,
                self.label_acceleration_41, self.label_acceleration_42,
                self.label_acceleration_43, self.label_acceleration_x,
                self.label_acceleration_y, self.label_acceleration_z
            ],
            [
                self.label_magnetic_field_11, self.label_magnetic_field_21,
                self.label_magnetic_field_22, self.label_magnetic_field_23,
                self.label_magnetic_field_41, self.label_magnetic_field_42,
                self.label_magnetic_field_43, self.label_magnetic_field_x,
                self.label_magnetic_field_y, self.label_magnetic_field_z
            ],
            [
                self.label_angular_velocity_11, self.label_angular_velocity_21,
                self.label_angular_velocity_22, self.label_angular_velocity_23,
                self.label_angular_velocity_41, self.label_angular_velocity_42,
                self.label_angular_velocity_43, self.label_angular_velocity_x,
                self.label_angular_velocity_y, self.label_angular_velocity_z
            ],
            [
                self.label_euler_angle_11, self.label_euler_angle_21,
                self.label_euler_angle_22, self.label_euler_angle_23,
                self.label_euler_angle_41, self.label_euler_angle_42,
                self.label_euler_angle_43, self.label_euler_angle_roll,
                self.label_euler_angle_pitch, self.label_euler_angle_heading
            ],
            [
                self.label_quaternion_11, self.label_quaternion_21,
                self.label_quaternion_22, self.label_quaternion_23,
                self.label_quaternion_24, self.label_quaternion_41,
                self.label_quaternion_42, self.label_quaternion_43,
                self.label_quaternion_44, self.label_quaternion_w,
                self.label_quaternion_x, self.label_quaternion_y,
                self.label_quaternion_z
            ],
            [
                self.label_linear_acceleration_11,
                self.label_linear_acceleration_21,
                self.label_linear_acceleration_22,
                self.label_linear_acceleration_23,
                self.label_linear_acceleration_41,
                self.label_linear_acceleration_42,
                self.label_linear_acceleration_43,
                self.label_linear_acceleration_x,
                self.label_linear_acceleration_y,
                self.label_linear_acceleration_z
            ],
            [
                self.label_gravity_vector_11, self.label_gravity_vector_21,
                self.label_gravity_vector_22, self.label_gravity_vector_23,
                self.label_gravity_vector_41, self.label_gravity_vector_42,
                self.label_gravity_vector_43, self.label_gravity_vector_x,
                self.label_gravity_vector_y, self.label_gravity_vector_z
            ],
            [
                self.label_temperature_11, self.label_temperature_21,
                self.label_temperature_41, self.label_temperature
            ]
        ]

        even_color = QColor(240, 240, 240)
        odd_color = QColor(255, 255, 255)

        self.data_color = [(Qt.red, even_color), (Qt.darkGreen, even_color),
                           (Qt.blue, even_color), (Qt.red, odd_color),
                           (Qt.darkGreen, odd_color), (Qt.blue, odd_color),
                           (Qt.red, even_color), (Qt.darkGreen, even_color),
                           (Qt.blue, even_color), (Qt.red, odd_color),
                           (Qt.darkGreen, odd_color), (Qt.blue, odd_color),
                           (Qt.magenta, even_color), (Qt.red, even_color),
                           (Qt.darkGreen, even_color), (Qt.blue, even_color),
                           (Qt.red, odd_color), (Qt.darkGreen, odd_color),
                           (Qt.blue, odd_color), (Qt.red, even_color),
                           (Qt.darkGreen, even_color), (Qt.blue, even_color),
                           (Qt.magenta, odd_color)]

        even_palette = QPalette()
        even_palette.setColor(QPalette.Window, even_color)
        odd_palette = QPalette()
        odd_palette.setColor(QPalette.Window, odd_color)

        for i, row in enumerate(self.data_rows):
            for label in row:
                if i % 2:
                    label.setPalette(odd_palette)
                else:
                    label.setPalette(even_palette)

                label.setAutoFillBackground(True)

        self.plot_timer = QTimer(self)
        self.plot_timer.start(100)

        for i in range(23):
            self.data_plot_widget.append(
                PlotWidget(
                    "",
                    [("", self.data_color[i][0], self.sensor_data[i], str)],
                    clear_button=self.clear_graphs,
                    x_scale_visible=False,
                    y_scale_visible=False,
                    curve_outer_border_visible=False,
                    curve_motion='smooth',
                    canvas_color=self.data_color[i][1],
                    external_timer=self.plot_timer,
                    curve_start='right',
                    key=None,
                    y_resolution=0.01))

        for w in self.data_plot_widget:
            w.setMinimumHeight(15)
            w.setMaximumHeight(25)

        for i in range(23):
            self.data_grid.addWidget(self.data_plot_widget[i], i, 4)

        self.data_grid.setColumnMinimumWidth(2, 75)

        self.gl_layout = QVBoxLayout()
        self.gl_layout.addWidget(self.imu_gl)
        self.layout_bottom.addLayout(self.gl_layout)
        self.save_orientation.clicked.connect(self.save_orientation_clicked)
        self.button_detach_3d_view.clicked.connect(self.detach_3d_view_clicked)

        self.button_calibration.clicked.connect(self.calibration_clicked)
        self.calibration_color = [
            Qt.red, QColor(0xFF, 0xA0, 0x00), Qt.yellow, Qt.darkGreen
        ]

        self.calibration = None
        self.alive = True
        self.callback_counter = 0
Exemplo n.º 23
0
    def initUI(self):
        self.setWindowTitle("番茄计时器")
        self.setGeometry(0, 0, 256, 208)
        # 设置番茄图标(程序和托盘)
        self.icon = QIcon(os.path.join(BASE_DIR, 'tomato.svg'))
        self.setWindowIcon(self.icon)
        # 设置托盘功能(显示计时、还原窗体和退出程序)
        self.tray = QSystemTrayIcon()
        self.tray.setIcon(self.icon)
        self.tray_menu = QMenu(QApplication.desktop())
        self.restoreAction = QAction('显示', self, triggered=self.show)
        self.quitAction = QAction('退出', self, triggered=app.quit)

        self.tipAction = QAction(
            "%s/%d > %2d:%02d" %
            (self.current_status, self.round + 1, self.second_remain // 60,
             self.second_remain % 60),
            self,
            triggered=self.show)
        self.tray_menu.addAction(self.tipAction)
        self.tray_menu.addAction(self.restoreAction)
        self.tray_menu.addAction(self.quitAction)
        self.tray.setContextMenu(self.tray_menu)
        # 设置定时器
        self.timer = QTimer()  # 初始化计时器
        self.timer.setInterval(1000)  # 每秒跳1次
        self.timer.timeout.connect(self.onTimer)  # 绑定定时触发事件

        vbox = QVBoxLayout()
        # 提示标签
        self.labelRound = QLabel(self)  # 提示标签
        self.labelRound.setText("准备开始")
        self.labelRound.setFixedHeight(50)
        self.labelRound.setAlignment(Qt.AlignCenter)
        self.pe = QPalette()
        self.pe.setColor(QPalette.Window, Qt.darkRed)  # 蓝底白字
        self.pe.setColor(QPalette.WindowText, Qt.white)
        self.labelRound.setAutoFillBackground(True)
        self.labelRound.setPalette(self.pe)
        self.labelRound.setFont(QFont("Courier", 20, QFont.Courier))

        vbox.addWidget(self.labelRound)
        # 倒计时显示器
        self.clock = QLCDNumber(self)  # 剩余时间显示组件
        self.clock.display("%2d:%02d" % (self.work, 0))
        vbox.addWidget(self.clock)

        hbox = QHBoxLayout()
        vbox.addLayout(hbox)
        # 功能按钮
        self.startButton = QPushButton("开始")
        self.startButton.clicked.connect(self.start)
        hbox.addWidget(self.startButton)

        self.stopButton = QPushButton("停止")
        self.stopButton.setEnabled(False)
        self.stopButton.clicked.connect(self.stop)
        hbox.addWidget(self.stopButton)

        self.pauseButton = QPushButton("暂停")
        self.pauseButton.setEnabled(False)
        self.pauseButton.clicked.connect(self.pause)
        hbox.addWidget(self.pauseButton)

        self.setLayout(vbox)

        self.tray.show()
        self.show()
Exemplo n.º 24
0
    def initLoginScreen(self):

        # font
        font = QFont("Arial", 23)

        self.set_background("./Graphics/background.gif")

        # labels
        self.l_username = QLabel("nr indeksu", self)
        self.l_username.setFont(font)

        palette = QPalette()
        palette.setColor(QPalette.Foreground, Qt.white)
        self.l_username.setPalette(palette)
        self.l_username.move(120, 170)

        l_password = QLabel("hasło", self)
        l_password.setFont(font)
        l_password.setPalette(palette)
        l_password.move(120, 200)

        palette.setColor(QPalette.Foreground, Qt.red)
        self.message = QLabel("Niepoprawny login lub hasło", self)
        self.message.move(200, 280)
        self.message.setPalette(palette)
        self.message.hide()

        font = QFont("Arial", 18)
        metrics = QFontMetrics(font)

        # line edits
        self.le_username = QLineEdit(self)
        self.le_username.setFont(QFont("Arial", 16))
        self.le_username.setFixedSize(metrics.width("888888888888"),
                                      metrics.height())
        self.le_username.move(
            260,
            self.l_username.y() + (self.l_username.height() / 2) -
            (self.le_username.height() / 2))  # center lineEdit
        self.le_username.setAttribute(Qt.WA_MacShowFocusRect, 0)
        self.le_username.setFocus()
        self.le_username.textChanged.connect(
            lambda: (self.message.hide(), self.le_username.disconnect()))

        self.le_password = QLineEdit(self)
        self.le_password.setFont(font)
        self.le_password.setFixedSize(metrics.width("888888888888"),
                                      metrics.height())
        self.le_password.move(
            260,
            l_password.y() + (l_password.height() / 2) -
            (self.le_password.height() / 2))  # center lineEdit
        self.le_password.setAttribute(Qt.WA_MacShowFocusRect, 0)
        self.le_password.setEchoMode(QLineEdit.Password)
        self.le_password.textChanged.connect(
            lambda: (self.message.hide(), self.le_password.disconnect()))

        # button
        submit = QPushButton(self)
        submit.setFont(QFont("Arial", 16))
        submit.setStyleSheet("background-color: solid")
        submit.setText("zaloguj")
        submit.setFixedSize(self.le_password.width(), submit.height() + 3)
        submit.move(260, 240)
        submit.clicked.connect(self.submit_on_clicked)

        # window settings
        self.setFixedSize(500, 300)
        self.setWindowTitle("Ps scraper")
        self.show()
Exemplo n.º 25
0
    def __init__(self, titleName):  # 构造函数
        super(videoPlayer, self).__init__()  # 类的继承

        self.length = 0  # 视频总时长
        self.position = 0  # 视频当前时长
        self.count = 0
        self.player_status = -1

        # 设置窗口
        self.setGeometry(300, 50, 1200, 800) #大小,与桌面放置位置
        self.setWindowIcon(QIcon(':/images/video_player_icon.png'))  # 程序图标
        self.setWindowTitle(titleName)  # 窗口名称
        self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint)
     

        # 设置窗口背景
        self.palette = QPalette()  
        self.palette.setColor(QPalette.Background, Qt.black)
        self.setPalette(self.palette)

        self.now_position = QLabel("/  00:00")   # 目前时间进度
        self.all_duration = QLabel('00:00')   # 总的时间进度
        self.all_duration.setStyleSheet('''QLabel{color:#ffffff}''')
        self.now_position.setStyleSheet('''QLabel{color:#ffffff}''')

        #视频插件
        self.video_widget = QVideoWidget(self)
        self.video_widget.setGeometry(QRect(0, 0, 1200, 700)) #大小,与桌面放置位置
        #self.video_widget.resize(1200, 700)  # 设置插件宽度与高度
        #self.video_widget.move(0, 30)   # 设置插件放置位置
        self.video_palette = QPalette()
        self.video_palette.setColor(QPalette.Background, Qt.black)  # 设置播放器背景
        self.video_widget.setPalette(self.video_palette)
        video_widget_color="background-color:#000000"
        self.video_widget.setStyleSheet(video_widget_color)
        
     
        #布局容器
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(0)
        #self.verticalLayout.setContentsMargins(0, 5, 0, 10)
        self.layout = QHBoxLayout()
        self.layout.setSpacing(15)   # 各个插件的间距
        
        
        
        # 设置播放器
        self.player = QMediaPlayer(self)   
        self.player.setVideoOutput(self.video_widget)
        #设置播放按钮事件
        self.player.durationChanged.connect(self.get_duration_func)
        self.player.positionChanged.connect(self.progress)  # 媒体播放时发出信号
        self.player.mediaStatusChanged.connect(self.playerStatusChanged)
        self.player.error.connect(self.player_error)
        

        # 播放按钮
        self.play_btn = QPushButton(self)
        self.play_btn.setIcon(QIcon(':/images/play_btn_icon.png'))  # 设置按钮图标,下同
        self.play_btn.setIconSize(QSize(35,35))
        self.play_btn.setStyleSheet('''QPushButton{border:none;}QPushButton:hover{border:none;border-radius:35px;}''')
        self.play_btn.setCursor(QCursor(Qt.PointingHandCursor))
        self.play_btn.setToolTip("播放")
        self.play_btn.setFlat(True)
        #self.play_btn.hide()
        #isHidden()      #判定控件是否隐藏

        #isVisible()     判定控件是否显示
        self.play_btn.clicked.connect(self.start_button)

        #音量条        
        self.volume_slider = QSlider(Qt.Horizontal)  # 声音设置
        self.volume_slider.setMinimum(0)    # 音量0到100
        self.volume_slider.setMaximum(100)
       
        self.volume_slider.valueChanged.connect(self.volumes_change)
      
        self.volume_slider.setStyleSheet('''QSlider{}
QSlider::sub-page:horizontal:disabled{background: #00009C;  border-color: #999;  }
QSlider::add-page:horizontal:disabled{background: #eee;  border-color: #999; }
QSlider::handle:horizontal:disabled{background: #eee;  border: 1px solid #aaa;  border-radius: 4px;  }
QSlider::add-page:horizontal{background: #575757;  border: 0px solid #777;  height: 10px;border-radius: 2px; }
QSlider::handle:horizontal:hover{background:qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0.6 #2A8BDA,   stop:0.778409 rgba(255, 255, 255, 255));  width: 11px;  margin-top: -3px;  margin-bottom: -3px;  border-radius: 5px; }
QSlider::sub-page:horizontal{background: qlineargradient(x1:0, y1:0, x2:0, y2:1,   stop:0 #B1B1B1, stop:1 #c4c4c4);  background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,stop: 0 #5DCCFF, stop: 1 #1874CD);  border: 1px solid #4A708B;  height: 10px;  border-radius: 2px;  }
QSlider::groove:horizontal{border: 1px solid #4A708B;  background: #C0C0C0;  height: 5px;  border-radius: 1px;  padding-left:-1px;  padding-right:-1px;}
QSlider::handle:horizontal{background: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5,   stop:0.6 #45ADED, stop:0.778409 rgba(255, 255, 255, 255));  width: 11px;  margin-top: -3px;  margin-bottom: -3px;  border-radius: 5px; }''')


        #视频播放进度条        
        self.video_slider = QSlider(Qt.Horizontal, self)  # 视频进度拖拖动
        self.video_slider.setMinimum(0)   # 视频进度0到100%
        #self.video_slider.setMaximum(100)
        self.video_slider.setSingleStep(1)
        self.video_slider.setGeometry(QRect(0, 0, 200, 10))
        self.video_slider.sliderReleased.connect(self.video_silder_released)
        self.video_slider.sliderPressed.connect(self.video_silder_pressed)
        
        self.video_slider.setStyleSheet('''QSlider{}
QSlider::sub-page:horizontal:disabled{background: #00009C;  border-color: #999;  }
QSlider::add-page:horizontal:disabled{background: #eee;  border-color: #999; }
QSlider::handle:horizontal:disabled{background: #eee;  border: 1px solid #aaa;  border-radius: 4px;  }
QSlider::add-page:horizontal{background: #575757;  border: 0px solid #777;  height: 10px;border-radius: 2px; }
QSlider::handle:horizontal:hover{background:qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0.6 #2A8BDA,   stop:0.778409 rgba(255, 255, 255, 255));  width: 11px;  margin-top: -3px;  margin-bottom: -3px;  border-radius: 5px; }
QSlider::sub-page:horizontal{background: qlineargradient(x1:0, y1:0, x2:0, y2:1,   stop:0 #B1B1B1, stop:1 #c4c4c4);  background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,stop: 0 #5DCCFF, stop: 1 #1874CD);  border: 1px solid #4A708B;  height: 10px;  border-radius: 2px;  }
QSlider::groove:horizontal{border: 1px solid #4A708B;  background: #C0C0C0;  height: 5px;  border-radius: 1px;  padding-left:-1px;  padding-right:-1px;}
QSlider::handle:horizontal{background: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5,   stop:0.6 #45ADED, stop:0.778409 rgba(255, 255, 255, 255));  width: 11px;  margin-top: -3px;  margin-bottom: -3px;  border-radius: 5px; }''')

     #静音按钮    
        self.mute_button = QPushButton('')
        self.mute_button.clicked.connect(self.mute)
        self.mute_button.setIconSize(QSize(30,30))
        self.mute_button.setStyleSheet('''QPushButton{border:none;}QPushButton:hover{border:none;}''')
        self.mute_button.setCursor(QCursor(Qt.PointingHandCursor))
        self.mute_button.setToolTip("播放")
        self.mute_button.setFlat(True)
        self.mute_button.setIcon(QIcon(':/images/sound_btn_icon.png'))
                            
        
        #暂停按钮
        self.pause_btn = QPushButton('')   
        self.pause_btn.setIcon(QIcon(':/images/stop_btn_icon.png'))
        self.pause_btn.clicked.connect(self.stop_button)
        self.pause_btn.setIconSize(QSize(35,35))
        self.pause_btn.setStyleSheet('''QPushButton{border:none;}QPushButton:hover{border:none;}''')
        self.pause_btn.setCursor(QCursor(Qt.PointingHandCursor))
        self.pause_btn.setToolTip("播放")
        self.pause_btn.setFlat(True)
        self.pause_btn.hide()
        

        #音量值和音量显示标签
        self.volume_value = QLabel()
        self.volume_value.setText(' ' * 5)
        self.volume_value.setStyleSheet('''QLabel{color:#ffffff;}''')

        self.volume_t = QLabel()
        
        self.volume_t.setStyleSheet('''QLabel{color:#ffffff;}''')

        #视频文件打开按钮
        self.open_btn = QPushButton('Open')
        self.open_btn.clicked.connect(self.getfile)

        #全屏按钮
        self.screen_btn = QPushButton('')
        self.screen_btn.setIcon(QIcon(QPixmap(':/images/fullsrceen_btn_icon.png')))
        self.screen_btn.setIconSize(QSize(38,38))
        self.screen_btn.setStyleSheet('''QPushButton{border:none;}QPushButton:hover{border:1px solid #F3F3F5;border-radius:35px;}''')
        self.screen_btn.setCursor(QCursor(Qt.PointingHandCursor))
        self.screen_btn.setToolTip("播放")
        self.screen_btn.setFlat(True)
        self.screen_btn.clicked.connect(self.fullscreen)

        #添加按钮组件
        self.verticalLayout.addStretch()
        self.layout.addWidget(self.play_btn, 0, Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addWidget(self.pause_btn, 0, Qt.AlignCenter | Qt.AlignVCenter)  # 插件,与前一个模块的距离,位置
        
        self.layout.addWidget(self.all_duration,0, Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addWidget(self.now_position, 0, Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addWidget(self.video_slider, 15, Qt.AlignVCenter | Qt.AlignVCenter)
        self.layout.addWidget(self.mute_button , 0, Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addWidget(self.volume_slider, 0, Qt.AlignCenter | Qt.AlignVCenter)
    
        self.layout.addWidget(self.volume_value, 0, Qt.AlignCenter | Qt.AlignVCenter)
       
        #self.layout.addWidget(self.screen_btn)
        #self.layout.addWidget(self.open_btn)
        self.verticalLayout.addLayout(self.layout)
        
        #self.verticalLayout.addLayout(self.layout)
        self.setLayout(self.verticalLayout)
Exemplo n.º 26
0
    def initUI(self):
        # Add core elements for the window
        self.lblDesign = QLabel("", self)
        self.lblDesign.setStyleSheet(
            "background-color: #019A74; font-weight: bold; color: White; font-family: century gothic; font-size: 16px"
        )
        self.lblDesign.setMinimumSize(400, 70)

        self.lbl_tittle1 = QLabel("Aula ", self)
        self.lbl_tittle1.setStyleSheet(
            "font-weight: b  old; color: white; font-family: century gothic; font-size: 32px"
        )
        self.lbl_tittle1.move(100, 80)
        self.img_logo = QLabel(self)
        pixmap = QPixmap("Images/mini_Teacher3.png")
        self.img_logo.setPixmap(pixmap)
        self.img_logo.move(20, -12)
        self.img_logo.setMinimumSize(100, 100)

        self.lbl_tittle2 = QLabel("Virtual", self)
        self.lbl_tittle2.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 32px"
        )
        self.lbl_tittle2.setMinimumSize(110, 30)
        self.lbl_tittle2.move(192, 80)

        # This window
        self.setFixedSize(400, 650)
        self.setWindowTitle('Registro de usuario')
        #self.setWindowIcon(QtGui.QIcon('Clases/images/b6.ico'))

        # Label name
        self.lbl_name = QLabel("Nombre", self)
        self.lbl_name.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_name.move(50, 120)

        # Text field name
        self.txt_name = QLineEdit(self)
        self.txt_name.move(50, 150)
        self.txt_name.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15px"
        )
        self.txt_name.setMinimumSize(300, 25)

        #Label last_name
        self.lbl_last_name = QLabel("Apellido paterno", self)
        self.lbl_last_name.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_last_name.setMinimumSize(200, 200)
        self.lbl_last_name.move(50, 100)

        #Text field last_name
        self.txt_last_name = QLineEdit(self)
        self.txt_last_name.move(50, 215)
        self.txt_last_name.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15px"
        )
        self.txt_last_name.setMinimumSize(300, 25)

        #Label last_name_m
        self.lbl_last_name_m = QLabel("Apellido materno", self)
        self.lbl_last_name_m.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_last_name_m.setMinimumSize(200, 200)
        self.lbl_last_name_m.move(50, 165)

        #Text field last_name_m
        self.txt_last_name_m = QLineEdit(self)
        self.txt_last_name_m.move(50, 280)
        self.txt_last_name_m.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15px"
        )
        self.txt_last_name_m.setMinimumSize(300, 25)

        #Label matricula
        self.lbl_matricula = QLabel("Matrícula", self)
        self.lbl_matricula.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_matricula.move(50, 315)

        #Text field matricula
        self.txt_matricula = QLineEdit(self)
        self.txt_matricula.move(50, 345)
        self.txt_matricula.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15px"
        )
        self.txt_matricula.setMinimumSize(300, 25)

        #Label email
        self.lbl_email = QLabel("Correo", self)
        self.lbl_email.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_email.move(50, 380)

        #Text field email
        self.txt_email = QLineEdit(self)
        self.txt_email.move(50, 410)
        self.txt_email.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15px"
        )
        self.txt_email.setMinimumSize(300, 25)

        # Label password
        self.lbl_password = QLabel("Contraseña", self)
        self.lbl_password.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_password.move(50, 440)
        self.lbl_password.setMinimumSize(300, 35)

        # Text field Password
        self.txt_password = QLineEdit(self)
        self.txt_password.setEchoMode(QLineEdit.Password)
        self.txt_password.move(50, 475)
        self.txt_password.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15"
        )
        self.txt_password.setMinimumSize(300, 25)

        # Label repeat_password
        self.lbl_repeat_password = QLabel("Repetir contraseña", self)
        self.lbl_repeat_password.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 15px"
        )
        self.lbl_repeat_password.move(50, 505)
        self.lbl_repeat_password.setMinimumSize(300, 35)

        # Text field repeat_assword
        self.txt_repeat_password = QLineEdit(self)
        self.txt_repeat_password.setEchoMode(QLineEdit.Password)
        self.txt_repeat_password.move(50, 540)
        self.txt_repeat_password.setStyleSheet(
            "font-weight: bold; color: black; font-family: century gothic; font-size: 15"
        )
        self.txt_repeat_password.setMinimumSize(300, 25)

        # Button to register
        self.btn_registry = QPushButton('Registrarme', self)
        # self.btn_login.resize()
        self.btn_registry.move(155, 600)
        self.btn_registry.setStyleSheet(
            "background-color: #08AE9E; font-weight: bold; color: White; font-family: century gothic; font-size: 16px"
        )
        self.btn_registry.clicked.connect(self.registry_clicked)
        #cell.clicked.connect(self.buttonClicked)

        # Label empty fields
        self.lbl_succes = QLabel("Registro realizado correctamente", self)
        self.lbl_succes.setStyleSheet(
            "font-weight: bold; color: orange; font-family: century gothic; font-size: 14px"
        )
        self.lbl_succes.move(50, 570)
        self.lbl_succes.setMinimumSize(300, 30)
        self.lbl_succes.setVisible(False)

        # Label empty fields
        self.lbl_empty_fields = QLabel("Hay campos vacios", self)
        self.lbl_empty_fields.setStyleSheet(
            "font-weight: bold; color: orange; font-family: century gothic; font-size: 14px"
        )
        self.lbl_empty_fields.move(50, 570)
        self.lbl_empty_fields.setMinimumSize(300, 30)
        self.lbl_empty_fields.setVisible(False)

        # Label invalid fields
        self.lbl_invalid_password = QLabel("La contraseña no coincide", self)
        self.lbl_invalid_password.setStyleSheet(
            "font-weight: bold; color: orange; font-family: century gothic; font-size: 14px"
        )
        self.lbl_invalid_password.move(50, 570)
        self.lbl_invalid_password.setMinimumSize(300, 30)
        self.lbl_invalid_password.setVisible(False)

        # Log out button
        self.lbl_exit = QLabel('Regresar', self)
        self.lbl_exit.move(310, 40)
        self.lbl_exit.setStyleSheet(
            "font-weight: bold; color: white; font-family: century gothic; font-size: 14px"
        )
        self.lbl_exit.setMinimumSize(100, 15)
        self.lbl_exit.mousePressEvent = self.exit_clicked

        # Set baackground
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(QColor("#1B528A")))
        # 2F4D6B"
        self.setPalette(palette)
        self.show()
Exemplo n.º 27
0
button1.setText('按钮')
button1.setToolTip('这是按钮')
button1.move(100, 100)
button1.resize(100, 100)  # 工作区尺寸
button1.clicked.connect(onClick_button1)

lable1 = QLabel(main)
lable1.setText('<a href="www.baidu.com">百度一下</a>')
lable1.move(100, 230)
lable1.resize(100, 50)
lable1.setFont(QFont('SongTi', 14))
# 打开外部链接(跳转网页和触发事件二者选其一)
# lable1.setOpenExternalLinks(True)
lable1.setAlignment(Qt.AlignCenter)
# 允许填充背景
lable1.setAutoFillBackground(True)
palette = QPalette()
palette.setColor(QPalette.Window, Qt.green)
lable1.setPalette(palette)
lable1.linkActivated.connect(linkClicked)
lable1.linkHovered.connect(linkHovered)

lable2 = QLabel(main)
lable2.setAlignment(Qt.AlignCenter)
lable2.setPixmap(QPixmap("C:/Users/Administrator/Desktop/wuli.png"))
# lable2.linkActivated.connect(linkClicked)

main.resize(300, 300)
main.setWindowTitle('标题')
main.show()
sys.exit(app.exec_())
Exemplo n.º 28
0
Arquivo: main.py Projeto: yarda/urh
def main():
    fix_windows_stdout_stderr()

    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..", "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith("/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed -> add directory to path
        sys.path.insert(0, src_dir)

    if len(sys.argv) > 1 and sys.argv[1] == "--version":
        import urh.version
        print(urh.version.VERSION)
        sys.exit(0)

    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            sys.path.insert(0, os.path.join(prefix))
            from data import generate_ui
            generate_ui.gen()
        except (ImportError, FileNotFoundError):
            print("Will not regenerate UI, because script can't be found. This is okay in release.")

    from urh.util import util
    util.set_windows_lib_path()

    try:
        import urh.cythonext.signalFunctions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        if hasattr(sys, "frozen"):
            print("C++ Extensions not found. Exiting...")
            sys.exit(1)
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.curdir
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(["URH"] + sys.argv[1:])
    app.setWindowIcon(QIcon(":/icons/icons/appicon.png"))

    util.set_icon_theme()

    constants.SETTINGS.setValue("default_theme", app.style().objectName())

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if constants.SETTINGS.value("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    main_window = MainController()

    if sys.platform == "darwin":
        menu_bar = main_window.menuBar()
        menu_bar.setNativeMenuBar(False)
        import multiprocessing as mp
        mp.set_start_method("spawn")  # prevent errors with forking in native RTL-SDR backend
    elif sys.platform == "win32":
        # Ensure we get the app icon in windows taskbar
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("jopohl.urh")
        import multiprocessing as mp
        mp.freeze_support()

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    # use system colors for painting
    widget = QWidget()
    bgcolor = widget.palette().color(QPalette.Background)
    fgcolor = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bgcolor
    constants.LINECOLOR = fgcolor
    constants.SELECTION_COLOR = selection_color
    constants.SEND_INDICATOR_COLOR = selection_color

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(return_code)  # sys.exit() is not enough on Windows and will result in crash on exit
Exemplo n.º 29
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1871, 1200)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.transformsGroupBox = QGroupBox(self.centralwidget)
        self.transformsGroupBox.setGeometry(QRect(1500, 170, 240, 500))
        self.transformsGroupBox.setMaximumSize(QSize(240, 600))
        font = QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.transformsGroupBox.setFont(font)
        self.transformsGroupBox.setToolTip("")
        self.transformsGroupBox.setWhatsThis("")
        self.transformsGroupBox.setObjectName("transformsGroupBox")
        self.edgesButton = QPushButton(self.transformsGroupBox)
        self.edgesButton.setGeometry(QRect(110, 180, 120, 30))
        self.edgesButton.setObjectName("edgesButton")
        self.brightnessButton = QPushButton(self.transformsGroupBox)
        self.brightnessButton.setGeometry(QRect(110, 20, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.brightnessButton.setFont(font)
        self.brightnessButton.setObjectName("brightnessButton")
        self.getSizeButton = QPushButton(self.transformsGroupBox)
        self.getSizeButton.setGeometry(QRect(0, 470, 75, 23))
        self.getSizeButton.setObjectName("getSizeButton")
        self.paramsGroupBox = QGroupBox(self.transformsGroupBox)
        self.paramsGroupBox.setGeometry(QRect(10, 29, 91, 321))
        font = QFont()
        font.setPointSize(8)
        self.paramsGroupBox.setFont(font)
        self.paramsGroupBox.setObjectName("paramsGroupBox")
        self.leftSlider = QSlider(self.paramsGroupBox)
        self.leftSlider.setGeometry(QRect(10, 50, 20, 240))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.leftSlider.sizePolicy().hasHeightForWidth())
        self.leftSlider.setSizePolicy(sizePolicy)
        self.leftSlider.setOrientation(Qt.Vertical)
        self.leftSlider.setTickPosition(QSlider.TicksAbove)
        self.leftSlider.setObjectName("leftSlider")
        self.rightSlider = QSlider(self.paramsGroupBox)
        self.rightSlider.setGeometry(QRect(50, 50, 20, 240))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.rightSlider.sizePolicy().hasHeightForWidth())
        self.rightSlider.setSizePolicy(sizePolicy)
        self.rightSlider.setOrientation(Qt.Vertical)
        self.rightSlider.setTickPosition(QSlider.TicksAbove)
        self.rightSlider.setObjectName("rightSlider")
        self.leftLabel = QLabel(self.paramsGroupBox)
        self.leftLabel.setGeometry(QRect(10, 20, 20, 15))
        self.leftLabel.setTextFormat(Qt.PlainText)
        self.leftLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.leftLabel.setObjectName("leftLabel")
        self.rightLabel = QLabel(self.paramsGroupBox)
        self.rightLabel.setGeometry(QRect(50, 20, 20, 15))
        self.rightLabel.setTextFormat(Qt.PlainText)
        self.rightLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.rightLabel.setObjectName("rightLabel")
        self.adaptiveThresholdButton = QPushButton(self.transformsGroupBox)
        self.adaptiveThresholdButton.setGeometry(QRect(110, 140, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.adaptiveThresholdButton.setFont(font)
        self.adaptiveThresholdButton.setObjectName("adaptiveThresholdButton")
        self.gray2colSelButton = QPushButton(self.transformsGroupBox)
        self.gray2colSelButton.setGeometry(QRect(110, 100, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.gray2colSelButton.setFont(font)
        self.gray2colSelButton.setObjectName("gray2colSelButton")
        self.gray2colAllButton = QPushButton(self.transformsGroupBox)
        self.gray2colAllButton.setGeometry(QRect(110, 60, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.gray2colAllButton.setFont(font)
        self.gray2colAllButton.setObjectName("gray2colAllButton")
        self.fftButton = QPushButton(self.transformsGroupBox)
        self.fftButton.setGeometry(QRect(110, 220, 120, 30))
        self.fftButton.setObjectName("fftButton")
        self.dftButton = QPushButton(self.transformsGroupBox)
        self.dftButton.setGeometry(QRect(110, 260, 120, 30))
        self.dftButton.setObjectName("dftButton")
        self.gaborButton = QPushButton(self.transformsGroupBox)
        self.gaborButton.setGeometry(QRect(110, 300, 120, 30))
        self.gaborButton.setObjectName("gaborButton")
        self.differenceButton = QPushButton(self.transformsGroupBox)
        self.differenceButton.setGeometry(QRect(110, 340, 120, 30))
        self.differenceButton.setObjectName("differenceButton")
        self.RGB2GrayButton = QPushButton(self.transformsGroupBox)
        self.RGB2GrayButton.setGeometry(QRect(110, 380, 120, 30))
        self.RGB2GrayButton.setObjectName("RGB2GrayButton")
        self.invertedCheckBox = QCheckBox(self.transformsGroupBox)
        self.invertedCheckBox.setGeometry(QRect(110, 430, 121, 17))
        self.invertedCheckBox.setObjectName("invertedCheckBox")
        self.angleDial = QDial(self.transformsGroupBox)
        self.angleDial.setGeometry(QRect(20, 360, 81, 64))
        self.angleDial.setMinimum(1)
        self.angleDial.setMaximum(4)
        self.angleDial.setPageStep(1)
        self.angleDial.setSliderPosition(1)
        self.angleDial.setWrapping(False)
        self.angleDial.setNotchesVisible(True)
        self.angleDial.setObjectName("angleDial")
        self.groupButtonsBox = QGroupBox(self.centralwidget)
        self.groupButtonsBox.setGeometry(QRect(1500, 730, 241, 141))
        self.groupButtonsBox.setMaximumSize(QSize(250, 600))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.groupButtonsBox.setFont(font)
        self.groupButtonsBox.setObjectName("groupButtonsBox")
        self.addImgButton = QPushButton(self.groupButtonsBox)
        self.addImgButton.setGeometry(QRect(50, 20, 150, 30))
        palette = QPalette()
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Button, brush)
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Button, brush)
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Button, brush)
        self.addImgButton.setPalette(palette)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.addImgButton.setFont(font)
        self.addImgButton.setObjectName("addImgButton")
        self.saveSceneImgButton = QPushButton(self.groupButtonsBox)
        self.saveSceneImgButton.setGeometry(QRect(50, 60, 150, 30))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.saveSceneImgButton.setFont(font)
        self.saveSceneImgButton.setObjectName("saveSceneImgButton")
        self.saveImgButton = QPushButton(self.groupButtonsBox)
        self.saveImgButton.setGeometry(QRect(50, 100, 150, 30))
        font = QFont()
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.saveImgButton.setFont(font)
        self.saveImgButton.setObjectName("saveImgButton")
        self.graphicsView = QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QRect(10, 15, 1471, 900))
        self.graphicsView.setMaximumSize(QSize(4000, 3000))
        self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.graphicsView.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.graphicsView.setObjectName("graphicsView")
        self.scene = TransformScene()
        self.graphicsView.setScene(self.scene)
        self.scaleEditLabel = QLabel(self.centralwidget)
        self.scaleEditLabel.setGeometry(QRect(1500, 100, 47, 13))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.scaleEditLabel.setFont(font)
        self.scaleEditLabel.setObjectName("scaleEditLabel")
        self.scaleBox = QDoubleSpinBox(self.centralwidget)
        self.scaleBox.setGeometry(QRect(1550, 100, 62, 22))
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        self.scaleBox.setFont(font)
        self.scaleBox.setMinimum(0.1)
        self.scaleBox.setMaximum(10.0)
        self.scaleBox.setSingleStep(0.1)
        self.scaleBox.setProperty("value", 0.5)
        self.scaleBox.setObjectName("scaleBox")
        self.infoLabel = QLabel(self.centralwidget)
        self.infoLabel.setGeometry(QRect(1499, 130, 230, 20))
        self.infoLabel.setFrameShape(QFrame.WinPanel)
        self.infoLabel.setText("")
        self.infoLabel.setAlignment(Qt.AlignCenter)
        self.infoLabel.setObjectName("infoLabel")
        self.infoLabel_2 = QLabel(self.centralwidget)
        self.infoLabel_2.setGeometry(QRect(1500, 20, 230, 20))
        font = QFont()
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.infoLabel_2.setFont(font)
        self.infoLabel_2.setFrameShape(QFrame.WinPanel)
        self.infoLabel_2.setText("")
        self.infoLabel_2.setAlignment(Qt.AlignCenter)
        self.infoLabel_2.setObjectName("infoLabel_2")
        self.infoLabel_3 = QLabel(self.centralwidget)
        self.infoLabel_3.setGeometry(QRect(1500, 60, 230, 20))
        font = QFont()
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.infoLabel_3.setFont(font)
        self.infoLabel_3.setFrameShape(QFrame.Box)
        self.infoLabel_3.setText("")
        self.infoLabel_3.setAlignment(Qt.AlignCenter)
        self.infoLabel_3.setObjectName("infoLabel_3")
        self.clearImgButton = QPushButton(self.centralwidget)
        self.clearImgButton.setGeometry(QRect(1550, 690, 150, 30))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.clearImgButton.setFont(font)
        self.clearImgButton.setObjectName("clearImgButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 1871, 21))
        self.menubar.setObjectName("menubar")
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionExit = QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setObjectName("actionHelp")
        self.actionAbout = QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.actionDefault_Values = QAction(MainWindow)
        self.actionDefault_Values.setObjectName("actionDefault_Values")
        self.menuHelp.addAction(self.actionHelp)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addSeparator()
        self.menuHelp.addAction(self.actionDefault_Values)
        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        self.scene.file_signal.connect(on_file_signal)
        self.scene.info_signal.connect(on_info_signal)
        self.scene.sliders_reset_signal.connect(on_sliders_reset_signal)
Exemplo n.º 30
0
    def initUI(self):

        try:
            self.setWindowState(QtCore.Qt.WindowMaximized)
        except:
            self.setGeometry(10, 30, 1350, 750)

        self.setWindowTitle('Dana')

        self.setWindowIcon(
            QIcon('download.png')
        )  # Have this png at same directory as this code is. Icon Image

        oImage = QImage(
            "download(1).jpg"
        )  # Have this png at same directory as this code is. Background Image
        sImage = oImage.scaled(QSize(1350, 750))
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))
        self.setPalette(palette)

        saveButton = QPushButton("ADD/MODIFY", self)
        deleteButton = QPushButton("DELETE", self)
        clearButton = QPushButton("CLEAR", self)
        TrainButton = QPushButton("Train DANA", self)
        saveButton.setFont(QtGui.QFont("Calibri", 13))
        deleteButton.setFont(QtGui.QFont("Calibri", 13))
        clearButton.setFont(QtGui.QFont("Calibri", 13))
        TrainButton.setFont(QtGui.QFont("Calibri", 13))
        saveButton.move(100, 690)
        clearButton.move(260, 690)
        TrainButton.move(420, 690)
        saveButton.clicked.connect(self.saveClicked)
        deleteButton.clicked.connect(self.deleteClicked)
        clearButton.clicked.connect(self.clearClicked)
        TrainButton.clicked.connect(self.TrainClicked)
        saveButton.setStyleSheet("background-color: #F7CE16")
        deleteButton.setStyleSheet("background-color: #F7CE16")
        clearButton.setStyleSheet("background-color: #F7CE16")
        TrainButton.setStyleSheet("background-color: #F7CE16")

        headerfont = QtGui.QFont("Cambria", 13, QtGui.QFont.Bold)

        l1 = QLabel("BOOK ID: ")
        l1.setFont(headerfont)
        l1.setMinimumHeight(30)
        l1.setFixedWidth(180)
        text1 = QLineEdit()
        text1.setFixedWidth(250)
        text1.setMinimumHeight(30)
        text1.setPlaceholderText("The Library Book ID ")
        text1.setFont(QtGui.QFont("Times", 11))

        l2 = QLabel("AUTHOR: ")
        l2.setFont(headerfont)
        l2.setMinimumHeight(30)
        l2.setFixedWidth(180)
        text2 = QLineEdit()
        text2.setFixedWidth(600)
        text2.setMinimumHeight(30)
        text2.setPlaceholderText(" EX: Sumitra Arora ")
        text2.setFont(QtGui.QFont("Times", 11))

        l3 = QLabel("TITLE: ")
        l3.setFont(headerfont)
        l3.setMinimumHeight(30)
        l3.setFixedWidth(180)
        text3 = QLineEdit()
        text3.setFixedWidth(600)
        text3.setMinimumHeight(30)
        text3.setPlaceholderText(" EX: Artificial Intelligence,C,C++ ")
        text3.setFont(QtGui.QFont("Times", 11))

        l4 = QLabel("PUBLICATION: ")
        l4.setFont(headerfont)
        l4.setMinimumHeight(30)
        l4.setFixedWidth(180)
        text4 = QLineEdit()
        text4.setFixedWidth(600)
        text4.setMinimumHeight(30)
        text4.setPlaceholderText(" EX: TATA MCGRAW HILL ")
        text4.setFont(QtGui.QFont("Times", 11))

        l5 = QLabel("EDITION: ")
        l5.setFont(headerfont)
        l5.setMinimumHeight(30)
        l5.setFixedWidth(180)
        text5 = QLineEdit()
        text5.setFixedWidth(250)
        text5.setMinimumHeight(30)
        text5.setPlaceholderText(" EX: 1,2,3 ")
        text5.setFont(QtGui.QFont("Times", 11))

        l6 = QLabel("ISSUE STATUS: ")
        l6.setFont(headerfont)
        l6.setMinimumHeight(30)
        l6.setFixedWidth(200)

        hboxperiod = QHBoxLayout()
        hboxperiod.setSpacing(70)
        r1 = QRadioButton("BOOK ISSUED")
        r1.setFont(QtGui.QFont("Calibri", 9, QtGui.QFont.Bold))
        r1.setMinimumHeight(30)
        r2 = QRadioButton("NOT ISSUED")
        r2.setFont(QtGui.QFont("Calibri", 9, QtGui.QFont.Bold))
        r2.setMinimumHeight(30)
        r2.setChecked(True)
        widgetperiod = QWidget(self)
        groupperiod = QButtonGroup(widgetperiod)
        groupperiod.addButton(r1)
        groupperiod.addButton(r2)
        hboxperiod.addWidget(r1)
        hboxperiod.addWidget(r2)
        hboxperiod.addStretch()

        l7 = QLabel("PRICE: ")
        l7.setFont(headerfont)
        l7.setMinimumHeight(30)
        l7.setFixedWidth(200)
        text7 = QLineEdit()
        text7.setFixedWidth(250)
        text7.setMinimumHeight(30)
        text7.setPlaceholderText("Price of the Book")
        text7.setFont(QtGui.QFont("Times", 11))

        l8 = QLabel("ROW NUMBER: ")
        l8.setFont(headerfont)
        l8.setMinimumHeight(30)
        l8.setFixedWidth(200)
        text8 = QLineEdit()
        text8.setFixedWidth(250)
        text8.setMinimumHeight(30)
        text8.setPlaceholderText("Start counting from Door")
        text8.setFont(QtGui.QFont("Times", 11))

        l9 = QLabel("COLUMN NUMBER: ")
        l9.setFont(headerfont)
        l9.setMinimumHeight(30)
        l9.setFixedWidth(200)
        text9 = QLineEdit()
        text9.setFixedWidth(250)
        text9.setMinimumHeight(30)
        text9.setPlaceholderText("Start counting from the Help Desk")
        text9.setFont(QtGui.QFont("Times", 11))

        l10 = QLabel("SHELF PARTION NUMBER: ")
        l10.setFont(headerfont)
        l10.setMinimumHeight(30)
        l10.setFixedWidth(200)
        text10 = QLineEdit()
        text10.setFixedWidth(250)
        text10.setMinimumHeight(30)
        text10.setPlaceholderText("Start counting from top of the shelf")
        text10.setFont(QtGui.QFont("Times", 11))

        l11 = QLabel("CLASSIFYING SUBJECT: ")
        l11.setFont(headerfont)
        l11.setMinimumHeight(30)
        l11.setFixedWidth(180)
        text11 = QLineEdit()
        text11.setFixedWidth(600)
        text11.setMinimumHeight(30)
        text11.setPlaceholderText(
            " EX: Mathematics/Science/Computer Science or others.")
        text11.setFont(QtGui.QFont("Times", 11))

        text12 = QLineEdit()
        text12.setFixedWidth(600)
        text12.setMinimumHeight(30)
        text12.setPlaceholderText(
            " Enter the BOOK ID and Press the Delete Button to delete the data of the book"
        )
        text12.setFont(QtGui.QFont("Times", 11))

        fbox = QFormLayout()
        fbox.setVerticalSpacing(27)
        fbox.setHorizontalSpacing(30)
        fbox.addRow(l1, text1)
        fbox.addRow(l2, text2)
        fbox.addRow(l3, text3)
        fbox.addRow(l4, text4)
        fbox.addRow(l5, text5)
        fbox.addRow(l11, text11)
        fbox.addRow(l6, hboxperiod)
        fbox.addRow(l7, text7)
        fbox.addRow(l8, text8)
        fbox.addRow(l9, text9)
        fbox.addRow(l10, text10)
        fbox.addRow(deleteButton, text12)

        self.setLayout(fbox)
        self.lineedits = [
            text1, text2, text3, text4, text5, text7, text8, text9, text10,
            text11
        ]
        self.deletelineedit = [text12]
        self.radiobutton = [r1, r2]
        self.show()