class collapsibleGroupBox2(QWidget):
    def __init__(self, parent=None, title=None):
        QWidget.__init__(self, parent)
        self.frame = QFrame(self)
        self.button = QPushButton("Toggle", self)
        self.button.setCheckable(True)
        self.button.setChecked(True)
        self.switched = False
        self.vPolicy = None

        self.button.setStyleSheet(style.collapsibleGroupBoxButton())

        if title:
            self.setTitle(title)

    def resizeEvent(self, event):
        if not self.switched:
            self.switchLayout()
        return QWidget.resizeEvent(self, event)

    def switchLayout(self):
        self.frame.setLayout(self.layout())
        self.wLayout = QVBoxLayout(self)
        self.wLayout.setContentsMargins(0, 0, 0, 0)
        self.wLayout.setSpacing(0)
        self.wLayout.addWidget(self.button)
        self.wLayout.addWidget(self.frame)
        self.button.toggled.connect(self.setExpanded)
        self.frame.layout().setContentsMargins(0, 0, 0, 4)
        self.frame.layout().setSpacing(0)
        self.switched = True

        self.vPolicy = self.sizePolicy().verticalPolicy()
        self.parent().layout().setAlignment(Qt.AlignTop)

        self.setExpanded(self.button.isChecked())

    def setFlat(self, val):
        if val:
            self.frame.setFrameShape(QFrame.NoFrame)

    def setCheckable(self, val):
        pass

    def setTitle(self, title):
        self.button.setText(title)

    def setExpanded(self, val):
        self.frame.setVisible(val)
        if val:
            self.setSizePolicy(QSizePolicy.Preferred, self.vPolicy)
        else:
            self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)

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

    def restoreState(self, val):
        self.button.setChecked(val)
Esempio n. 2
0
def main(args):
    app = QApplication([])

    main_frame = QFrame()

    layout = QVBoxLayout(main_frame)

    number_edit = PyQtExtras.NumberEdit()
    number_edit.set_value(10)
    print "Current value of 1 is: " + str(number_edit.get_value())

    number_edit2 = PyQtExtras.NumberEdit(max_length=2)
    number_edit2.set_value(2)
    print "Current value of 2 is: " + str(number_edit2.get_value())
    number_edit2.set_value(20)
    print "Current value of 2 is: " + str(number_edit2.get_value())

    number_edit3 = PyQtExtras.NumberEdit(max_length=1)
    number_edit3.set_value(2)
    print "Current value of 3 is: " + str(number_edit3.get_value())
    number_edit3.set_value(50)
    print "Current values of 3 is: " + str(number_edit3.get_value())
    number_edit3.set_value(25)
    print "Current value of 3 is: " + str(number_edit3.get_value())
    number_edit3.set_value("text")
    print "Current value of 3 is: " + str(number_edit3.get_value())

    layout.addWidget(number_edit)
    layout.addWidget(number_edit2)
    layout.addWidget(number_edit3)

    main_frame.show()

    app.exec_()
Esempio n. 3
0
 def mousePressEvent(self, event):
     if event.button() == Qt.LeftButton:
         self.fMouseDown = True
         self.setCursor(QCursor(Qt.SizeAllCursor))
         self.handleMouseEvent(event.x(), event.y())
         return event.accept()
     QFrame.mouseMoveEvent(self, event)
Esempio n. 4
0
    def __init__(self, N=1, parent=None):
        super(Controller, self).__init__(parent)

        import interface

        pumpBackends = interface.initPumps("COM3", N)
        pumps = [Pump(i) for i in pumpBackends]

        timer = QTimer(self)
        for pump in pumps:
            timer.timeout.connect(pump.update_status)

        timer.start(1000)

        divider = QFrame()
        divider.setFrameShape(QFrame.VLine)

        mainLayout = QHBoxLayout()
        mainLayout.addWidget(pumps[0])
        for pump in pumps[1:]:
            mainLayout.addWidget(divider)
            mainLayout.addWidget(pump)

        self.setLayout(mainLayout)
        self.setWindowTitle("Syringe Pump Controller")
Esempio n. 5
0
    def paintEvent(self, event):
        painter = QPainter(self)

        if self.fUseCustomPaint:
            painter.setBrush(QColor(36, 36, 36))
            painter.setPen(QColor(62, 62, 62))
            painter.drawRect(2, 2, self.width()-4, self.height()-4)

            painter.setBrush(self.fViewBg)
            painter.setPen(self.fViewBg)
            painter.drawRect(3, 3, self.width()-6, self.height()-6)
        else:
            painter.setBrush(self.fViewBg)
            painter.setPen(self.fViewBg)
            painter.drawRoundedRect(3, 3, self.width()-6, self.height()-6, 3, 3)

        self.fScene.render(painter, self.fRenderTarget, self.fRenderSource, Qt.KeepAspectRatio)

        width  = self.fViewRect[iWidth]/self.fScale
        height = self.fViewRect[iHeight]/self.fScale

        if width > self.kInternalWidth:
            width = self.kInternalWidth
        if height > self.kInternalHeight:
            height = self.kInternalHeight

        # cursor
        painter.setBrush(self.fViewBrush)
        painter.setPen(self.fViewPen)
        painter.drawRect(self.fViewRect[iX]+self.fInitialX, self.fViewRect[iY]+3, width, height)

        if self.fUseCustomPaint:
            event.accept()
        else:
            QFrame.paintEvent(self, event)
    def __init__(self, *args):
        # Invoke parent init
        QFrame.__init__(self, *args)
        self.item_id = None
        self.item_type = None

        # Get translation object
        _ = get_app()._tr

        # Widgets
        self.lblSelection = QLabel()
        self.lblSelection.setText("<strong>%s</strong>" % _("No Selection"))
        self.btnSelectionName = QPushButton()
        self.btnSelectionName.setVisible(False)
        self.btnSelectionName.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)

        # Support rich text
        self.lblSelection.setTextFormat(Qt.RichText)

        hbox = QHBoxLayout()
        hbox.setContentsMargins(0,0,0,0)
        hbox.addWidget(self.lblSelection)
        hbox.addWidget(self.btnSelectionName)
        self.setLayout(hbox)

        # Connect signals
        get_app().window.propertyTableView.loadProperties.connect(self.select_item)
Esempio n. 7
0
    def mousePressEvent(self, event):
        QFrame.mousePressEvent(self, event)

        video = self.backend.fillobj(self.video)
        if video:
            video_widget = Video(video, self)
            video_widget.show()
Esempio n. 8
0
    def __init__(self, parent=None, update_func=None, params=None):
        super().__init__(parent)

        self.setMaximumWidth(200)

        self.params = params

        self.H1_HEIGHT = 50
        self.H2_HEIGHT = 50
        self.SIDE_MARGIN = 5
        self.H1_FONT_SIZE = 18
        self.H2_FONT_SIZE = 18
        self.H3_FONT_SIZE = 16
        self.TEXT_FONT_SIZE = 14

        style = '''
            QPushButton:flat{
                text-align: left;
                padding: 1ex;
            }
            QPushButton:pressed{
                background-color: silver;
            }
            QPushButton:hover:!pressed{
                font: bold;
            }
            '''
        self.setStyleSheet(style)

        self.update_func = update_func

        self.inner = QWidget(self)

        self.vbox = QVBoxLayout(self.inner)
        self.vbox.setSpacing(0)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        self.vbox.setAlignment(Qt.AlignTop)

        topframe = QFrame()
        topframe.setStyleSheet('background-color: white')
        topframe.setFixedHeight(self.H1_HEIGHT)

        lbl_h1 = QLabel('Contents', topframe)
        fnt = lbl_h1.font()
        fnt.setPointSize(self.H1_FONT_SIZE)
        lbl_h1.setFont(fnt)
        lbl_h1.setFixedHeight(self.H1_HEIGHT)
        lbl_h1.setMargin(self.SIDE_MARGIN)

        self.vbox.addWidget(topframe)

        self.list_button = []
        if self.params.lang == 'en':
            self.edit_button('Introduction')
        else:
            self.edit_button('はじめに')

        self.inner.setLayout(self.vbox)

        self.setWidget(self.inner)
 def __init__(self):
     super().__init__()
     vbox = QVBoxLayout(self)
     self.setTitle("Python Project")
     frame = QFrame()
     frame.setLineWidth(2)
     vbox.addStretch(1)
     frame.setFrameShape(QFrame.StyledPanel)
     vbox.addWidget(frame)
     box = QGridLayout(frame)
     box.addWidget(QLabel("Project Name:"), 0, 0)
     self._line_project_name = QLineEdit()
     self.registerField("name*", self._line_project_name)
     box.addWidget(self._line_project_name, 0, 1)
     box.addWidget(QLabel("Create in:"), 1, 0)
     self.line = QLineEdit()
     self.registerField("path", self.line)
     choose_dir_action = self.line.addAction(
         QIcon(self.style().standardPixmap(
             self.style().SP_DirIcon)), QLineEdit.TrailingPosition)
     box.addWidget(self.line, 1, 1)
     box.addWidget(QLabel("Interpreter:"), 2, 0)
     line_interpreter = QComboBox()
     line_interpreter.setEditable(True)
     line_interpreter.addItems(utils.get_python())
     box.addWidget(line_interpreter, 2, 1)
     # from ninja_ide.utils import utils
     choose_dir_action.triggered.connect(self._choose_dir)
     self.line.setText(utils.get_home_dir())
Esempio n. 10
0
    def create_video(self):
        """Create video widget."""

        self.instance = vlc.Instance()

        video_widget = QFrame()
        self.mediaplayer = self.instance.media_player_new()
        if system() == 'Linux':
            self.mediaplayer.set_xwindow(video_widget.winId())
        elif system() == 'Windows':
            self.mediaplayer.set_hwnd(video_widget.winId())
        elif system() == 'darwin':  # to test
            self.mediaplayer.set_nsobject(video_widget.winId())
        else:
            lg.warning('unsupported system for video widget')
            return

        self.medialistplayer = vlc.MediaListPlayer()
        self.medialistplayer.set_media_player(self.mediaplayer)
        event_manager = self.medialistplayer.event_manager()
        event_manager.event_attach(vlc.EventType.MediaListPlayerNextItemSet,
                                   self.next_video)

        self.idx_button = QPushButton()
        self.idx_button.setText('Start')
        self.idx_button.clicked.connect(self.start_stop_video)

        layout = QVBoxLayout()
        layout.addWidget(video_widget)
        layout.addWidget(self.idx_button)
        self.setLayout(layout)
Esempio n. 11
0
 def __init__(self, parent=None):
     QFrame.__init__(self, parent)
     self.ui = Ui_frame_tab_queue()
     self.ui.setupUi(self)
     self.screen = parent
     self.listener = Listener(self.screen, self)
     self.connectSignals()
Esempio n. 12
0
    def createUI(self):
        """Set up the user interface, signals & slots
        """
        self.widget = QWidget(self)
        self.setCentralWidget(self.widget)

        # In this widget, the video will be drawn
        if sys.platform == "darwin": # for MacOS
            from PyQt5.QtWidgets import QMacCocoaViewContainer	
            self.videoframe = QMacCocoaViewContainer(0)
        else:
            self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor (QPalette.Window,
                               QColor(0,0,0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)
        self.playbutton.clicked.connect(self.PlayPause)

        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

        self.widget.setLayout(self.vboxlayout)

        open = QAction("&Open", self)
        open.triggered.connect(self.OpenFile)
        exit = QAction("&Exit", self)
        exit.triggered.connect(sys.exit)
        menubar = self.menuBar()
        filemenu = menubar.addMenu("&File")
        filemenu.addAction(open)
        filemenu.addSeparator()
        filemenu.addAction(exit)

        self.timer = QTimer(self)
        self.timer.setInterval(200)
        self.timer.timeout.connect(self.updateUI)
Esempio n. 13
0
    def class_selected(self):
        # the .ui is set to 1 selection
        for index in self.classes.selectionModel().selectedIndexes():
            class_name = self.class_model.data(index, Qt.DisplayRole)

        self.log.debug("Setting class to {0}".format(class_name))

        self.enable_all.setToolTip("Include all permissions in the {0} class.".format(class_name))
        self.disable_all.setToolTip("Exclude all permissions in the {0} class.".format(class_name))

        self._clear_mappings()

        # populate new mappings
        for perm in sorted(self.perm_map.perms(class_name)):
            # create permission mapping
            mapping = PermissionMapping(self, perm, self.edit)
            mapping.setAttribute(Qt.WA_DeleteOnClose)
            self.class_toggle.connect(mapping.enabled.setChecked)
            self.perm_mappings.addWidget(mapping)
            self.widgets.append(mapping)

            # add horizonal line
            line = QFrame(self)
            line.setFrameShape(QFrame.HLine)
            line.setFrameShadow(QFrame.Sunken)
            self.perm_mappings.addWidget(line)
            self.widgets.append(line)
Esempio n. 14
0
    def finalise(self):     # cette fonction est a appeler une fois tout le contenu ajoute.
        line = QFrame(self)#, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
        line.setFrameStyle(QFrame.HLine)
        self.sizer.addWidget(line)

        self.box = QHBoxLayout()

        ##if wx.Platform != "__WXMSW__":
            ##btn = wx.ContextHelpButton(self)
            ##self.box.Add(btn)

        btn = QPushButton(" Créer " if self.objet else "Enregistrer", clicked=self.accept)
        btn.setWhatsThis("Créer l'objet." if self.objet else "Enregistrer les modifications.")
        ##btn.SetDefault()
        #XXX: Action à ajouter !!
        self.box.addWidget(btn)

        btn = QPushButton("Annuler", clicked=self.close)
        btn.setWhatsThis("Quitter sans rien changer.")
        self.box.addWidget(btn)

        self.sizer.addLayout(self.box)

        self.setLayout(self.sizer)
        if self.objet:
            self.champs['nom'].setFocus()
Esempio n. 15
0
    def __init__(self, parent, closeButton=True):
        QFrame.__init__(self, parent)
        self.setMaximumSize(QSize(9999999,22))
        self.setObjectName("windowTitle")
        self.hboxlayout = QHBoxLayout(self)
        self.hboxlayout.setSpacing(0)
        self.hboxlayout.setContentsMargins(0,0,4,0)

        self.label = QLabel(self)
        self.label.setObjectName("label")
        self.label.setStyleSheet("padding-left:4px; font:bold 11px; color: #FFFFFF;")

        self.hboxlayout.addWidget(self.label)

        spacerItem = QSpacerItem(40,20,QSizePolicy.Expanding,QSizePolicy.Minimum)
        self.hboxlayout.addItem(spacerItem)

        if closeButton:
            self.pushButton = QPushButton(self)
            self.pushButton.setFocusPolicy(Qt.NoFocus)
            self.pushButton.setObjectName("pushButton")
            self.pushButton.setStyleSheet("font:bold;")
            self.pushButton.setText("X")

            self.hboxlayout.addWidget(self.pushButton)

        self.dragPosition = None
        self.mainwidget = self.parent()
        self.setStyleSheet("""
            QFrame#windowTitle {background-color:#222222;color:#FFF;}
        """)

        # Initial position to top left
        self.dragPosition = self.mainwidget.frameGeometry().topLeft()
 def __init__(self, photoBaseDir, validPhotoFileExts, picChangeMs, parent=None):
     QFrame.__init__(self, parent)
     self.setStyleSheet("QTabWidget::pane { border: 0; }; background-color: 'black';")
     self.setLineWidth(0)
     self.setFrameShape(QtWidgets.QFrame.NoFrame)
     # self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
     # Vars
     self.picChangeMs = picChangeMs
     self.photoBaseDir = photoBaseDir
     # # Widget
     # self.scene = QGraphicsScene()
     # self.setScene(self.scene)
     # self.setBackgroundBrush(QColor("black"))
     # self.setLineWidth(0)
     # self.setFrameShape(QtWidgets.QFrame.NoFrame)
     # Layout
     # layout = QVBoxLayout()
     # lbl = QTextEdit()
     # lbl.setReadOnly(True)
     # lbl.setLineWidth(0)
     # lbl.setFrameShape(QtWidgets.QFrame.NoFrame)
     # lbl.setStyleSheet('font: 30pt "Segoe UI"; color:"white"; background-color:"black"; QTabWidget::pane { border: 0; }')
     # lbl.setHtml("Hello")
     # layout.addWidget(lbl)
     # self.setLayout(layout)
     # Class vars
     self.picChgTimer = None
     self.photoFileManager = PhotoFileManager(validPhotoFileExts, self.photoBaseDir, 7200.00)
     self.photoFileManager.startPhotoListUpdate()
Esempio n. 17
0
    def resizeEvent(self, event):
        self.fRenderSource = self.getRenderSource()

        if self.fRealParent is not None:
            QTimer.singleShot(0, self.fRealParent.slot_miniCanvasCheckAll)

        QFrame.resizeEvent(self, event)
Esempio n. 18
0
    def mousePressEvent(self, event):
        QFrame.mousePressEvent(self, event)

        if event.button() == 4:
            self.newTabPressed()
        else:
            self.viewPressed()
Esempio n. 19
0
    def __init__(self):
        super().__init__()
        self.setTitle(translations.TR_WIZARD_PYQT_PROJECT_TITLE_SECOND_PAGE)
        self.setSubTitle(
            translations.TR_WIZARD_PYQT_PROJECT_SUBTITLE_SECOND_PAGE)
        vbox = QVBoxLayout(self)
        frame = QFrame(self)
        frame.setFrameShape(QFrame.StyledPanel)
        vbox.addWidget(frame)
        # Fields
        fields_box = QGridLayout(frame)
        fields_box.addWidget(
            QLabel(translations.TR_WIZARD_PYQT_CLASS_NAME), 0, 0)
        self._line_class_name = QLineEdit()
        self.registerField("class_name*", self._line_class_name)
        fields_box.addWidget(self._line_class_name, 0, 1)

        fields_box.addWidget(
            QLabel(translations.TR_WIZARD_PYQT_BASE_CLASS), 1, 0)
        self._combo_class_name = QComboBox()
        self._combo_class_name.addItems(["QWidget", "QMainWindow", "QDialog"])
        self.registerField(
            "base_class", self._combo_class_name, property="currentText")
        fields_box.addWidget(self._combo_class_name, 1, 1)

        fields_box.addWidget(
            QLabel(translations.TR_WIZARD_PYQT_WIDGET_FILE), 2, 0)
        self._line_widget_file = QLineEdit()
        self._line_widget_file.setReadOnly(True)
        fields_box.addWidget(self._line_widget_file, 2, 1)
        self._combo_class_name.currentTextChanged.connect(
            self.__update_line_widget)
        self.__update_line_widget(self._combo_class_name.currentText())
Esempio n. 20
0
    def resizeEvent(self, event):
        self.fInitialX     = float(self.width())/2.0 - float(self.kInternalWidth)/2.0
        self.fRenderTarget = QRectF(self.fInitialX, 3.0, float(self.kInternalWidth), float(self.kInternalHeight))

        if self.fRealParent is not None:
            QTimer.singleShot(0, self.fRealParent.slot_miniCanvasCheckAll)

        QFrame.resizeEvent(self, event)
Esempio n. 21
0
 def __init__(self, text='Year:', min_year=1950, max_year=2100, **kwargs):
     QFrame.__init__(self)
     self.main_layout = QHBoxLayout(self)
     self.label = QLabel(text)
     self.year_selector = QSpinBox()
     self.year_selector.setRange(min_year, max_year)
     self.main_layout.addWidget(self.label)
     self.main_layout.addWidget(self.year_selector)
Esempio n. 22
0
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)

        self.original_parent = parent
        self.palette = self.palette()
        self.palette.setColor(QPalette.Window, QColor(0,0,0))

        self.setPalette(self.palette)
        self.setAutoFillBackground(True)
Esempio n. 23
0
    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        self.setToolTip('This is a <b>QWidget</b> widget.')
        #quitBtn = QPushButton('Quit', self)
        #quitBtn.clicked.connect(self.quitBtnEvent())
        #quitBtn.clicked.connect(QCoreApplication.instance().quit)
        #quitBtn.setToolTip('This is a <b>QPushButton</b> widget.')
        #quitBtn.resize(quitBtn.sizeHint())

        exitAction = QAction(QIcon('application-exit-4.png'), '&Exit', self)
        exitAction.setShortcut('Alt+F4')
        exitAction.setStatusTip('Exit Application')
        exitAction.triggered.connect(qApp.quit)

        menuBar = QMenuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.resize(fileMenu.sizeHint())

        toolBar = QToolBar(self)
        toolBar.addAction(exitAction)
        #toolBar.resize(toolBar.sizeHint())
        toolBar.setFixedHeight(60)

        hozLine = QFrame()
        hozLine.setFrameStyle(QFrame.HLine)
        #hozLine.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding)

        statusBar = QStatusBar(self)
        statusBar.showMessage('Ready')

        grid = QGridLayout()
        lbl_1 = QLabel('1,1')
        lbl_2 = QLabel('1,2')
        lbl_3 = QLabel('2,1')
        lbl_4 = QLabel('2,2')
        grid.addWidget(lbl_1, 1, 1)
        grid.addWidget(lbl_2, 1, 2)
        grid.addWidget(lbl_3, 2, 1)
        grid.addWidget(lbl_4, 2, 2)

        vbox = QVBoxLayout()
        vbox.addWidget(menuBar)
        vbox.addWidget(hozLine)
        vbox.addWidget(toolBar)
        # vbox.addWidget(hozLine)
        vbox.addLayout(grid)
        vbox.addStretch(1)
        vbox.addWidget(statusBar)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 500, 500)
        self.setWindowTitle('Photos')
        self.setWindowIcon(QIcon('camera-photo-5.png'))
        self.center()
        self.show()
Esempio n. 24
0
 def timerEvent(self, event):
     if event.timerId() == self.timer.timerId():
         if self.isWaitingAfterLine:
             self.isWaitingAfterLine = False
             self.newPiece()
         else:
             self.oneLineDown()
     else:
         QFrame.timerEvent(self, event)
Esempio n. 25
0
    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self._buttons = []
        frame = QFrame()
        frame.setObjectName("actionbar")
        box = QVBoxLayout(frame)
        box.setContentsMargins(1, 1, 1, 1)
        box.setSpacing(0)

        self._combo_project = QComboBox()
        self._combo_project.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Fixed)
        self._combo_project.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self._combo_project.setObjectName("combo_projects")
        box.addWidget(self._combo_project)
        vbox.addWidget(frame)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        vbox.addLayout(self._projects_area)

        # Empty widget
        self._empty_proj = QLabel(translations.TR_NO_PROJECTS)
        self._empty_proj.setAlignment(Qt.AlignCenter)
        self._empty_proj.setAutoFillBackground(True)
        self._empty_proj.setBackgroundRole(QPalette.Base)
        self._projects_area.addWidget(self._empty_proj)
        self._projects_area.setCurrentWidget(self._empty_proj)

        self.projects = []

        self._combo_project.activated.connect(
            self._change_current_project)
        self._combo_project.customContextMenuRequested[
            'const QPoint&'].connect(self.context_menu_for_root)

        connections = (
            {
                "target": "main_container",
                "signal_name": "addToProject",
                "slot": self._add_file_to_project
            },
            {
                "target": "main_container",
                "signal_name": "showFileInExplorer",
                "slot": self._show_file_in_explorer
            },
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)
Esempio n. 26
0
    def __init__(self, text):
        QFrame.__init__(self, text)

        self.grid_scroll_area = PyQtExtras.GridScrollArea(self)

        self.text = text

        self.child_set = dict()

        self.setAcceptDrops(True)
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        self.ui = Ui_frame_tab_video()
        self.ui.setupUi(self)
        self.screen = parent
        self.listener = Listener(parent, self)
        self.connectSignals()

        interface.tab_video.fillElementsFromConfig(self,
                                                   self.screen.config)
Esempio n. 28
0
    def initUI(self):      

        hbox = QHBoxLayout(self)

        topleft = QFrame(self)
        topleft.setFrameShape(QFrame.StyledPanel)
 
        topright = QFrame(self)
        topright.setFrameShape(QFrame.StyledPanel)

        bottom = QFrame(self)
        bottom.setFrameShape(QFrame.StyledPanel)

        splitter1 = QSplitter(Qt.Horizontal)
        splitter1.addWidget(topleft)
        splitter1.addWidget(topright)

        splitter2 = QSplitter(Qt.Vertical)
        splitter2.addWidget(splitter1)
        splitter2.addWidget(bottom)

        hbox.addWidget(splitter2)
        self.setLayout(hbox)
        
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QSplitter')
        self.show()
Esempio n. 29
0
    def initUI(self, haveAuto):

        vbox = QVBoxLayout(self)

        top = QFrame(self)
        top.setFrameShape(QFrame.StyledPanel)

        bottom = QFrame(self)
        bottom.setFrameShape(QFrame.StyledPanel)

        grid1 = QGridLayout()
        grid1.setSpacing(10)
        self.lineLabel = []
        self.lineEdit = []

        for i in range(len(self.label)):
            self.lineLabel.append(QLabel(self.label[i]))
            self.lineEdit.append(QLineEdit('%s' % self.value[i]))

            grid1.addWidget(self.lineLabel[i], i, 0)
            grid1.addWidget(self.lineEdit[i], i, 1)

        top.setLayout(grid1)

        grid2 = QGridLayout()
        grid2.setSpacing(5)

        autoButton = QPushButton(self.tr("Auto"))
        okButton = QPushButton(self.tr("OK"))
        cancelButton = QPushButton(self.tr("Cancel"))

        autoButton.clicked.connect(self.cbAuto)
        okButton.clicked.connect(self.cbOK)
        cancelButton.clicked.connect(self.cbCancel)

        if haveAuto:
            grid2.addWidget(autoButton, 0, 0)
        grid2.addWidget(okButton, 0, 1)
        grid2.addWidget(cancelButton, 0, 2)

        bottom.setLayout(grid2)

        vbox.addWidget(top)
        vbox.addWidget(bottom)

        self.setLayout(vbox)

        self.resize(50, 50)
        self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
        self.setWindowTitle(self.title)
        iconWT = QIcon()
        iconWT.addPixmap(QPixmap(":images/DXF2GCODE-001.ico"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(QIcon(iconWT))

        self.exec_()
Esempio n. 30
0
    def define_section2(self):
        """defining section 2: Specify allele details
        """
        mywidget = QWidget(self)
        layout = QGridLayout()
        mywidget.setLayout(layout)
        
        a1_new = False
        self.allele1_sec = AlleleSection("Allele 1:", self)
        layout.addWidget(self.allele1_sec,0,0)
        
        a2_new = False
        self.allele2_sec = AlleleSection("Allele 2:", self)
        layout.addWidget(self.allele2_sec,0,1)
        
        #ToDo: add closest alleles!
        
        button_widget = QFrame(self) # contains both-checkbox & proceed-button
        layout2 = QFormLayout()
        button_widget.setLayout(layout2)
#         self.both_cbx = QCheckBox(self)
#         self.both_cbx.clicked.connect(self.select_both)
#         self.both_lbl = QLabel("Both alleles?")
#         self.both_lbl.setStyleSheet(general.label_style_main)
#         layout2.addRow(self.both_lbl, self.both_cbx)
#         self.msg = QLabel("When selecting this option, please ensure\nyou have entered details for both alleles.")
#         self.msg.setStyleSheet(general.label_style_normal)
#         layout2.addRow(self.msg)
        layout2.addRow(QLabel("\n\n"))
        
        if a1_new:
            self.allele1_sec.checkbox.setChecked(True)
            if a2_new:
                self.allele2_sec.checkbox.setChecked(True)
        elif a2_new:
            self.allele2_sec.checkbox.setChecked(True)
#         self.allele1_sec.checkbox.clicked.connect(self.unselect_both_cbx)
        self.allele1_sec.checkbox.clicked.connect(self.unselect_other_box)
        self.allele2_sec.checkbox.clicked.connect(self.unselect_other_box)
#         self.allele2_sec.checkbox.clicked.connect(self.unselect_both_cbx)
        
        self.ok_btn = ProceedButton("Proceed", [self.allele1_sec.checkbox, self.allele2_sec.checkbox], self.log,
                                    only1 = True)
        self.ok_btn.check_ready()
        self.ok_btn.clicked.connect(self.make_ENA_file)
        self.allele1_sec.selection_changed.connect(self.ok_btn.check_ready)
        self.allele2_sec.selection_changed.connect(self.ok_btn.check_ready)
        
        layout2.addRow(self.ok_btn)
        layout.addWidget(button_widget, 0 ,3)
        layout.setColumnStretch(0,1)
        layout.setColumnStretch(1,1)
        layout.setColumnStretch(2,0)
        self.sections.append(("(2) Specify allele details:", mywidget))
Esempio n. 31
0
    def __init__(self):
        self.app = QApplication([])
        self.window = QMainWindow()
        self.window.setFixedSize(self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
        self.window.setWindowTitle('Dragon Quest III: Heavenly Flight')
        self.icon = QtGui.QIcon()
        self.icon.addPixmap(
            QtGui.QPixmap(os.path.join(THIS_FILEPATH, "ico.ico")),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.window.setWindowIcon(self.icon)

        self.title_container = QLabel(self.window)
        self.title_container.setGeometry(
            QtCore.QRect(0, 0, self.SCREEN_WIDTH, 30))
        self.title_container.setStyleSheet("background-color:black;")

        self.title_label = QLabel("Dragon Quest III: Heavenly Flight",
                                  self.window)
        self.title_label.setGeometry(QtCore.QRect(0, 0, self.SCREEN_WIDTH, 30))
        self.title_label.setAlignment(QtCore.Qt.AlignCenter)
        self.title_label.setStyleSheet("font-size:18px;")

        self.title_label_border = QFrame(self.window)
        self.title_label_border.setGeometry(
            QtCore.QRect(-10, -10, self.SCREEN_WIDTH + 20, 40))
        self.title_label_border.setStyleSheet(
            "border:2px solid rgb(0, 0, 0); ")

        self.rom_label = QLabel("Input ROM path:", self.window)
        self.rom_label.setGeometry(QtCore.QRect(10, 40, 120, 30))
        self.rom_label.setToolTip('Choose ROM path:')

        self.rom_label_input = QLineEdit("", self.window)
        self.rom_label_input.setGeometry(QtCore.QRect(140, 40, 360, 30))
        self.rom_label_input.setToolTip('Choose ROM path:')
        self.rom_label_input.setText("")

        self.rom_button = QPushButton("Browse", self.window)
        self.rom_button.setGeometry(QtCore.QRect(510, 40, 80, 30))
        self.rom_button.clicked.connect(self.rom_input_click)

        self.seed_label = QLabel("Seed:", self.window)
        self.seed_label.setGeometry(QtCore.QRect(10, 80, 120, 30))
        self.seed_label.setToolTip(
            'Choose a seed number. Blank will generate a new random one.')

        self.seed_label_input = QLineEdit("", self.window)
        self.seed_label_input.setGeometry(QtCore.QRect(140, 80, 360, 30))
        self.seed_label_input.setToolTip(
            'Choose a seed number. Blank will generate a new random one.')
        self.seed_label_input.setText("")
        self.onlyInt = QIntValidator()
        self.seed_label_input.setValidator(self.onlyInt)

        self.key_item_chests_checkbox = QCheckBox(
            "Place Key Items in chests only", self.window)
        self.key_item_chests_checkbox.setGeometry(
            QtCore.QRect(10, 120, 350, 30))
        self.key_item_chests_checkbox.setToolTip(
            'Checked: Key Items will only be placed in chests. Searchable locations (visible and invisible) and NPC events will not have keys.\nUnchecked: Key Items can be placed anywhere.\nBoth options adhere to having all checks with logical requirements.\nTiering has no impact on Key Item placement.'
        )
        self.key_item_chests_checkbox.setChecked(True)

        self.reward_tiering_checkbox = QCheckBox("Reward tiering", self.window)
        self.reward_tiering_checkbox.setGeometry(QtCore.QRect(
            10, 150, 350, 30))
        self.reward_tiering_checkbox.setToolTip(
            'Checked: Rewards are placed with collectibles of increasing value throughout the game, with a small chance of higher tier goods randomly appearing anywhere.\nUnchecked: All rewards have completely random value goods.\nBoth options adhere to a placement average system, controlling how often items appear throughout the seed.\nRewards can be placed with higher or lower tiers than the check tier by design, but are usually +/- 1 with tiering.'
        )
        self.reward_tiering_checkbox.setChecked(True)

        self.shop_tiering_checkbox = QCheckBox("Shop tiering", self.window)
        self.shop_tiering_checkbox.setGeometry(QtCore.QRect(10, 180, 350, 30))
        self.shop_tiering_checkbox.setToolTip(
            'Checked: Shops are placed with wares of increasing value throughout the game.\nUnchecked: All shops have randomly assigned wares of any value.\nBoth options do not adhere to a placement average system, where different shops may have similar items.\nWares can be placed with higher or lower tiers than the shop tier by design, but are usually +/- 1 with tiering.'
        )
        self.shop_tiering_checkbox.setChecked(True)

        self.shop_tiering_checkbox = QCheckBox("Shop tiering", self.window)
        self.shop_tiering_checkbox.setGeometry(QtCore.QRect(10, 180, 350, 30))
        self.shop_tiering_checkbox.setToolTip(
            'Checked: Shops are placed with wares of increasing value throughout the game.\nUnchecked: All shops have randomly assigned wares of any value.\nBoth options do not adhere to a placement average system, where different shops may have similar items.\nWares can be placed with higher or lower tiers than the shop tier by design, but are usually +/- 1 with tiering.'
        )
        self.shop_tiering_checkbox.setChecked(True)

        self.starting_locations_label = QLabel("Starting locations:",
                                               self.window)
        self.starting_locations_label.setGeometry(
            QtCore.QRect(389, 160, 200, 30))
        self.starting_locations_label.setToolTip(
            '1: Player starts in Aliahan.\n2-3: Player starts in Aliahan and is given an extra 1-2 random warp locations.'
        )

        self.starting_locations_combobox = QComboBox(self.window)
        self.starting_locations_combobox.setGeometry(
            QtCore.QRect(540, 160, 40, 30))
        self.starting_locations_combobox.setToolTip(
            '1: Player starts in Aliahan.\n2-3: Player starts in Aliahan and is given an extra 1-2 random warp locations.'
        )
        self.starting_locations_combobox.addItem("1")
        self.starting_locations_combobox.addItem("2")
        self.starting_locations_combobox.addItem("3")

        self.exp_multiplier_label = QLabel("EXP multiplier:", self.window)
        self.exp_multiplier_label.setGeometry(QtCore.QRect(413, 200, 200, 30))
        self.exp_multiplier_label.setToolTip('EXP multiplier settings.')

        self.exp_multiplier_combobox = QComboBox(self.window)
        self.exp_multiplier_combobox.setGeometry(QtCore.QRect(
            540, 200, 40, 30))
        self.exp_multiplier_combobox.setToolTip('EXP multiplier settings.')
        self.exp_multiplier_combobox.addItem("4")
        self.exp_multiplier_combobox.addItem("2")
        self.exp_multiplier_combobox.addItem("1")

        self.small_medal_count_label = QLabel("Small Medal count:",
                                              self.window)
        self.small_medal_count_label.setGeometry(
            QtCore.QRect(380, 120, 200, 30))
        self.small_medal_count_label.setToolTip(
            'Number of Small Medals to place in the world. Only 12 Small Medals are required for all rewards.\nMinimum amount is 0, and maximum amount is 50.'
        )

        self.small_medal_count_input = QLineEdit("15", self.window)
        self.small_medal_count_input.setGeometry(QtCore.QRect(
            540, 120, 40, 30))
        self.small_medal_count_input.setValidator(self.onlyInt)
        self.small_medal_count_input.setToolTip(
            'Number of Small Medals to place in the world. Only 12 Small Medals are required for all rewards.\nMinimum amount is 0, and maximum amount is 50.'
        )

        self.generate_button = QPushButton("Generate", self.window)
        self.generate_button.setGeometry(QtCore.QRect(10, 240, 580, 30))
        self.generate_button.clicked.connect(self.generate)

        self.log_header_label = QLabel("Console log:", self.window)
        self.log_header_label.setGeometry(QtCore.QRect(10, 280, 90, 30))

        self.log_output = QTextEdit(self.window)
        self.log_output.setGeometry(QtCore.QRect(10, 320, 580, 200))
        # self.log_output = self.set_white(self.log_output)
        self.log_output.verticalScrollBar().setValue(
            self.log_output.verticalScrollBar().minimum())

        self.log_output_thread = LogThread(self.window)
        self.log_output_thread.log.connect(self.update_log_text)
        # self.log_output_thread.started.connect(lambda: self.update_log('start'))

        self.log_clear_button = QPushButton("Clear Log", self.window)
        self.log_clear_button.setGeometry(QtCore.QRect(10, 540, 100, 30))
        self.log_clear_button.clicked.connect(self.clear_log)

        self.open_dir_button = QPushButton("Open Output Folder", self.window)
        self.open_dir_button.setGeometry(QtCore.QRect(120, 540, 180, 30))
        self.open_dir_button.clicked.connect(self.open_output_folder)

        self.github_label = QLabel("Link to GitHub", self.window)
        urlLink = "<a href=\'https://github.com/cleartonic/dq3hf'style=\"color: #13bbba;\"><b>Link to GitHub</b></a>"
        self.github_label.setText(urlLink)
        self.github_label.setGeometry(QtCore.QRect(465, 530, 180, 30))
        self.github_label.setAlignment(QtCore.Qt.AlignBottom)
        self.github_label.setAlignment(QtCore.Qt.AlignLeft)
        self.github_label.setOpenExternalLinks(True)
        self.github_label.setStyleSheet("font-size:18px")

        self.tw_label = QLabel("Link to GitHub", self.window)
        urlLink = "<a href=\'https://twitter.com/cleartonic'style=\"color: #665ae8;\"><b>@cleartonic</b></a>"
        self.tw_label.setText(urlLink)
        self.tw_label.setGeometry(QtCore.QRect(487, 560, 180, 30))
        self.tw_label.setAlignment(QtCore.Qt.AlignBottom)
        self.tw_label.setAlignment(QtCore.Qt.AlignLeft)
        self.tw_label.setOpenExternalLinks(True)
        self.tw_label.setStyleSheet("font-size:18px;")

        # Final settings
        self.app.setStyle('Fusion')
        self.app.setFont(QtGui.QFont("Segoe UI", 12))

        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(53, 53, 53))
        palette.setColor(QPalette.WindowText, QColor(255, 255, 255))
        palette.setColor(QPalette.Base, QColor(25, 25, 25))
        palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
        palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 255))
        palette.setColor(QPalette.ToolTipText, QColor(255, 255, 255))
        palette.setColor(QPalette.Text, QColor(255, 255, 255))
        palette.setColor(QPalette.Button, QColor(53, 53, 53))
        palette.setColor(QPalette.ButtonText, QColor(255, 255, 255))
        palette.setColor(QPalette.BrightText, QColor(120, 120, 0))
        palette.setColor(QPalette.Link, QColor(42, 130, 218))
        palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        palette.setColor(QPalette.HighlightedText, QColor(0, 0, 0))
        self.app.setPalette(palette)
Esempio n. 32
0
    def __init__(self, *args):
        super().__init__(BrickletThermocouple, *args)

        self.thermo = self.device

        self.qtcb_error_state.connect(self.cb_error_state)
        self.thermo.register_callback(self.thermo.CALLBACK_ERROR_STATE,
                                      self.qtcb_error_state.emit)

        self.cbe_temperature = CallbackEmulator(self,
                                                self.thermo.get_temperature,
                                                None, self.cb_temperature,
                                                self.increase_error_count)

        self.current_temperature = CurveValueWrapper()  # float, °C

        self.error_label = QLabel('Current Errors: None')
        self.error_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        plots = [('Temperature', Qt.red, self.current_temperature,
                  '{:.2f} °C'.format)]
        self.plot_widget = PlotWidget('Temperature [°C]',
                                      plots,
                                      extra_key_widgets=[self.error_label],
                                      y_resolution=0.01)

        self.averaging_label = QLabel('Averaging:')
        self.averaging_combo = QComboBox()
        self.averaging_combo.addItem('1', BrickletThermocouple.AVERAGING_1)
        self.averaging_combo.addItem('2', BrickletThermocouple.AVERAGING_2)
        self.averaging_combo.addItem('4', BrickletThermocouple.AVERAGING_4)
        self.averaging_combo.addItem('8', BrickletThermocouple.AVERAGING_8)
        self.averaging_combo.addItem('16', BrickletThermocouple.AVERAGING_16)

        self.type_label = QLabel('Thermocouple Type:')
        self.type_combo = QComboBox()
        self.type_combo.addItem('B', BrickletThermocouple.TYPE_B)
        self.type_combo.addItem('E', BrickletThermocouple.TYPE_E)
        self.type_combo.addItem('J', BrickletThermocouple.TYPE_J)
        self.type_combo.addItem('K', BrickletThermocouple.TYPE_K)
        self.type_combo.addItem('N', BrickletThermocouple.TYPE_N)
        self.type_combo.addItem('R', BrickletThermocouple.TYPE_R)
        self.type_combo.addItem('S', BrickletThermocouple.TYPE_S)
        self.type_combo.addItem('T', BrickletThermocouple.TYPE_T)
        self.type_combo.addItem('Gain 8', BrickletThermocouple.TYPE_G8)
        self.type_combo.addItem('Gain 32', BrickletThermocouple.TYPE_G32)

        self.filter_label = QLabel('Noise Rejection Filter:')
        self.filter_combo = QComboBox()
        self.filter_combo.addItem('50 Hz',
                                  BrickletThermocouple.FILTER_OPTION_50HZ)
        self.filter_combo.addItem('60 Hz',
                                  BrickletThermocouple.FILTER_OPTION_60HZ)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.averaging_label)
        hlayout.addWidget(self.averaging_combo)
        hlayout.addStretch()
        hlayout.addWidget(self.type_label)
        hlayout.addWidget(self.type_combo)
        hlayout.addStretch()
        hlayout.addWidget(self.filter_label)
        hlayout.addWidget(self.filter_combo)

        line = QFrame()
        line.setObjectName("line")
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

        self.averaging_combo.currentIndexChanged.connect(
            self.configuration_changed)
        self.type_combo.currentIndexChanged.connect(self.configuration_changed)
        self.filter_combo.currentIndexChanged.connect(
            self.configuration_changed)
Esempio n. 33
0
class Player(QMainWindow):
    """A simple Media Player using VLC and Qt
    """
    def __init__(self, master=None):
        QMainWindow.__init__(self, master)
        self.setWindowTitle("Video Annotation Tool")

        # creating a basic vlc instance
        self.instance = vlc.Instance()
        # creating an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()

        self.createUI()
        self.isPaused = False

        self.setMouseTracking(True)
        self.size = None

    def createUI(self):
        """Set up the user interface, signals & slots
        """
        self.widget = QWidget(self)
        self.setCentralWidget(self.widget)

        # In this widget, the video will be drawn
        if sys.platform == "darwin":  # for MacOS
            from PyQt5.QtWidgets import QMacCocoaViewContainer
            self.videoframe = QMacCocoaViewContainer(0)
        else:
            self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0, 0, 0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)
        self.playbutton.clicked.connect(self.PlayPause)

        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.time_label = QLabel("<center>0</center>")
        self.coordinates = QLabel("<center>x, y</center>")
        self.hbuttonbox.addWidget(self.time_label)
        self.hbuttonbox.addWidget(self.coordinates)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

        self.widget.setLayout(self.vboxlayout)

        open = QAction("&Open", self)
        open.triggered.connect(self.OpenFile)
        exit = QAction("&Exit", self)
        exit.triggered.connect(sys.exit)
        menubar = self.menuBar()
        filemenu = menubar.addMenu("&File")
        filemenu.addAction(open)
        filemenu.addSeparator()
        filemenu.addAction(exit)

        self.timer = QTimer(self)
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.updateUI)

    def PlayPause(self):
        """Toggle play/pause status
        """
        if self.mediaplayer.is_playing():
            self.mediaplayer.pause()
            self.playbutton.setText("Play")
            self.isPaused = True
        else:
            if self.mediaplayer.play() == -1:
                self.OpenFile()
                return
            self.mediaplayer.play()
            self.playbutton.setText("Pause")
            self.timer.start()
            self.isPaused = False

    def Stop(self):
        """Stop player
        """
        self.mediaplayer.stop()
        self.playbutton.setText("Play")

    def OpenFile(self, filename=None):
        """Open a media file in a MediaPlayer
        """
        if filename is None:
            filename = QFileDialog.getOpenFileName(self, "Open File",
                                                   os.path.expanduser('~'))[0]
        if not filename:
            filename = QFileDialog.getOpenFileName(self, "Open File",
                                                   os.path.expanduser('~'))[0]
            #return

        # create the media
        if sys.version < '3':
            filename = unicode(filename)
        self.media = self.instance.media_new(filename)
        # put the media in the media player
        self.mediaplayer.set_media(self.media)

        # parse the metadata of the file
        self.media.parse()
        # set the title of the track as window title
        self.setWindowTitle(self.media.get_meta(0))

        # the media player has to be 'connected' to the QFrame
        # (otherwise a video would be displayed in it's own window)
        # this is platform specific!
        # you have to give the id of the QFrame (or similar object) to
        # vlc, different platforms have different functions for this
        if sys.platform.startswith('linux'):  # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":  # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
        self.size = self.mediaplayer.video_get_size()
        self.PlayPause()

    def setVolume(self, Volume):
        """Set the volume
        """
        self.mediaplayer.audio_set_volume(Volume)

    def setPosition(self, position):
        """Set the position
        """
        # setting the position to where the slider was dragged
        self.mediaplayer.set_position(position / 1000.0)
        # the vlc MediaPlayer needs a float value between 0 and 1, Qt
        # uses integer variables, so you need a factor; the higher the
        # factor, the more precise are the results
        # (1000 should be enough)

    def updateUI(self):
        """updates the user interface"""
        # setting the slider to the desired position
        self.positionslider.setValue(self.mediaplayer.get_position() * 1000)
        self.time_label.setText(
            f'Time {str(self.mediaplayer.get_time() / 1000)} seconds')
        #self.size = self.mediaplayer.video_get_size()

        if not self.mediaplayer.is_playing():
            # no need to call this function if nothing is played
            self.timer.stop()
            if not self.isPaused:
                # after the video finished, the play button stills shows
                # "Pause", not the desired behavior of a media player
                # this will fix it
                self.Stop()

    def get_coordinates(self):
        return self.mediaplayer.video_get_cursor()

    def mouseMoveEvent(self, event):
        print(self.mediaplayer.video_get_cursor())
        if isinstance(self.size, tuple):
            video_width, video_height = self.size
        else:
            video_width, video_height = 0, 0
        # self.coordinates.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()) + "Distance from center: " + str(distance_from_center))
        #self.coordinates.setText('Coordinates: ( %d : %d )' % (event.x() - 9, event.y() - 30) + "Distance from center: ")
        self.coordinates.setText(
            f'Coordinates: {self.get_coordinates()[0]}, {self.get_coordinates()[1]}. Video size {video_height} {video_width}'
        )
        self.pos = event.pos()
        self.update()
Esempio n. 34
0
    def __init__(self, url, movieID, user):
        super().__init__()
        self.controller = MovieController(url)
        self.url = url
        self.user = user
        self.setWindowTitle("Movie Player")
        self.movieID = movieID
        # creating a basic vlc instance
        self.instance = vlc.Instance()
        # creating an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()
        self.isPaused = True
        

#        self.moviebox = QVBoxLayout()
#        self.moviebox.addWidget(self.widget)
#        self.widget.setLayout(self.moviebox)
#        print("here")
        
        self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor (QPalette.Window,
                                QColor(0,0,0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)


        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        
        self.vboxlayout = QVBoxLayout()
      
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

    
        self.comment = QPlainTextEdit()
        

        
        self.comment.setPlaceholderText("Type Comment Here ...")
        self.comment.setFixedHeight(50)
        self.commentbox = QVBoxLayout()
        
        self.commentSubmit = QPushButton("Comment")
        self.commentSubmit.clicked.connect(lambda: self.submitComment())
        self.commentbox.addWidget(self.comment)
        self.commentbox.addWidget(self.commentSubmit)
        
        self.commentSection = QLabel("Comments:\n")
        self.commentSection.setFixedHeight(10)
        self.commentbox.addWidget(self.commentSection)
        self.commentSection_comments = QTextEdit("No Comments Yet")
        self.commentSection_comments.setStyleSheet("QTextEdit {color:black;font-size:13px;font-family: \"Times New Roman\", Times, serif;background-color:transparent;border-style: none}")
        self.commentSection_comments.setReadOnly(True)
        self.commentSection_comments.setFixedHeight(50)
        
        self.commentbox.addWidget(self.commentSection_comments)
        self.vboxlayout.addLayout(self.commentbox)
        
        
        self.setLayout(self.vboxlayout)
        self.playbutton.clicked.connect(lambda: self.PlayPause())
        self.stopbutton.clicked.connect(lambda: self.Stop())

        self.resize(640,480)
       
        self.timer = QTimer(self)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.updateUI)   
        
        
        
        self.loaded = False
        self.video = pafy.new(self.url) 
        
        self.best = self.video.getbest() 
            
        self.media = self.instance.media_new(self.best.url)
        
        self.mediaplayer.set_media(self.media)
        
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32": # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin": # for MacOS
            self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
            
        
        self.LoadComments()
Esempio n. 35
0
class ZhuangGeiFX(QDialog):
    def __init__(self, data, chess, job, race, equip):
        super().__init__()
        self.data = data
        self.chess = chess
        self.job = job
        self.race = race
        self.equip = equip
        self.initshow()

    def initshow(self):
        self.setMinimumWidth(504)
        self.setObjectName('ZhuangbeiFX')
        self.spTitle = QLabel('装备分析')
        self.spTitle.setObjectName('Title')
        self.spDoc = QLabel(self.data['equipment_info'].replace(
            '&amp;nbsp;', ''))
        self.spDoc.setObjectName('Doc')
        self.spDoc.setWordWrap(True)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.spTitle)
        self.vbox.addWidget(self.spDoc)
        #装备推荐框架
        self.zbTJFrame = QFrame()
        self.zbTJVbox = QVBoxLayout()

        #遍历站位数据,看有没有装备,有装备的就加入zbTJHbox
        self.zbtj_YLH = []
        self.xjzb_Vbox = []
        #初始化羁绊和职业容器
        job_list = []
        race_list = []

        txData = None
        for item in self.data['hero_location']:
            # 将羁绊和职业数据存进容器
            try:
                chessData = chessId_get_data(self.chess, item['hero_id'])
                if chessData == None:
                    continue

            except:
                continue
            try:
                for job_item in chessData['jobIds'].split(','):
                    job_list.append(job_item)
            except:
                pass
            try:
                for race_item in chessData['raceIds'].split(','):
                    race_list.append(race_item)
            except:
                pass
            zwpath = Path_chess + chessData['name']
            if item['equipment_id'] != '':
                #英雄头像
                self.zbtj_YLH.append(QHBoxLayout())
                self.zbTJVbox.addLayout(self.zbtj_YLH[-1])
                if chessData["price"] == '1':
                    color = '#989898'
                elif chessData["price"] == '2':
                    color = '#58B137'
                elif chessData["price"] == '3':
                    color = '#3678C8'
                elif chessData["price"] == '4':
                    color = '#C81FC8'
                else:
                    color = '#FDBC03'
                tp_yx = QLabel()
                # 让图像适应标签
                tp_yx.setScaledContents(True)
                tp_yx.setPixmap(QPixmap(zwpath))
                tp_yx.setMaximumSize(50, 50)
                tp_yx.setMinimumSize(50, 50)
                tp_yx.setObjectName('tp_yx')
                tp_yx.setStyleSheet(
                    '''#tp_yx{border: 1px solid %s;border-radius: 10px;  }
                                                               ''' % color)

                tp_yx.setToolTip(tanChudataForm(chessData, self.job,
                                                self.race))
                self.zbtj_YLH[-1].addWidget(tp_yx)
                jtbt = QLabel('>')
                jtbt.setObjectName('Title')
                self.zbtj_YLH[-1].addWidget(jtbt)

                for equi in item['equipment_id'].split(','):

                    djzb = equipId_get_data(self.equip, equi)
                    # 将羁绊和职业数据存进容器
                    try:

                        if djzb['jobId'] != '0' and djzb['jobId'] != None:
                            job_list.append(djzb['jobId'])
                    except:
                        pass
                    try:

                        if djzb['raceId'] != '0' and djzb['raceId'] != None:
                            race_list.append(djzb['raceId'])
                    except:
                        pass

                    zbpath = Path_equip + djzb['imagePath'].split('/')[-1]
                    #大件装备

                    tp_djzb = QLabel()
                    # 让图像适应标签
                    tp_djzb.setScaledContents(True)
                    tp_djzb.setPixmap(QPixmap(zbpath))
                    tp_djzb.setMaximumSize(40, 40)
                    tp_djzb.setMinimumSize(40, 40)
                    tp_djzb.setToolTip(tanChu_EquipData(self.equip, djzb))
                    self.zbtj_YLH[-1].addWidget(tp_djzb)
                    #取小装备的id
                    self.xjzb_Vbox.append(QVBoxLayout())
                    self.xjzb_Vbox[-1].addStretch()
                    self.zbtj_YLH[-1].addLayout(self.xjzb_Vbox[-1])
                    for itemXJ in djzb['formula'].split(','):
                        xjzb = equipId_get_data(self.equip, itemXJ)
                        xjzbpath = Path_equip + xjzb['imagePath'].split(
                            '/')[-1]
                        #print('小装备', zbpath)
                        tp_xjzb = QLabel()
                        # 让图像适应标签
                        tp_xjzb.setScaledContents(True)
                        tp_xjzb.setPixmap(QPixmap(xjzbpath))
                        tp_xjzb.setMaximumSize(20, 20)
                        tp_xjzb.setMinimumSize(20, 20)
                        self.xjzb_Vbox[-1].addWidget(tp_xjzb)
                    #一个弹簧..用来控制位置的
                    self.xjzb_Vbox[-1].addStretch()

                self.zbtj_YLH[-1].addStretch()
            """ # 天选羁绊和职业存入
            if 'isChosenHero' in item:

                if item['isChosenHero'] != None:
                    txData = item['isChosenHero']
                    # 天选羁绊id
                    sss = ''
                    for key in txData.keys():
                        sss = key
                    if sss == 'race':
                        race_list.append(txData['race'])
                    else:
                        job_list.append(txData['job'])
                else:
                    pass"""

        #职业分析组件---------------------------------------------
        self.from_job = QFrame()
        self.from_jobHBox = QHBoxLayout()
        #统计总职业数,并且将底图和图标获取
        jb_ss = {}.fromkeys(job_list).keys()
        for ss in jb_ss:
            num = job_list.count(ss)

            if txData != None:
                if sss == 'job' and txData['job'] == ss:
                    test_job = job_get_background_sf(self.job, ss, num, True)
                else:
                    test_job = job_get_background_sf(self.job, ss, num, False)
            else:
                test_job = job_get_background_sf(self.job, ss, num, False)
            if test_job != None:
                #将每一个小组件渲染
                tp_hbox = QHBoxLayout()
                #羁绊背景
                tp_jb_bj = QLabel()
                tp_jb_bj.setScaledContents(True)
                tp_jb_bj.setPixmap(QPixmap(test_job[0]))
                tp_jb_bj.setMaximumSize(30, 34)
                tp_jb_bj.setMinimumSize(30, 34)
                tp_jb_bj.setToolTip(
                    f'''<b style='color:#FFFFFF;'>{test_job[2]['introduce']}<br>{str(test_job[2]['level']).replace('{', '').replace('}', '').replace(',', '<br>')}</b>'''
                )

                #tp_jb_bj上方显示图标
                tp_jb = QLabel(tp_jb_bj)
                tp_jb.move(5, 7)
                tp_jb.setScaledContents(True)
                tp_jb.setPixmap(QPixmap(test_job[1]))
                tp_jb.setMaximumSize(20, 20)
                tp_jb.setMinimumSize(20, 20)
                #羁绊名 文字
                tp_text = QLabel(tp_jb_bj)
                tp_text.setObjectName('JB')
                tp_text.setText(f"{num} " + test_job[2]['name'])

                #将数据加入到每一列的布局中
                tp_hbox.addWidget(tp_jb_bj)
                tp_hbox.addWidget(tp_text)
                self.from_jobHBox.addLayout(tp_hbox)

        self.from_jobHBox.addStretch()

        # 羁绊分析组件---------------------------------------------
        self.from_race = QFrame()
        self.from_raceHBox = QHBoxLayout()
        # 统计总羁绊数,并且将底图和图标获取
        race_ss = {}.fromkeys(race_list).keys()
        for ss in race_ss:
            num = race_list.count(ss)

            if txData != None:
                if sss == 'race' and txData['race'] == ss:
                    test_race = race_get_background_sf(self.race, ss, num,
                                                       True)
                else:
                    test_race = race_get_background_sf(self.race, ss, num,
                                                       False)
            else:
                test_race = race_get_background_sf(self.race, ss, num, False)
            if test_race != None:
                # 将每一个小组件渲染

                tp_hbox = QHBoxLayout()
                # 羁绊背景
                tp_jb_bj = QLabel()
                tp_jb_bj.setScaledContents(True)
                tp_jb_bj.setPixmap(QPixmap(test_race[0]))
                tp_jb_bj.setMaximumSize(30, 34)
                tp_jb_bj.setMinimumSize(30, 34)
                tp_jb_bj.setToolTip(
                    f'''<b style='color:#FFFFFF;'>{test_race[2]['introduce']}<br>{str(test_race[2]['level']).replace('{', '').replace('}', '').replace(',', '<br>')}</b>'''
                )

                # tp_jb_bj上方显示图标
                tp_jb = QLabel(tp_jb_bj)
                tp_jb.move(5, 7)
                tp_jb.setScaledContents(True)
                tp_jb.setPixmap(QPixmap(test_race[1]))
                tp_jb.setMaximumSize(20, 20)
                tp_jb.setMinimumSize(20, 20)
                # 羁绊名 文字
                tp_text = QLabel(tp_jb_bj)
                tp_text.setObjectName('JB')
                tp_text.setText(f"{num} " + test_race[2]['name'])

                # 将数据加入到每一列的布局中
                tp_hbox.addWidget(tp_jb_bj)
                tp_hbox.addWidget(tp_text)
                self.from_raceHBox.addLayout(tp_hbox)
        self.from_raceHBox.addStretch()

        self.zbTJFrame.setLayout(self.zbTJVbox)
        self.from_job.setLayout(self.from_jobHBox)
        self.from_race.setLayout(self.from_raceHBox)
        self.vbox.addWidget(self.zbTJFrame)
        self.vbox.addWidget(self.from_job)
        self.vbox.addWidget(self.from_race)

        self.vbox.setSpacing(2)
        self.setLayout(self.vbox)
        self.setStyleSheet('''
        #ZhuangbeiFX{
        border: 1px solid rgb(185, 185, 185);  
        
    	background-color: rgb(22,26,32);
    	border-right-style:none;
        border-top-style:none;
        }
        #Title{
	    color: #FFFFFF;
	    background: rgba(22,26,32, 200);   
	    font: 75 12pt "微软雅黑";}
	    
	    #Doc{
	    color: #7E807D;
	    border-left-style: 1px solid rgb(185, 185, 185);  
	    background: rgba(22,26,32, 200) ;  
	    font: 75 10pt "微软雅黑";}
	    #JB{
	    color: #FFFFFF;
	    background: rgba(22,26,32, 200);   
	    font: 75 10pt "微软雅黑";}
	    QToolTip{
            border: 2px solid qconicalgradient(cx:0, cy:0, angle:135, stop:0 rgba(255, 255, 0, 69), stop:0.375 rgba(255, 255, 0, 69), stop:0.423533 rgba(251, 255, 0, 145), stop:0.45 rgba(247, 255, 0, 208), stop:0.477581 rgba(255, 244, 71, 130), stop:0.518717 rgba(255, 218, 71, 130), stop:0.55 rgba(255, 255, 0, 255), stop:0.57754 rgba(255, 203, 0, 130), stop:0.625 rgba(255, 255, 0, 69), stop:1 rgba(255, 255, 0, 69));   
	        background-color: rgb(22,26,32);
	        ridge:ridge;
	        padding: 4px;
	        border-radius:10px;
        }
        ''')
Esempio n. 36
0
    def init_ui(self):
        self.setFont(QFont('Segoe UI'))

        self.setGeometry(0, 0, 780, 820)
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        self.setWindowTitle('HyPro - Plotting Window')

        self.qvbox_layout = QVBoxLayout()
        self.qvbox_frame_holder = QFrame()
        self.qvbox_frame_holder.setLayout(self.qvbox_layout)
        self.grid_layout = QGridLayout()

        self.main_menu = self.menuBar()
        self.file_menu = self.main_menu.addMenu('File')
        self.edit_menu = self.main_menu.addMenu('Edit')

        export = QAction(QIcon(':/assets/archivebox.svg'), 'Export Plot', self)
        export.triggered.connect(self.export_plot)
        self.file_menu.addAction(export)

        copy = QAction(QIcon(':/assets/newdoc.svg'), 'Copy', self)
        copy.triggered.connect(self.copy_plot)
        self.edit_menu.addAction(copy)

        self.run_list_label = QLabel('Select Run:', self)
        self.run_list = QListWidget(self)
        self.run_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.run_list.setMaximumWidth(120)

        self.show_bad_data = QCheckBox('Show bad data', self)

        self.mark_bad_data = QCheckBox('Mark bad data', self)

        self.apply_button = QPushButton('Apply', self)

        self.figure = plt.figure()
        self.figure.set_tight_layout(tight=True)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)

        self.main_plot = self.figure.add_subplot(111)

        for x in self.main_plot.get_xticklabels():
            x.set_fontsize(12)
        for y in self.main_plot.get_yticklabels():
            y.set_fontsize(12)

        self.grid_layout.addWidget(self.canvas, 0, 1)
        self.grid_layout.addWidget(self.qvbox_frame_holder, 0, 0)

        self.qvbox_layout.addWidget(self.run_list_label)
        self.qvbox_layout.addWidget(self.run_list)
        self.qvbox_layout.addWidget(self.show_bad_data)
        self.qvbox_layout.addWidget(self.mark_bad_data)
        self.qvbox_layout.addWidget(self.apply_button)

        self.centralWidget().setLayout(self.grid_layout)
Esempio n. 37
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.interface_lng_val = 'Russian'
        if self.interface_lng_val == 'Russian':
            self.setWindowTitle("Графический интерфейс программы OpenFOAM")
        elif self.interface_lng_val == 'English':
            self.setWindowTitle("OpenFOAM_decompose_GUI")

        # Базовые переменные

        self.full_dir = ''
        self.prj_name = ''
        self.con = ''
        self.lock_bool = False
        self.application = ''

        # ---------------------------Панель управления подготовкой задачи МСС----------------------------- #

        self.proj_open = QAction(self)
        self.proj_open.setEnabled(True)
        proj_ico = self.style().standardIcon(QStyle.SP_ArrowUp)
        self.proj_open.setIcon(proj_ico)
        if self.interface_lng_val == 'Russian':
            self.proj_open.setToolTip('Открыть проект')
        elif self.interface_lng_val == 'English':
            self.proj_open.setToolTip('Open the project')

        self.lng_chs = QAction(self)
        self.lng_chs.setEnabled(True)
        lng_chs_ico = self.style().standardIcon(
            QStyle.SP_FileDialogDetailedView)
        self.lng_chs.setIcon(lng_chs_ico)
        if self.interface_lng_val == 'Russian':
            self.lng_chs.setToolTip('Выбрать язык интерфейса программы')
        elif self.interface_lng_val == 'English':
            self.lng_chs.setToolTip('Select the interface language')

        self.file_open = QAction(self)
        self.file_open.setEnabled(False)
        file_open_ico = self.style().standardIcon(QStyle.SP_FileIcon)
        self.file_open.setIcon(file_open_ico)
        if self.interface_lng_val == 'Russian':
            self.file_open.setToolTip(
                'Открыть форму создания служебного файла для директории 0')
        elif self.interface_lng_val == 'English':
            self.file_open.setToolTip(
                'Open the form for creating the service file for the directory 0'
            )

        self.toolBar_1 = QToolBar("MyToolBar")
        self.toolBar_1.addAction(self.proj_open)
        self.toolBar_1.addAction(self.lng_chs)
        self.toolBar_1.addAction(self.file_open)

        self.proj_open.triggered.connect(
            lambda: first_toolbar_functions_class.on_proj_open(self))
        self.lng_chs.triggered.connect(
            lambda: first_toolbar_functions_class.on_lng_chs(self))
        self.file_open.triggered.connect(
            lambda: first_toolbar_functions_class.on_0_files_window_chs(self))

        self.addToolBar(self.toolBar_1)

        ###----------------------Панель управления подготовкой РС--------------------------###

        self.msh_open = QAction(self)
        self.msh_open.setEnabled(False)
        msh_ico = self.style().standardIcon(QStyle.SP_FileDialogNewFolder)
        self.msh_open.setIcon(msh_ico)
        if self.interface_lng_val == 'Russian':
            self.msh_open.setToolTip('Открыть форму выбора расчетной сетки')
        elif self.interface_lng_val == 'English':
            self.msh_open.setToolTip('Open the mesh selection form')

        self.msh_run = QAction(self)
        self.msh_run.setEnabled(False)
        msh_ico = self.style().standardIcon(QStyle.SP_ArrowRight)
        self.msh_run.setIcon(msh_ico)
        if self.interface_lng_val == 'Russian':
            self.msh_run.setToolTip('Выполнить генерацию расчетной сетки')
        elif self.interface_lng_val == 'English':
            self.msh_run.setToolTip('Make the mesh generation')

        self.msh_visual = QAction(self)
        self.msh_visual.setEnabled(False)
        msh_visual_ico = self.style().standardIcon(QStyle.SP_MediaSeekForward)
        self.msh_visual.setIcon(msh_visual_ico)
        if self.interface_lng_val == 'Russian':
            self.msh_visual.setToolTip(
                'Выполнить визуализацию расчетной сетки')
        elif self.interface_lng_val == 'English':
            self.msh_visual.setToolTip('Make the mesh visualization')

        self.toolBar_2 = QToolBar()
        self.toolBar_2.addAction(self.msh_open)
        self.toolBar_2.addAction(self.msh_run)
        self.toolBar_2.addAction(self.msh_visual)

        self.msh_open.triggered.connect(
            lambda: second_toolbar_functions_class.on_msh_open(self))
        self.msh_run.triggered.connect(
            lambda: second_toolbar_functions_class.on_msh_run(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.msh_visual.triggered.connect(
            lambda: second_toolbar_functions_class.on_visual_msh_run(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.addToolBar(self.toolBar_2)
        self.insertToolBarBreak(self.toolBar_2)

        ###----------------------Панель управления решением задачи МСС--------------------------###

        self.solv_run = QAction(self)
        self.solv_run.setEnabled(False)
        solv_run_ico = self.style().standardIcon(QStyle.SP_DialogNoButton)
        self.solv_run.setIcon(solv_run_ico)
        if self.interface_lng_val == 'Russian':
            self.solv_run.setToolTip('Выполнить решение')
        elif self.interface_lng_val == 'English':
            self.solv_run.setToolTip('Run solution')

        self.solv_stop = QAction(self)
        self.solv_stop.setEnabled(False)
        close_ico = self.style().standardIcon(QStyle.SP_DockWidgetCloseButton)
        self.solv_stop.setIcon(close_ico)
        if self.interface_lng_val == 'Russian':
            self.solv_stop.setToolTip('Остановить процесс решения')
        elif self.interface_lng_val == 'English':
            self.solv_stop.setToolTip('Stop the solution process')

        self.solv_run_vis = QAction(self)
        self.solv_run_vis.setEnabled(False)
        solv_run_vis_ico = self.style().standardIcon(QStyle.SP_CommandLink)
        self.solv_run_vis.setIcon(solv_run_vis_ico)
        if self.interface_lng_val == 'Russian':
            self.solv_run_vis.setToolTip(
                'Выполнить визуализацию результатов решения')
        elif self.interface_lng_val == 'English':
            self.solv_run_vis.setToolTip('Visualize the solution results')

        self.toolBar_3 = QToolBar()
        self.toolBar_3.addAction(self.solv_run)
        self.toolBar_3.addAction(self.solv_stop)
        self.toolBar_3.addAction(self.solv_run_vis)

        self.solv_run.triggered.connect(
            lambda: second_toolbar_functions_class.on_solv_run(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.solv_stop.triggered.connect(
            lambda: second_toolbar_functions_class.on_solv_stop(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.solv_run_vis.triggered.connect(
            lambda: second_toolbar_functions_class.on_solv_vis(
                prj_path_val, mesh_name_txt_val, pp_dir, self, self.
                interface_lng_val, msh_type))

        self.addToolBar(self.toolBar_3)
        self.insertToolBarBreak(self.toolBar_3)

        ###----------------Верхний виджет с полным путем до файла сетки----------------###

        self.tdw = QDockWidget()
        self.tdw.setFixedSize(1400, 65)
        self.tdw.setFeatures(self.tdw.NoDockWidgetFeatures)
        self.tdw_grid = QGridLayout()
        self.tdw_grid.setColumnStretch(2, 1)
        self.tdw_frame = QFrame()
        self.tdw_frame.setStyleSheet("background-color: ghostwhite;"
                                     "border-width: 0.5px;"
                                     "border-style: solid;"
                                     "border-color: silver;")
        self.tdw_frame.setLayout(self.tdw_grid)
        self.tdw.setWidget(self.tdw_frame)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.tdw)

        ###-----------------Левый виджет с файловой системой проекта---------------------###

        self.fsw = QDockWidget()
        self.fsw.setFeatures(self.fsw.NoDockWidgetFeatures)
        self.fsw_label = QLabel()
        self.fsw_label.setAlignment(QtCore.Qt.AlignCenter)
        self.fsw_grid = QGridLayout()
        self.fsw_grid.addWidget(self.fsw_label, 0, 0)
        self.fsw_frame = QFrame()
        self.fsw_frame.setFixedSize(200, 35)
        self.fsw_frame.setStyleSheet("background-color: honeydew;"
                                     "border-width: 1px;"
                                     "border-style: solid;"
                                     "border-color: dimgray;"
                                     "border-radius: 4px;")
        self.fsw_frame.setLayout(self.fsw_grid)

        if self.interface_lng_val == 'Russian':
            fs_lbl = "Файловая Cтруктура Проекта"
        elif self.interface_lng_val == 'English':
            fs_lbl = "File Structure of the Project"

        self.fsw_label.setText("<font color='SeaGreen'>" + fs_lbl + "</font>")
        self.fsw_label.setStyleSheet("border-style: none;" "font-size: 10pt;")
        self.fsw.setTitleBarWidget(self.fsw_frame)
        self.treeview = QTreeView()
        self.treeview.setFixedSize(200, 520)
        self.treeview.model = QtGui.QStandardItemModel()
        self.treeview.setModel(self.treeview.model)
        self.treeview.setColumnWidth(0, 100)
        self.treeview.setColumnHidden(1, True)
        self.treeview.setColumnHidden(2, True)
        self.treeview.setColumnHidden(3, True)
        self.treeview.header().hide()
        self.treeview.setItemsExpandable(False)
        self.treeview.clicked.connect(self.on_treeview_clicked)
        self.fsw.setWidget(self.treeview)

        ###-----------Правый виджет с формой вывода результатов генерации файлов-----------###

        self.cdw = QDockWidget()
        self.cdw.setFeatures(self.cdw.NoDockWidgetFeatures)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.cdw)

        self.cdw_grid = QGridLayout()
        self.cdw_frame = QFrame()
        self.cdw_frame.setFixedSize(495, 35)
        self.cdw_frame.setStyleSheet("border-width: 1px;"
                                     "border-style: solid;"
                                     "border-color: dimgray;"
                                     "border-radius: 4px;"
                                     "background-color: honeydew;")
        self.cdw_frame.setLayout(self.cdw_grid)

        self.outf_lbl = QLabel()
        self.outf_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.outf_lbl.setStyleSheet("border-style: none;" "font-size: 9pt;")

        self.cdw_grid.addWidget(self.outf_lbl, 0, 0)

        self.outf_edit = QTextEdit()
        self.outf_scroll = QScrollArea()
        self.outf_scroll.setWidgetResizable(True)
        self.outf_scroll.setWidget(self.outf_edit)
        self.outf_scroll.setFixedSize(495, 520)

        ###-----------------Центральный виджет с формой параметров---------------------###

        self.ffw = QDockWidget()
        self.ffw.setFeatures(self.ffw.NoDockWidgetFeatures)
        self.ffw_label = QLabel()
        self.ffw_label.setAlignment(QtCore.Qt.AlignCenter)
        self.ffw_grid = QGridLayout()
        self.ffw_grid.addWidget(self.ffw_label, 0, 0)
        self.ffw_frame = QFrame()
        self.ffw_frame.setFixedSize(693, 44)
        self.ffw_frame.setStyleSheet("border-width: 1px;"
                                     "border-style: solid;"
                                     "border-color: dimgray;"
                                     "border-radius: 4px;"
                                     "background-color: honeydew;")
        self.ffw_frame.setLayout(self.ffw_grid)

        ###------------------Нижний виджет со служебными сообщениями------------------###

        if self.interface_lng_val == 'Russian':
            self.serv_mes = QDockWidget("Служебные сообщения")
        elif self.interface_lng_val == 'English':
            self.serv_mes = QDockWidget("Service messages")

        self.serv_mes.setFixedSize(1400, 160)
        self.serv_mes.setFeatures(self.serv_mes.NoDockWidgetFeatures)
        self.listWidget = QListWidget()
        self.serv_mes.setWidget(self.listWidget)
Esempio n. 38
0
    def setupUi(self):

        # 游戏大厅界面
        self.setGeometry(QRect(10, 10, 671, 711))
        # self.setStyleSheet("background-image: url(./img/bg.bmp);")
        self.setFrameShape(QFrame.Box)
        self.setFrameShadow(QFrame.Sunken)
        self.setLineWidth(2)
        self.setObjectName("uiGameFrame")

        self.hallBanner = QLabel(self)
        self.hallBanner.setGeometry(QRect(20, 10, 630, 50))
        self.hallBanner.setObjectName("hallBanner")
        self.hallBanner.setScaledContents(True)
        # self.hallBanner.setStyleSheet("/*border:1px solid;*/background-image: url(./img/banner.png);")
        pix = QtGui.QPixmap('./img/banner.png')
        self.hallBanner.setPixmap(pix)

        self.hall_scrollArea = QScrollArea(self)
        self.hall_scrollArea.setGeometry(QRect(20, 80, 630, 551))
        self.hall_scrollArea.setWidgetResizable(True)
        self.hall_scrollArea.setObjectName("scrollArea")
        self.hall_widgetContents = QWidget()
        self.hall_widgetContents.setGeometry(QRect(0, 0, 629, 549))
        self.hall_widgetContents.setObjectName("widgetContents")
        self.hall_widgetContents.setMinimumSize(QSize(400, 400))
        # self.hall_widgetContents.setStyleSheet('background:rgba(0,0,0,0)')

        # 创建房间列表,用于存储房间
        self.rooms = {}
        self.lay = QGridLayout(self.hall_widgetContents)

        self.hall_scrollArea.setWidget(self.hall_widgetContents)

        # 按钮区域
        self.cmd_frame = QFrame(self)
        self.cmd_frame.setGeometry(QRect(55, 655, 560, 47))
        self.cmd_frame.setFrameShape(QFrame.StyledPanel)
        self.cmd_frame.setFrameShadow(QFrame.Raised)
        self.cmd_frame.setObjectName("cmdFrame")

        # 快速游戏
        self.hallFastJoin = QPushButton(self.cmd_frame)
        self.hallFastJoin.setGeometry(QRect(10, 10, 100, 27))
        self.hallFastJoin.setObjectName("hallFastJoin")

        # 用户信息
        self.hallUserInfo = QPushButton(self.cmd_frame)
        self.hallUserInfo.setGeometry(QRect(120, 10, 100, 27))
        self.hallUserInfo.setObjectName("hallUserInfo")

        # 单机游戏
        self.hallConsoleGame = QPushButton(self.cmd_frame)
        self.hallConsoleGame.setGeometry(QRect(230, 10, 100, 27))
        self.hallConsoleGame.setObjectName("hallConsoleGame")

        # 返回大厅
        self.hallCreateRoom = QPushButton(self.cmd_frame)
        self.hallCreateRoom.setGeometry(QRect(340, 10, 100, 27))
        self.hallCreateRoom.setObjectName("hallCreateRoom")

        # 设置
        self.hallSetBtn = QPushButton(self.cmd_frame)
        self.hallSetBtn.setGeometry(QRect(450, 10, 100, 27))
        self.hallSetBtn.setObjectName("hallSetBtn")

        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)
Esempio n. 39
0
class Study(QFrame):

    TOP_ICON_WIDTH = 50
    TOP_ICON_HEIGHT = 50
    MAIN_IMAGE_WIDTH = 100
    MAIN_IMAGE_HEIGHT = 100

    choosed = pyqtSignal(str)

    def __init__(self, areas, info_list, master=None):
        super().__init__(master)
        self.areas = areas
        self.info_list = info_list
        self.build_inter()

    def build_inter(self):
        temp = QPixmap(os.path.join(paths.IMAGE, "数学.png"))
        self.top_icon = temp.scaled(Study.TOP_ICON_WIDTH,
                                    Study.TOP_ICON_HEIGHT, Qt.KeepAspectRatio)

        self.mid_type_icon = {}
        self.mid_frames = []
        for index, type_ in enumerate(self.areas):
            temp = QPixmap(os.path.join(paths.IMAGE, type_ + ".png"))
            temp_icon = temp.scaled(Study.MAIN_IMAGE_WIDTH,
                                    Study.MAIN_IMAGE_HEIGHT,
                                    Qt.KeepAspectRatio)
            self.mid_type_icon[type_] = temp_icon
            push_frame = QPushFrame(self, type_, temp_icon, self.info_list)
            push_frame.clicked.connect(self.choose_type)
            self.mid_frames.append(push_frame)

        self.build_main()

        self.show()

    def build_main(self):
        with open("study.qss", "r") as f:
            self.setStyleSheet(f.read())
        self.setObjectName("study_main")

        self.main_vbox = QVBoxLayout()
        self.setLayout(self.main_vbox)

        #self.top_icon_lb = QLabel(self)
        #self.top_icon_lb.setPixmap(self.top_icon)

        self.top_subj_lb = QLabel("数学", self)
        self.top_subj_lb.setFont(QFont("苹方-简", 24))
        self.top_subj_lb.setObjectName("subject")

        self.top_frame = QFrame(self)
        self.top_frame.setObjectName("top_frame")
        self.top_column = QHBoxLayout()
        self.top_frame.setLayout(self.top_column)
        #self.top_column.addWidget(self.top_icon_lb)
        self.top_column.addStretch(1)
        self.top_column.addWidget(self.top_subj_lb)
        self.top_column.addStretch(1)
        self.top_column.setContentsMargins(0, 0, 0, 0)

        self.main_vbox.addWidget(self.top_frame)

        self.scroll_center = QScrollArea(self)
        self.scroll_center.setAlignment(Qt.AlignCenter)
        self.scroll_center.setObjectName("scroll_center")

        self._center_area = QFrame(self)
        self._center_area.setSizePolicy(self.scroll_center.sizePolicy())
        self._center_vbox = QVBoxLayout()
        self._center_area.setLayout(self._center_vbox)
        self._center_area.setObjectName("center_area")

        length = len(self.mid_frames)
        for frame in self.mid_frames:
            self._center_vbox.addWidget(frame)
        self._center_vbox.setContentsMargins(0, 0, 0, 0)

        self.scroll_center.setWidget(self._center_area)

        self.main_vbox.addWidget(self.scroll_center)

        self.main_vbox.setContentsMargins(0, 0, 0, 0)

    '''
    def clear(self, layout):
        for i in range(layout.count()):
            item = layout.itemAt(i)
            if isinstance(item, QWidgetItem):
                item.widget().close()
            elif isinstance(item, QSpacerItem):
                continue
            else:
                self.clear(item.layout())
    '''

    def choose_type(self):
        # self.clear(self.main_vbox)
        type_ = self.sender().text()
        self.choosed.emit(type_)

    def resizeEvent(self, event):
        width = self.width()
        fited = width * 95 / 100
        self._center_area.setFixedWidth(fited)
        for frame in self.mid_frames:
            frame.setFixedWidth(fited)
    def initUi(self):
        self.paintArea = PaintArea()

        # 4
        self.shapeLabel = QLabel("形状: ")
        comboxItems = [
            ["Point", shape.Point],
            ["Line", shape.Line],
            ["Rectangle", shape.Rectangle],
            ["Ellipse", shape.Ellipse],
        ]
        self.shapeComboBox = QComboBox()
        for comboxItem in comboxItems:
            self.shapeComboBox.addItem(*comboxItem)
        # 连接
        self.shapeComboBox.activated.connect(self.paintArea.setShape)

        self.penColorLabel = QLabel("画笔颜色: ")
        self.penColorFrame = QFrame()
        self.penColorFrame.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.penColorFrame.setAutoFillBackground(True)
        self.penColorFrame.setPalette(QPalette(DefaultPenColor))
        self.penColorBtn = QPushButton("更改")
        self.penColorBtn.clicked.connect(self.setPenColor)

        self.penWidthLabel = QLabel("画笔宽度: ")
        self.penWidthSpinBox = QSpinBox()
        self.penWidthSpinBox.setRange(0, 20)
        self.penWidthSpinBox.setValue(DefaultPenSize)
        self.penWidthSpinBox.valueChanged.connect(self.setPenWidth)

        self.penStyleLabel = QLabel("画笔风格: ")
        self.penStyleComboBox = QComboBox()

        # TODO: functionlize
        styleItems = [
            ["SolidLine", int(Qt.SolidLine)],
            ["DashLine", int(Qt.DashLine)],
            ["DotLine", int(Qt.DotLine)],
            ["DashDotLine", int(Qt.DashDotLine)],
            ["DashDotDotLine", int(Qt.DashDotDotLine)],
            ["CustomDashLine", int(Qt.CustomDashLine)],
        ]
        for styleItem in styleItems:
            self.penStyleComboBox.addItem(*styleItem)

        self.penStyleComboBox.activated.connect(self.setPenStyle)

        self.penCapLabel = QLabel("画笔顶帽: ")
        self.penJoinLabel = QLabel("画笔连接点:  ")
        self.fillRuleLavel = QLabel("填充模式: ")
        self.fillRuleComboBox = QComboBox()
        self.fillRuleComboBox.addItem("Odd Even", Qt.OddEvenFill)
        self.fillRuleComboBox.addItem("Winding", Qt.WindingFill)
        self.fillRuleComboBox.activated.connect(self.setFillRule)

        self.brushColorLabel = QLabel("画刷颜色: ")
        self.brushColorFrame = QFrame()
        self.brushColorFrame.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.brushColorFrame.setAutoFillBackground(True)
        self.brushColorFrame.setPalette(QPalette(DefaultPenColor))
        self.brushColorBtn = QPushButton("更改")
        self.brushColorBtn.clicked.connect(self.setBrushColor)

        self.brushStyleLabel = QLabel("画刷风格: ")
        self.brushStyleComboBox = QComboBox()

        brushStyleItems = [
            ["NoBrush",
             int(Qt.NoBrush)], ["SolidPattern",
                                int(Qt.SolidPattern)],
            ["Dense1Pattern", int(Qt.Dense1Pattern)],
            ["Dense2Pattern", int(Qt.Dense2Pattern)],
            ["Dense3Pattern", int(Qt.Dense3Pattern)],
            ["Dense4Pattern", int(Qt.Dense4Pattern)],
            ["Dense5Pattern", int(Qt.Dense5Pattern)],
            ["Dense6Pattern", int(Qt.Dense6Pattern)],
            ["Dense7Pattern", int(Qt.Dense7Pattern)],
            ["HorPattern", int(Qt.HorPattern)],
            ["VerPattern", int(Qt.VerPattern)],
            ["CrossPattern", int(Qt.CrossPattern)],
            ["BDiagPattern", int(Qt.BDiagPattern)],
            ["FDiagPattern", int(Qt.FDiagPattern)],
            ["DiagCrossPattern", int(Qt.DiagCrossPattern)],
            ["LinearGradientPattern",
             int(Qt.LinearGradientPattern)],
            ["ConicalGradientPattern",
             int(Qt.ConicalGradientPattern)],
            ["RadialGradientPattern",
             int(Qt.RadialGradientPattern)],
            ["TexturePattern", int(Qt.TexturePattern)]
        ]
        for styleItem in brushStyleItems:
            self.brushStyleComboBox.addItem(*styleItem)

        self.brushStyleComboBox.activated.connect(self.setBrushStyle)

        self.selectPicBtn = QPushButton("选择图片")
        self.selectPicBtn.clicked.connect(self.openPic)

        # tag: create and set widgets
        self.cleanBtn = QPushButton("清屏")
        self.cleanBtn.clicked.connect(self.cleanAll)
        # 3

        # 2

        # left area gen
        self.rightLayout = QGridLayout()
        rightWidgets = [
            [self.shapeLabel, self.shapeComboBox],
            [self.penColorLabel, self.penColorFrame, self.penColorBtn],
            [self.penWidthLabel, self.penWidthSpinBox],
            [self.fillRuleLavel, self.fillRuleComboBox],
            [self.penStyleLabel, self.penStyleComboBox],
            [self.brushColorLabel, self.brushColorFrame, self.brushColorBtn],
            [self.brushStyleLabel, self.brushStyleComboBox],
            [self.cleanBtn],
            [self.selectPicBtn],
        ]
        # tag: add and show widgets
        for r in range(len(rightWidgets)):
            for c in range(len(rightWidgets[r])):
                self.rightLayout.addWidget(rightWidgets[r][c], r, c)
        # 1
        self.mainLayout = QHBoxLayout(self)
        self.mainLayout.addWidget(self.paintArea)
        self.mainLayout.addLayout(self.rightLayout)

        #
        self.mainLayout.setStretchFactor(self.paintArea, 1)
        self.mainLayout.setStretchFactor(self.rightLayout, 0)
Esempio n. 41
0
class Classification(QMainWindow):
    def __init__(self):
        super(Classification, self).__init__()
        self.setupUi(self)
        self.show()

    def setupUi(self, window):
        window.setObjectName("MainWindow")
        window.resize(758, 418)
        window.setMinimumSize(758, 418)
        self.centralWidget = QWidget(window)
        self.centralWidget.setObjectName("centralWidget")
        self.horizontalLayout = QHBoxLayout(self.centralWidget)
        self.horizontalLayout.setContentsMargins(11, 11, 11, 11)
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.sideBar = QWidget(self.centralWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.sideBar.sizePolicy().hasHeightForWidth())
        self.sideBar.setSizePolicy(sizePolicy)
        self.sideBar.setObjectName("sideBar")
        self.verticalLayout = QVBoxLayout(self.sideBar)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setAlignment(Qt.AlignTop)
        self.fromImage = TabButton(self.sideBar)
        self.fromImage.setObjectName("fromImage")
        self.verticalLayout.addWidget(self.fromImage)
        self.fromCamera = TabButton(self.sideBar)
        self.fromCamera.setObjectName("fromCamera")
        self.verticalLayout.addWidget(self.fromCamera)
        self.horizontalLayout.addWidget(self.sideBar)
        self.line = QFrame(self.centralWidget)
        self.line.setFrameShape(QFrame.VLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.horizontalLayout.addWidget(self.line)
        self.mainWindow = QWidget(self.centralWidget)

        self.mainLayout = QVBoxLayout(self.mainWindow)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(6)

        self.onImageSelect()

        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(5)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.mainWindow.sizePolicy().hasHeightForWidth())
        self.mainWindow.setSizePolicy(sizePolicy)
        self.mainWindow.setObjectName("mainWindow")
        self.horizontalLayout.addWidget(self.mainWindow)
        window.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(window)
        self.menuBar.setGeometry(QRect(0, 0, 758, 22))
        self.menuBar.setObjectName("menuBar")
        window.setMenuBar(self.menuBar)

        self.retranslateUi(window)
        QMetaObject.connectSlotsByName(window)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.fromImage.setText(_translate("MainWindow", "From Image"))
        self.fromCamera.setText(_translate("MainWindow", "Camera"))

    @pyqtSlot(bool, name='on_fromCamera_clicked')
    def onCameraSelect(self, checked=False):
        layout_utils.cleanLayout(self.mainLayout)
        self.mainLayout.addWidget(FromCameraWidget())

    @pyqtSlot(bool, name='on_fromImage_clicked')
    def onImageSelect(self, checked=False):
        layout_utils.cleanLayout(self.mainLayout)
        self.mainLayout.addWidget(FromImageWidget())
Esempio n. 42
0
class TVL(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self)
        self.capitalLog = []
        self.luckyLog = []
        self.unluckyLog = []
        self.lucky = []
        self.unlucky = []
        self.capital = []
        self.sitex = []
        self.sitey = []
        self.talent = []
        self.displayTarget = ""
        self.epochs = 0
        self.displayGrand = 0
        self.outdir = "file:///" + os.getcwd().replace('\\', '/') + "/data/"
        self.setWindowTitle('Talent vs Luck')
        self.setWindowIcon(QtGui.QIcon('title.ico'))
        self.resize(851, 535)
        self.setMinimumSize(851, 535)
        self.setMaximumSize(851, 535)
        self.gridLayoutWidget = QWidget(self)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 191, 511))
        self.gridLayout_2 = QGridLayout(self.gridLayoutWidget)
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
        self.M_lab = QLabel("地图规模", self.gridLayoutWidget)
        self.M_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.M_lab, 0, 0, 1, 1)
        self.T_avg = QComboBox(self.gridLayoutWidget)
        for i in range(1, 10):
            self.T_avg.addItem(str(i / 10))
        self.gridLayout_2.addWidget(self.T_avg, 5, 1, 1, 1)
        self.avg_lab = QLabel("talent均值", self.gridLayoutWidget)
        self.avg_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.avg_lab, 5, 0, 1, 1)
        self.T_std = QComboBox(self.gridLayoutWidget)
        for i in range(1, 10):
            self.T_std.addItem(str(i / 10))
        self.gridLayout_2.addWidget(self.T_std, 6, 1, 1, 1)
        self.std_lab = QLabel("talent标准差", self.gridLayoutWidget)
        self.std_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.std_lab, 6, 0, 1, 1)
        self.grand_lab = QLabel("图表粒度", self.gridLayoutWidget)
        self.grand_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.grand_lab, 7, 0, 1, 1)
        self.grand = QComboBox(self.gridLayoutWidget)
        for i in range(1, 5):
            self.grand.addItem(str(i * 10))
        self.gridLayout_2.addWidget(self.grand, 7, 1, 1, 1)
        self.luck = QComboBox(self.gridLayoutWidget)
        for i in range(1, 10):
            self.luck.addItem(str(i * 100))
        self.gridLayout_2.addWidget(self.luck, 2, 1, 1, 1)
        self.step = QComboBox(self.gridLayoutWidget)
        for i in range(1, 7):
            self.step.addItem(str(i * 50))
        self.gridLayout_2.addWidget(self.step, 4, 1, 1, 1)
        self.map = QComboBox(self.gridLayoutWidget)
        for i in range(1, 7):
            self.map.addItem(str(i * 100) + "x" + str(i * 100))
        self.gridLayout_2.addWidget(self.map, 0, 1, 1, 1)
        self.unluck = QComboBox(self.gridLayoutWidget)
        for i in range(1, 10):
            self.unluck.addItem(str(i * 100))
        self.gridLayout_2.addWidget(self.unluck, 3, 1, 1, 1)
        self.N_lab = QLabel("人数", self.gridLayoutWidget)
        self.N_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.N_lab, 1, 0, 1, 1)
        self.unluck_lab = QLabel("不幸事件", self.gridLayoutWidget)
        self.unluck_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.unluck_lab, 3, 0, 1, 1)
        self.luck_lab = QLabel("幸运事件", self.gridLayoutWidget)
        self.luck_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.luck_lab, 2, 0, 1, 1)
        self.s_lab = QLabel("迭代次数", self.gridLayoutWidget)
        self.s_lab.setAlignment(QtCore.Qt.AlignCenter)
        self.gridLayout_2.addWidget(self.s_lab, 4, 0, 1, 1)
        self.N = QComboBox(self.gridLayoutWidget)
        for i in range(1, 7):
            self.N.addItem(str(i * 500))
        self.gridLayout_2.addWidget(self.N, 1, 1, 1, 1)
        self.line = QFrame(self)
        self.line.setGeometry(QtCore.QRect(210, 10, 20, 511))
        self.line.setFrameShape(QFrame.VLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line_2 = QFrame(self)
        self.line_2.setGeometry(QtCore.QRect(340, 10, 20, 511))
        self.line_2.setFrameShape(QFrame.VLine)
        self.line_2.setFrameShadow(QFrame.Sunken)
        self.verticalLayoutWidget = QWidget(self)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(230, 10, 101, 511))
        self.verticalLayout_2 = QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.start = QPushButton("Start", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.start)
        self.TN = QPushButton("T-N", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.TN)
        self.LN = QPushButton("L-N", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.LN)
        self.CN = QPushButton("C-N", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.CN)
        self.CT = QPushButton("C-T", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.CT)
        self.TC = QPushButton("T-C", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.TC)
        self.LC = QPushButton("L-C", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.LC)
        self.CL = QPushButton("C-L", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.CL)
        self.UC = QPushButton("U-C", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.UC)
        self.CU = QPushButton("C-U", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.CU)
        self.CmaxTime = QPushButton("Cmax-Time", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.CmaxTime)
        self.CmaxEvent = QPushButton("Cmax-Event", self.verticalLayoutWidget)
        self.verticalLayout_2.addWidget(self.CmaxEvent)
        self.verticalLayoutWidget_2 = QWidget(self)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(
            360, 10, 471, 511))
        self.verticalLayout_3 = QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.slider = QSlider(self.verticalLayoutWidget_2)
        self.slider.setMinimum(0)
        self.slider.setOrientation(QtCore.Qt.Horizontal)
        self.verticalLayout_3.addWidget(self.slider)
        self.screen = QWebEngineView(self.verticalLayoutWidget_2)
        self.verticalLayout_3.addWidget(self.screen)
        self.start.clicked.connect(self.startAction)
        self.TN.clicked.connect(self.TNAction)
        self.LN.clicked.connect(self.LNAction)
        self.CN.clicked.connect(self.CNAction)
        self.CT.clicked.connect(self.CTAction)
        self.TC.clicked.connect(self.TCAction)
        self.LC.clicked.connect(self.LCAction)
        self.CL.clicked.connect(self.CLAction)
        self.UC.clicked.connect(self.UCAction)
        self.CU.clicked.connect(self.CUAction)
        self.CmaxTime.clicked.connect(self.CmaxTimeAction)
        self.CmaxEvent.clicked.connect(self.CmaxEventAction)
        self.slider.valueChanged[int].connect(self.sliderAction)
        self.TN.setEnabled(False)
        self.LN.setEnabled(False)
        self.CN.setEnabled(False)
        self.CT.setEnabled(False)
        self.TC.setEnabled(False)
        self.LC.setEnabled(False)
        self.CL.setEnabled(False)
        self.UC.setEnabled(False)
        self.CU.setEnabled(False)
        self.CmaxTime.setEnabled(False)
        self.CmaxEvent.setEnabled(False)
        self.slider.setEnabled(False)
        self.screen.setHtml("please set configuration")

    def sliderAction(self, value):
        self.slider.setValue(value)
        if self.displayTarget == "TN":
            self.screen.load(
                QtCore.QUrl(self.outdir + "TN" + str((value + 1) * 10) +
                            ".html"))
        elif self.displayTarget == "LN":
            self.screen.load(
                QtCore.QUrl(self.outdir + "LN" + str(value) + ".html"))
        elif self.displayTarget == "CN":
            self.screen.load(
                QtCore.QUrl(self.outdir + "CN" + str(value) + ".html"))
        elif self.displayTarget == "CT":
            self.screen.load(
                QtCore.QUrl(self.outdir + "CT" + str(value) + ".html"))
        elif self.displayTarget == "TC":
            self.screen.load(
                QtCore.QUrl(self.outdir + "TC" + str(value) + ".html"))
        elif self.displayTarget == "LC":
            self.screen.load(
                QtCore.QUrl(self.outdir + "LC" + str(value) + ".html"))
        elif self.displayTarget == "CL":
            self.screen.load(
                QtCore.QUrl(self.outdir + "CL" + str(value) + ".html"))
        elif self.displayTarget == "UC":
            self.screen.load(
                QtCore.QUrl(self.outdir + "UC" + str(value) + ".html"))
        elif self.displayTarget == "CU":
            self.screen.load(
                QtCore.QUrl(self.outdir + "CU" + str(value) + ".html"))

    def renderBar(self, source, xname, yname, times, path):
        for i in range(times):
            index = pd.cut(source[i], bins=self.displayGrand).categories.values
            index = [round(i.mid, 4) for i in index]
            bar = Bar(width=450, height=450, is_animation=False)
            bar.add(xname,
                    index,
                    pd.value_counts(source[i],
                                    bins=self.displayGrand,
                                    sort=False),
                    xaxis_name=xname,
                    yaxis_name=yname,
                    is_legend_show=False,
                    is_toolbox_show=False)
            bar.render("data/" + path + str(i) + ".html")

    def renderScatter(self, xname, yname, ax, ay, times, path, op):
        for i in range(times):
            sc = Scatter(width=450, height=450, is_animation=False)
            if op == 0:
                sc.add(xname,
                       ax[i],
                       ay[i],
                       xaxis_name=xname,
                       yaxis_name=yname,
                       is_legend_show=False,
                       is_toolbox_show=False)
            elif op == -1:
                sc.add(xname,
                       ax[i],
                       ay,
                       xaxis_name=xname,
                       yaxis_name=yname,
                       is_legend_show=False,
                       is_toolbox_show=False)
            else:
                sc.add(xname,
                       ax,
                       ay[i],
                       xaxis_name=xname,
                       yaxis_name=yname,
                       is_legend_show=False,
                       is_toolbox_show=False)
            sc.render("data/" + path + str(i) + ".html")

    def startAction(self):
        #init
        self.capitalLog = []
        self.luckyLog = []
        self.unluckyLog = []
        mapsize = int(self.map.currentText()[:3])
        num = int(self.N.currentText())
        lucknum = int(self.luck.currentText())
        unlucknum = int(self.unluck.currentText())
        self.epochs = int(self.step.currentText())
        self.displayGrand = int(self.grand.currentText())
        std = float(self.T_std.currentText())
        avg = float(self.T_avg.currentText())
        self.talent = np.random.normal(avg, std, num)
        self.capital = [10] * num
        self.sitex = np.random.uniform(0, mapsize, num)
        self.sitey = np.random.uniform(0, mapsize, num)
        self.lucky = [0] * num
        self.unlucky = [0] * num
        self.capitalLog.append(deepcopy(self.capital))
        self.luckyLog.append(deepcopy(self.lucky))
        self.unluckyLog.append(deepcopy(self.unlucky))
        #simulate
        for i in range(self.epochs):
            goodx = np.random.uniform(0, mapsize, lucknum)
            goody = np.random.uniform(0, mapsize, lucknum)
            badx = np.random.uniform(0, mapsize, unlucknum)
            bady = np.random.uniform(0, mapsize, unlucknum)
            for j in range(num):
                for k in range(lucknum):
                    disx = abs(goodx[k] - self.sitex[j])
                    disy = abs(goody[k] - self.sitey[j])
                    if (disx <= 2 or disx >= mapsize - 1) and (
                            disy <= 2 or disy >= mapsize - 1):
                        self.lucky[j] += 1
                        r = random.random()
                        if r < self.talent[j]:
                            self.capital[j] *= 2
                for k in range(unlucknum):
                    disx = abs(badx[k] - self.sitex[j])
                    disy = abs(bady[k] - self.sitey[j])
                    if (disx <= 2 or disx >= mapsize - 1) and (
                            disy <= 2 or disy >= mapsize - 1):
                        self.unlucky[j] += 1
                        self.capital[j] /= 2
            self.capitalLog.append(deepcopy(self.capital))
            self.luckyLog.append(deepcopy(self.lucky))
            self.unluckyLog.append(deepcopy(self.unlucky))
        if os.path.exists("./data") == False:
            os.mkdir("data")
        #draw TN and Cmax
        for i in [10, 20, 30, 40, 50]:
            index = pd.cut(self.talent, bins=i).categories.values
            index = [round(i.mid, 4) for i in index]
            bar = Bar(width=450, height=450, is_animation=False)
            bar.add("talent",
                    index,
                    pd.value_counts(self.talent, bins=i, sort=False),
                    xaxis_name="talent",
                    yaxis_name="individuals",
                    is_legend_show=False,
                    is_toolbox_show=False)
            bar.render("data/TN" + str(i) + ".html")
        cmax = np.argmax(self.capital)
        ctime = [k[cmax] for k in self.capitalLog]
        cstep = list(range(self.epochs + 1))
        line = Line(width=450, height=450, is_animation=False)
        line.add("captial",
                 cstep,
                 ctime,
                 xaxis_name="time",
                 yaxis_name="captial",
                 is_legend_show=False,
                 is_toolbox_show=False)
        line.render("data/CmaxTime.html")
        cevent = [0]
        for i in range(1, self.epochs + 1):
            cevent.append(
                (self.luckyLog[i][cmax] - self.luckyLog[i - 1][cmax]) -
                (self.unluckyLog[i][cmax] - self.unluckyLog[i - 1][cmax]))
        line = Line(width=450, height=450, is_animation=False)
        line.add("event",
                 cstep,
                 cevent,
                 xaxis_name="time",
                 yaxis_name="event",
                 is_legend_show=False,
                 is_toolbox_show=False)
        line.render("data/CmaxEvent.html")
        #draw others
        self.renderBar(self.luckyLog, "lucky", "individuals", self.epochs,
                       "LN")
        self.renderBar(self.capitalLog, "captial", "individuals", self.epochs,
                       "CN")
        self.renderScatter("captial", "talent", self.capitalLog, self.talent,
                           self.epochs, "CT", -1)
        self.renderScatter("talent", "captial", self.talent, self.capitalLog,
                           self.epochs, "TC", 1)
        self.renderScatter("lucky", "captial", self.luckyLog, self.capitalLog,
                           self.epochs, "LC", 0)
        self.renderScatter("captial", "lucky", self.capitalLog, self.luckyLog,
                           self.epochs, "CL", 0)
        self.renderScatter("unlucky", "captial", self.unluckyLog,
                           self.capitalLog, self.epochs, "UC", 0)
        self.renderScatter("captial", "unlucky", self.capitalLog,
                           self.unluckyLog, self.epochs, "CU", 0)
        self.TN.setEnabled(True)
        self.LN.setEnabled(True)
        self.CN.setEnabled(True)
        self.CT.setEnabled(True)
        self.TC.setEnabled(True)
        self.LC.setEnabled(True)
        self.CL.setEnabled(True)
        self.UC.setEnabled(True)
        self.CU.setEnabled(True)
        self.CmaxTime.setEnabled(True)
        self.CmaxEvent.setEnabled(True)
        self.screen.setHtml("finished")

    def displayInit(self, t, m, p):
        self.displayTarget = t
        self.slider.setEnabled(True)
        self.slider.setValue(0)
        self.slider.setMaximum(m)
        self.screen.load(QtCore.QUrl(self.outdir + p))

    def TNAction(self):
        self.displayInit("TN", 4, "TN10.html")

    def LNAction(self):
        self.displayInit("LN", self.epochs, "LN0.html")

    def CNAction(self):
        self.displayInit("CN", self.epochs, "CN0.html")

    def CTAction(self):
        self.displayInit("CT", self.epochs, "CT0.html")

    def TCAction(self):
        self.displayInit("TC", self.epochs, "TC0.html")

    def LCAction(self):
        self.displayInit("LC", self.epochs, "LC0.html")

    def CLAction(self):
        self.displayInit("CL", self.epochs, "CL0.html")

    def UCAction(self):
        self.displayInit("UC", self.epochs, "UC0.html")

    def CUAction(self):
        self.displayInit("CU", self.epochs, "CU0.html")

    def CmaxTimeAction(self):
        self.slider.setEnabled(False)
        self.slider.setValue(0)
        self.screen.load(QtCore.QUrl(self.outdir + "CmaxTime.html"))

    def CmaxEventAction(self):
        self.slider.setEnabled(False)
        self.slider.setValue(0)
        self.screen.load(QtCore.QUrl(self.outdir + "CmaxEvent.html"))
Esempio n. 43
0
    def __init__(self, config, querylist, mainwin, debug=True):
        QSplitter.__init__(self, None)
        self.debug = debug
        self.conf = config
        self.main_window = mainwin
        self.sql = querylist

        self.liststore = [
        ]  # gtk.ListStore[]         stores the contents of the grids
        self.listcols = [
        ]  # gtk.TreeViewColumn[][]  stores the columns in the grids

        self.MYSQL_INNODB = 2
        self.PGSQL = 3
        self.SQLITE = 4

        # create new db connection to avoid conflicts with other threads
        self.db = Database.Database(self.conf, sql=self.sql)
        self.cursor = self.db.cursor

        settings = {}
        settings.update(self.conf.get_db_parameters())
        settings.update(self.conf.get_import_parameters())
        settings.update(self.conf.get_default_paths())

        # text used on screen stored here so that it can be configured
        self.filterText = {
            'handhead': _('Hand Breakdown for all levels listed above')
        }

        filters_display = {
            "Heroes": True,
            "Sites": True,
            "Games": True,
            "Currencies": True,
            "Limits": True,
            "LimitSep": True,
            "LimitType": True,
            "Type": True,
            "Seats": True,
            "SeatSep": True,
            "Dates": True,
            "Groups": True,
            "GroupsAll": True,
            "Button1": True,
            "Button2": True
        }

        self.filters = Filters.Filters(self.db, display=filters_display)
        self.filters.registerButton1Name(_("Filters"))
        self.filters.registerButton1Callback(self.showDetailFilter)
        self.filters.registerButton2Name(_("Refresh Stats"))
        self.filters.registerButton2Callback(self.refreshStats)

        scroll = QScrollArea()
        scroll.setWidget(self.filters)

        # ToDo: store in config
        # ToDo: create popup to adjust column config
        # columns to display, keys match column name returned by sql, values in tuple are:
        #     is column displayed(summary then position), column heading, xalignment, formatting, celltype
        self.columns = self.conf.get_gui_cash_stat_params()

        # Detail filters:  This holds the data used in the popup window, extra values are
        # added at the end of these lists during processing
        #                  sql test,              screen description,        min, max
        self.handtests = [  # already in filter class : ['h.seats', 'Number of Players', 2, 10]
            ['gt.maxSeats', 'Size of Table', 2, 10],
            ['h.playersVpi', 'Players who VPI', 0, 10],
            ['h.playersAtStreet1', 'Players at Flop', 0, 10],
            ['h.playersAtStreet2', 'Players at Turn', 0, 10],
            ['h.playersAtStreet3', 'Players at River', 0, 10],
            ['h.playersAtStreet4', 'Players at Street7', 0, 10],
            ['h.playersAtShowdown', 'Players at Showdown', 0, 10],
            ['h.street0Raises', 'Bets to See Flop', 0, 5],
            ['h.street1Raises', 'Bets to See Turn', 0, 5],
            ['h.street2Raises', 'Bets to See River', 0, 5],
            ['h.street3Raises', 'Bets to See Street7', 0, 5],
            ['h.street4Raises', 'Bets to See Showdown', 0, 5]
        ]

        self.cardstests = [
            [Card.DATABASE_FILTERS['pair'],
             _('Pocket pairs')],
            [Card.DATABASE_FILTERS['suited'],
             _('Suited')],
            [
                Card.DATABASE_FILTERS['suited_connectors'],
                _('Suited connectors')
            ],
            [Card.DATABASE_FILTERS['offsuit'],
             _('Offsuit')],
            [
                Card.DATABASE_FILTERS['offsuit_connectors'],
                _('Offsuit connectors')
            ],
        ]
        self.stats_frame = None
        self.stats_vbox = None
        self.detailFilters = []  # the data used to enhance the sql select
        self.cardsFilters = []

        self.stats_frame = QFrame()
        self.stats_frame.setLayout(QVBoxLayout())

        self.stats_vbox = QSplitter(Qt.Vertical)
        self.stats_frame.layout().addWidget(self.stats_vbox)

        self.addWidget(scroll)
        self.addWidget(self.stats_frame)
        self.setStretchFactor(0, 0)
        self.setStretchFactor(1, 1)

        # Make sure Hand column is not displayed.
        hand_column = (x for x in self.columns if x[0] == 'hand').next()
        hand_column[colshowsumm] = hand_column[colshowposn] = False

        # If rfi and steal both on for summaries, turn rfi off.
        rfi_column = (x for x in self.columns if x[0] == 'rfi').next()
        steals_column = (x for x in self.columns if x[0] == 'steals').next()
        if rfi_column[colshowsumm] and steals_column[colshowsumm]:
            rfi_column[colshowsumm] = False

        # If rfi and steal both on for position breakdowns, turn steals off.
        if rfi_column[colshowposn] and steals_column[colshowposn]:
            steals_column[colshowposn] = False
Esempio n. 44
0
class MainWindow(object):
    SCREEN_HEIGHT = 600
    SCREEN_WIDTH = 600

    def __init__(self):
        self.app = QApplication([])
        self.window = QMainWindow()
        self.window.setFixedSize(self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
        self.window.setWindowTitle('Dragon Quest III: Heavenly Flight')
        self.icon = QtGui.QIcon()
        self.icon.addPixmap(
            QtGui.QPixmap(os.path.join(THIS_FILEPATH, "ico.ico")),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.window.setWindowIcon(self.icon)

        self.title_container = QLabel(self.window)
        self.title_container.setGeometry(
            QtCore.QRect(0, 0, self.SCREEN_WIDTH, 30))
        self.title_container.setStyleSheet("background-color:black;")

        self.title_label = QLabel("Dragon Quest III: Heavenly Flight",
                                  self.window)
        self.title_label.setGeometry(QtCore.QRect(0, 0, self.SCREEN_WIDTH, 30))
        self.title_label.setAlignment(QtCore.Qt.AlignCenter)
        self.title_label.setStyleSheet("font-size:18px;")

        self.title_label_border = QFrame(self.window)
        self.title_label_border.setGeometry(
            QtCore.QRect(-10, -10, self.SCREEN_WIDTH + 20, 40))
        self.title_label_border.setStyleSheet(
            "border:2px solid rgb(0, 0, 0); ")

        self.rom_label = QLabel("Input ROM path:", self.window)
        self.rom_label.setGeometry(QtCore.QRect(10, 40, 120, 30))
        self.rom_label.setToolTip('Choose ROM path:')

        self.rom_label_input = QLineEdit("", self.window)
        self.rom_label_input.setGeometry(QtCore.QRect(140, 40, 360, 30))
        self.rom_label_input.setToolTip('Choose ROM path:')
        self.rom_label_input.setText("")

        self.rom_button = QPushButton("Browse", self.window)
        self.rom_button.setGeometry(QtCore.QRect(510, 40, 80, 30))
        self.rom_button.clicked.connect(self.rom_input_click)

        self.seed_label = QLabel("Seed:", self.window)
        self.seed_label.setGeometry(QtCore.QRect(10, 80, 120, 30))
        self.seed_label.setToolTip(
            'Choose a seed number. Blank will generate a new random one.')

        self.seed_label_input = QLineEdit("", self.window)
        self.seed_label_input.setGeometry(QtCore.QRect(140, 80, 360, 30))
        self.seed_label_input.setToolTip(
            'Choose a seed number. Blank will generate a new random one.')
        self.seed_label_input.setText("")
        self.onlyInt = QIntValidator()
        self.seed_label_input.setValidator(self.onlyInt)

        self.key_item_chests_checkbox = QCheckBox(
            "Place Key Items in chests only", self.window)
        self.key_item_chests_checkbox.setGeometry(
            QtCore.QRect(10, 120, 350, 30))
        self.key_item_chests_checkbox.setToolTip(
            'Checked: Key Items will only be placed in chests. Searchable locations (visible and invisible) and NPC events will not have keys.\nUnchecked: Key Items can be placed anywhere.\nBoth options adhere to having all checks with logical requirements.\nTiering has no impact on Key Item placement.'
        )
        self.key_item_chests_checkbox.setChecked(True)

        self.reward_tiering_checkbox = QCheckBox("Reward tiering", self.window)
        self.reward_tiering_checkbox.setGeometry(QtCore.QRect(
            10, 150, 350, 30))
        self.reward_tiering_checkbox.setToolTip(
            'Checked: Rewards are placed with collectibles of increasing value throughout the game, with a small chance of higher tier goods randomly appearing anywhere.\nUnchecked: All rewards have completely random value goods.\nBoth options adhere to a placement average system, controlling how often items appear throughout the seed.\nRewards can be placed with higher or lower tiers than the check tier by design, but are usually +/- 1 with tiering.'
        )
        self.reward_tiering_checkbox.setChecked(True)

        self.shop_tiering_checkbox = QCheckBox("Shop tiering", self.window)
        self.shop_tiering_checkbox.setGeometry(QtCore.QRect(10, 180, 350, 30))
        self.shop_tiering_checkbox.setToolTip(
            'Checked: Shops are placed with wares of increasing value throughout the game.\nUnchecked: All shops have randomly assigned wares of any value.\nBoth options do not adhere to a placement average system, where different shops may have similar items.\nWares can be placed with higher or lower tiers than the shop tier by design, but are usually +/- 1 with tiering.'
        )
        self.shop_tiering_checkbox.setChecked(True)

        self.shop_tiering_checkbox = QCheckBox("Shop tiering", self.window)
        self.shop_tiering_checkbox.setGeometry(QtCore.QRect(10, 180, 350, 30))
        self.shop_tiering_checkbox.setToolTip(
            'Checked: Shops are placed with wares of increasing value throughout the game.\nUnchecked: All shops have randomly assigned wares of any value.\nBoth options do not adhere to a placement average system, where different shops may have similar items.\nWares can be placed with higher or lower tiers than the shop tier by design, but are usually +/- 1 with tiering.'
        )
        self.shop_tiering_checkbox.setChecked(True)

        self.starting_locations_label = QLabel("Starting locations:",
                                               self.window)
        self.starting_locations_label.setGeometry(
            QtCore.QRect(389, 160, 200, 30))
        self.starting_locations_label.setToolTip(
            '1: Player starts in Aliahan.\n2-3: Player starts in Aliahan and is given an extra 1-2 random warp locations.'
        )

        self.starting_locations_combobox = QComboBox(self.window)
        self.starting_locations_combobox.setGeometry(
            QtCore.QRect(540, 160, 40, 30))
        self.starting_locations_combobox.setToolTip(
            '1: Player starts in Aliahan.\n2-3: Player starts in Aliahan and is given an extra 1-2 random warp locations.'
        )
        self.starting_locations_combobox.addItem("1")
        self.starting_locations_combobox.addItem("2")
        self.starting_locations_combobox.addItem("3")

        self.exp_multiplier_label = QLabel("EXP multiplier:", self.window)
        self.exp_multiplier_label.setGeometry(QtCore.QRect(413, 200, 200, 30))
        self.exp_multiplier_label.setToolTip('EXP multiplier settings.')

        self.exp_multiplier_combobox = QComboBox(self.window)
        self.exp_multiplier_combobox.setGeometry(QtCore.QRect(
            540, 200, 40, 30))
        self.exp_multiplier_combobox.setToolTip('EXP multiplier settings.')
        self.exp_multiplier_combobox.addItem("4")
        self.exp_multiplier_combobox.addItem("2")
        self.exp_multiplier_combobox.addItem("1")

        self.small_medal_count_label = QLabel("Small Medal count:",
                                              self.window)
        self.small_medal_count_label.setGeometry(
            QtCore.QRect(380, 120, 200, 30))
        self.small_medal_count_label.setToolTip(
            'Number of Small Medals to place in the world. Only 12 Small Medals are required for all rewards.\nMinimum amount is 0, and maximum amount is 50.'
        )

        self.small_medal_count_input = QLineEdit("15", self.window)
        self.small_medal_count_input.setGeometry(QtCore.QRect(
            540, 120, 40, 30))
        self.small_medal_count_input.setValidator(self.onlyInt)
        self.small_medal_count_input.setToolTip(
            'Number of Small Medals to place in the world. Only 12 Small Medals are required for all rewards.\nMinimum amount is 0, and maximum amount is 50.'
        )

        self.generate_button = QPushButton("Generate", self.window)
        self.generate_button.setGeometry(QtCore.QRect(10, 240, 580, 30))
        self.generate_button.clicked.connect(self.generate)

        self.log_header_label = QLabel("Console log:", self.window)
        self.log_header_label.setGeometry(QtCore.QRect(10, 280, 90, 30))

        self.log_output = QTextEdit(self.window)
        self.log_output.setGeometry(QtCore.QRect(10, 320, 580, 200))
        # self.log_output = self.set_white(self.log_output)
        self.log_output.verticalScrollBar().setValue(
            self.log_output.verticalScrollBar().minimum())

        self.log_output_thread = LogThread(self.window)
        self.log_output_thread.log.connect(self.update_log_text)
        # self.log_output_thread.started.connect(lambda: self.update_log('start'))

        self.log_clear_button = QPushButton("Clear Log", self.window)
        self.log_clear_button.setGeometry(QtCore.QRect(10, 540, 100, 30))
        self.log_clear_button.clicked.connect(self.clear_log)

        self.open_dir_button = QPushButton("Open Output Folder", self.window)
        self.open_dir_button.setGeometry(QtCore.QRect(120, 540, 180, 30))
        self.open_dir_button.clicked.connect(self.open_output_folder)

        self.github_label = QLabel("Link to GitHub", self.window)
        urlLink = "<a href=\'https://github.com/cleartonic/dq3hf'style=\"color: #13bbba;\"><b>Link to GitHub</b></a>"
        self.github_label.setText(urlLink)
        self.github_label.setGeometry(QtCore.QRect(465, 530, 180, 30))
        self.github_label.setAlignment(QtCore.Qt.AlignBottom)
        self.github_label.setAlignment(QtCore.Qt.AlignLeft)
        self.github_label.setOpenExternalLinks(True)
        self.github_label.setStyleSheet("font-size:18px")

        self.tw_label = QLabel("Link to GitHub", self.window)
        urlLink = "<a href=\'https://twitter.com/cleartonic'style=\"color: #665ae8;\"><b>@cleartonic</b></a>"
        self.tw_label.setText(urlLink)
        self.tw_label.setGeometry(QtCore.QRect(487, 560, 180, 30))
        self.tw_label.setAlignment(QtCore.Qt.AlignBottom)
        self.tw_label.setAlignment(QtCore.Qt.AlignLeft)
        self.tw_label.setOpenExternalLinks(True)
        self.tw_label.setStyleSheet("font-size:18px;")

        # Final settings
        self.app.setStyle('Fusion')
        self.app.setFont(QtGui.QFont("Segoe UI", 12))

        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(53, 53, 53))
        palette.setColor(QPalette.WindowText, QColor(255, 255, 255))
        palette.setColor(QPalette.Base, QColor(25, 25, 25))
        palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
        palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 255))
        palette.setColor(QPalette.ToolTipText, QColor(255, 255, 255))
        palette.setColor(QPalette.Text, QColor(255, 255, 255))
        palette.setColor(QPalette.Button, QColor(53, 53, 53))
        palette.setColor(QPalette.ButtonText, QColor(255, 255, 255))
        palette.setColor(QPalette.BrightText, QColor(120, 120, 0))
        palette.setColor(QPalette.Link, QColor(42, 130, 218))
        palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        palette.setColor(QPalette.HighlightedText, QColor(0, 0, 0))
        self.app.setPalette(palette)

    def update_log(self, text):
        self.log_output_thread.setText(text)
        self.log_output_thread.start()

    def update_log_text(self, val):
        self.log_output.append(str(val))

    def clear_log(self, message):
        self.log_output.setText("")

    def open_output_folder(self):
        os.startfile(os.path.join(THIS_FILEPATH, 'output'))

    def rom_input_click(self):
        dialog = QFileDialog()
        new_file = dialog.getOpenFileName(None,
                                          "Select video",
                                          "",
                                          filter="sfc (*.sfc);;smc (*.smc)")
        if not new_file[0]:
            self.update_log_text(
                "No file chosen. Generation will not occur until a file is chosen."
            )
        else:
            self.rom_label_input.setText(new_file[0])

    def generate(self):
        # parse configs into dict

        if self.rom_label_input.text() != '' or DEV_OVERRIDE:
            # if DEV_OVERRIDE:
            #     self.rom_label_input.setText(DEV_ROM_PATH)

            try:
                try:
                    medal_parse = int(self.small_medal_count_input.text())
                    if medal_parse < 0:
                        medal_parse = 0
                    if medal_parse > 50:
                        medal_parse = 50
                except:
                    medal_parse = 12

                if self.seed_label_input.text():
                    SEED_NUM = int(self.seed_label_input.text())
                else:
                    SEED_NUM = random.randint(1, 1000000)

                seed_config = {
                    'starting_areas': ['Aliahan'],
                    'place_keys_in_chests_only':
                    self.key_item_chests_checkbox.isChecked(),
                    'small_medal_count':
                    medal_parse,
                    'reward_tiering':
                    self.reward_tiering_checkbox.isChecked(),
                    'shop_tiering':
                    self.shop_tiering_checkbox.isChecked(),
                    'starting_locations':
                    self.starting_locations_combobox.currentText(),
                    'exp_multiplier':
                    self.exp_multiplier_combobox.currentText(),
                    'seed_num':
                    SEED_NUM
                }

                self.update_log_text("Beginning seed generation...")
                self.update_log_text("Seed number %s..." % SEED_NUM)

                logging.info("Seed number: %s" % SEED_NUM)
                random.seed(SEED_NUM)
                self.world = World(random, seed_config)

                try:
                    self.world.generate_seed()
                    logging.info("\n\n\n")
                    #                    logging.info(self.world.spoiler_log)

                    self.update_log_text(
                        "Finished seed creation, patching ROM...")

                    self.patch_rom()

                except Exception as e:
                    logging.info(
                        "Seed resulted in error. Seed was not generated: %s" %
                        e)
                    self.update_log(
                        "Seed resulted in error. Seed was not generated: %s" %
                        e)

            except Exception as e:
                logging.info("Program error %s" % e)
                self.update_log("Program error %s" % e)

        else:
            self.update_log_text(
                "No file chosen. Generation will not occur until a file is chosen."
            )

    def patch_rom(self):

        try:

            new_rom_path = os.path.join(THIS_FILEPATH, 'tmp',
                                        "dq3_%s.sfc" % self.world.seed_num)
            #            logging.info(new_rom_path)
            #            logging.info(self.rom_label_input.text())
            shutil.copy(self.rom_label_input.text(), new_rom_path)

            sh_calls = [
                "%s" % os.path.join(THIS_FILEPATH, 'asar', 'asar.exe'),
                "--fix-checksum=off",
                os.path.join("asar", "patch.asm"), new_rom_path
            ]
            subprocess.call(sh_calls)

            if DEV_OVERRIDE:
                sh_calls = [
                    "%s" % os.path.join(THIS_FILEPATH, 'asar', 'asar.exe'),
                    "--fix-checksum=off",
                    os.path.join("asar", "patch2.asm"), new_rom_path
                ]
                subprocess.call(sh_calls)

            new_new_rom_path = os.path.join(THIS_FILEPATH, 'output',
                                            os.path.basename(new_rom_path))
            #            logging.info(new_rom_path)
            shutil.move(new_rom_path, new_new_rom_path)
            try:
                os.remove(os.path.join(THIS_FILEPATH, 'tmp', 'patch_r.asm'))
            except Exception as e:
                logging.info("Could not remove files from tmp dir: %s" % e)

            logging.info("File %s successfully patched & created! " %
                         (new_new_rom_path))
            self.update_log_text("File %s successfully patched & created! " %
                                 (new_new_rom_path))
        except Exception as e:
            logging.info(
                "File %s was NOT successfully patched & created: %s " %
                (new_rom_path, e))
            self.update_log_text(
                "File %s was NOT successfully patched & created: %s " %
                (new_rom_path, e))
Esempio n. 45
0
    def __init__(self, persepolis_setting):
        super().__init__()
        self.persepolis_setting = persepolis_setting
        icons = ':/' + str(persepolis_setting.value('settings/icons')) + '/'

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # set ui direction
        ui_direction = self.persepolis_setting.value('ui_direction')

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)

# window
        self.setMinimumSize(QtCore.QSize(595, 284))

        self.setWindowIcon(
            QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg')))
        self.setWindowTitle(
            QCoreApplication.translate("progress_ui_tr",
                                       "Persepolis Download Manager"))

        verticalLayout = QVBoxLayout(self)

        # progress_tabWidget
        self.progress_tabWidget = QTabWidget(self)

        # information_tab
        self.information_tab = QWidget()
        information_verticalLayout = QVBoxLayout(self.information_tab)

        # link_label
        self.link_label = QLabel(self.information_tab)
        information_verticalLayout.addWidget(self.link_label)

        # status_label
        self.status_label = QLabel(self.information_tab)
        information_verticalLayout.addWidget(self.status_label)

        # downloaded_label
        self.downloaded_label = QLabel(self.information_tab)
        information_verticalLayout.addWidget(self.downloaded_label)

        # rate_label
        self.rate_label = QLabel(self.information_tab)
        information_verticalLayout.addWidget(self.rate_label)

        # time_label
        self.time_label = QLabel(self.information_tab)
        information_verticalLayout.addWidget(self.time_label)

        # connections_label
        self.connections_label = QLabel(self.information_tab)
        information_verticalLayout.addWidget(self.connections_label)

        # add information_tab to progress_tabWidget
        self.progress_tabWidget.addTab(self.information_tab, "")

        # options_tab
        self.options_tab = QWidget()
        options_tab_horizontalLayout = QHBoxLayout(self.options_tab)
        options_tab_horizontalLayout.setContentsMargins(11, 11, 11, 11)

        # limit_checkBox
        self.limit_checkBox = QCheckBox(self.options_tab)

        limit_verticalLayout = QVBoxLayout()
        limit_verticalLayout.addWidget(self.limit_checkBox)

        # limit_frame
        self.limit_frame = QFrame(self.options_tab)
        self.limit_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.limit_frame.setFrameShadow(QtWidgets.QFrame.Raised)
        limit_frame_verticalLayout = QVBoxLayout(self.limit_frame)
        limit_frame_horizontalLayout = QHBoxLayout()

        # limit_spinBox
        self.limit_spinBox = QDoubleSpinBox(self.options_tab)
        self.limit_spinBox.setMinimum(1)
        self.limit_spinBox.setMaximum(1023)
        limit_frame_horizontalLayout.addWidget(self.limit_spinBox)

        # limit_comboBox
        self.limit_comboBox = QComboBox(self.options_tab)
        self.limit_comboBox.addItem("")
        self.limit_comboBox.addItem("")

        limit_frame_horizontalLayout.addWidget(self.limit_comboBox)

        # limit_pushButton
        self.limit_pushButton = QPushButton(self.options_tab)

        limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout)
        limit_frame_verticalLayout.addWidget(self.limit_pushButton)

        limit_verticalLayout.addWidget(self.limit_frame)

        limit_verticalLayout.setContentsMargins(11, 11, 11, 11)

        options_tab_horizontalLayout.addLayout(limit_verticalLayout)

        # after_checkBox
        self.after_checkBox = QCheckBox(self.options_tab)

        after_verticalLayout = QVBoxLayout()
        after_verticalLayout.addWidget(self.after_checkBox)

        # after_frame
        self.after_frame = QFrame(self.options_tab)
        self.after_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.after_frame.setFrameShadow(QtWidgets.QFrame.Raised)

        after_frame_verticalLayout = QVBoxLayout(self.after_frame)

        # after_comboBox
        self.after_comboBox = QComboBox(self.options_tab)
        self.after_comboBox.addItem("")

        after_frame_verticalLayout.addWidget(self.after_comboBox)

        # after_pushButton
        self.after_pushButton = QPushButton(self.options_tab)
        after_frame_verticalLayout.addWidget(self.after_pushButton)

        after_verticalLayout.addWidget(self.after_frame)

        after_verticalLayout.setContentsMargins(11, 11, 11, 11)
        options_tab_horizontalLayout.addLayout(after_verticalLayout)

        self.progress_tabWidget.addTab(self.options_tab, "")

        verticalLayout.addWidget(self.progress_tabWidget)

        # download_progressBar
        self.download_progressBar = QProgressBar(self)
        verticalLayout.addWidget(self.download_progressBar)

        # buttons
        button_horizontalLayout = QHBoxLayout()
        button_horizontalLayout.addStretch(1)

        # resume_pushButton
        self.resume_pushButton = QPushButton(self)
        self.resume_pushButton.setIcon(QIcon(icons + 'play'))
        button_horizontalLayout.addWidget(self.resume_pushButton)

        # pause_pushButton
        self.pause_pushButton = QtWidgets.QPushButton(self)
        self.pause_pushButton.setIcon(QIcon(icons + 'pause'))
        button_horizontalLayout.addWidget(self.pause_pushButton)

        # stop_pushButton
        self.stop_pushButton = QtWidgets.QPushButton(self)
        self.stop_pushButton.setIcon(QIcon(icons + 'stop'))
        button_horizontalLayout.addWidget(self.stop_pushButton)

        verticalLayout.addLayout(button_horizontalLayout)

        self.progress_tabWidget.setCurrentIndex(0)
        # labels
        self.link_label.setText(
            QCoreApplication.translate("progress_ui_tr", "Link :"))
        self.status_label.setText(
            QCoreApplication.translate("progress_ui_tr", "Status : "))
        self.downloaded_label.setText(
            QCoreApplication.translate("progress_ui_tr", "Downloaded :"))
        self.rate_label.setText(
            QCoreApplication.translate("progress_ui_tr", "Transfer rate : "))
        self.time_label.setText(
            QCoreApplication.translate("progress_ui_tr",
                                       "Estimated time left :"))
        self.connections_label.setText(
            QCoreApplication.translate("progress_ui_tr",
                                       "Number of connections : "))
        self.progress_tabWidget.setTabText(
            self.progress_tabWidget.indexOf(self.information_tab),
            QCoreApplication.translate("progress_ui_tr",
                                       "Download information"))
        self.limit_checkBox.setText(
            QCoreApplication.translate("progress_ui_tr", "Limit Speed"))
        self.after_checkBox.setText(
            QCoreApplication.translate("progress_ui_tr", "After download"))
        self.limit_comboBox.setItemText(
            0, QCoreApplication.translate("progress_ui_tr", "KB/S"))
        self.limit_comboBox.setItemText(
            1, QCoreApplication.translate("progress_ui_tr", "MB/S"))
        self.limit_pushButton.setText(
            QCoreApplication.translate("progress_ui_tr", "Apply"))

        self.after_comboBox.setItemText(
            0, QCoreApplication.translate("progress_ui_tr", "Shut Down"))

        self.progress_tabWidget.setTabText(
            self.progress_tabWidget.indexOf(self.options_tab),
            QCoreApplication.translate("progress_ui_tr", "Download Options"))
        self.resume_pushButton.setText(
            QCoreApplication.translate("progress_ui_tr", "Resume"))
        self.pause_pushButton.setText(
            QCoreApplication.translate("progress_ui_tr", "Pause"))
        self.stop_pushButton.setText(
            QCoreApplication.translate("progress_ui_tr", "Stop"))
        self.after_pushButton.setText(
            QCoreApplication.translate("progress_ui_tr", "Apply"))
Esempio n. 46
0
class MainWindowUi(QMainWindow):
    """Main Window"""
    def __init__(self, lang, translator):
        super().__init__()
        # Init
        self.lang = lang
        self._translateanslator = translator
        self._translate = QApplication.translate
        self.window_body = QWidget(self)
        self.process_type = QGroupBox(self.window_body)
        self.btn_fw = QRadioButton(self.process_type)
        self.btn_nonarb = QRadioButton(self.process_type)
        self.btn_vendor = QRadioButton(self.process_type)
        self.btn_fwless = QRadioButton(self.process_type)
        self.frame = QFrame(self.window_body)
        self.btn_select = QPushButton(self.frame)
        self.btn_url = QPushButton(self.frame)
        self.btn_create = QPushButton(self.frame)
        self.menubar = QMenuBar(self)
        self.status_box = QTextEdit(self.window_body)
        self.groupbox_drop = DropSpace(self.window_body, self.status_box,
                                       self._translate)
        self.label_drop = QLabel(self.groupbox_drop)
        self.progress_bar = QProgressBar(self.window_body)
        self.menu_file = QMenu(self.menubar)
        self.statusbar = QStatusBar(self)
        self.menu_language = QMenu(self.menubar)
        self.menu_help = QMenu(self.menubar)
        self.action_open_zip = QAction(self)
        self.action_open_remote_zip = QAction(self)
        self.action_quit = QAction(self)
        # languages
        self.action_language_sq = QAction(self)
        self.action_language_ar = QAction(self)
        self.action_language_ca = QAction(self)
        self.action_language_zh_CN = QAction(self)
        self.action_language_hr = QAction(self)
        self.action_language_cs = QAction(self)
        self.action_language_nl = QAction(self)
        self.action_language_en = QAction(self)
        self.action_language_fr = QAction(self)
        self.action_language_de = QAction(self)
        self.action_language_el = QAction(self)
        self.action_language_hi = QAction(self)
        self.action_language_id = QAction(self)
        self.action_language_it = QAction(self)
        self.action_language_fa = QAction(self)
        self.action_language_ms = QAction(self)
        self.action_language_pl = QAction(self)
        self.action_language_pt_BR = QAction(self)
        self.action_language_ro = QAction(self)
        self.action_language_ru = QAction(self)
        self.action_language_sl = QAction(self)
        self.action_language_es_ES = QAction(self)
        self.action_language_tr = QAction(self)
        self.action_language_uk = QAction(self)
        self.action_language_vi = QAction(self)
        self.action_donate = QAction(self)
        self.action_about = QAction(self)
        self.action_report_bug = QAction(self)
        self.action_website = QAction(self)
        # vars
        self.filepath = None
        self.filename = ''
        # setup
        self.setup_ui()
        self.setWindowIcon(QIcon(f'{current_dir}/icon.png'))
        self.center()
        adjust_layout_direction(self, lang)
        self.show()

    def setup_ui(self):
        """
        setup window ui
        """
        # Main Window
        self.setObjectName("main_window")
        self.setEnabled(True)
        self.resize(600, 400)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QSize(600, 400))
        self.setMaximumSize(QSize(600, 400))
        self.window_body.setObjectName("window_body")
        self.setCentralWidget(self.window_body)
        # GroupBox: process_type
        self.process_choose()
        # GroupBox: Drop files
        self.file_dropper()
        # Frame: Status
        self.status_frame()
        # Menubar
        self.menu_bar()
        # UI Strings
        self.re_translate_ui()
        QMetaObject.connectSlotsByName(self)

    def process_choose(self):
        """
        GroupBox: process_type
        """
        self.process_type.setGeometry(QRect(10, 20, 250, 140))
        self.process_type.setObjectName("process_type")
        self.btn_fw.setGeometry(QRect(10, 20, 160, 30))
        self.btn_fw.setObjectName("btn_fw")
        self.btn_nonarb.setGeometry(QRect(10, 50, 160, 30))
        self.btn_nonarb.setObjectName("btn_nonarb")
        self.btn_vendor.setGeometry(QRect(10, 80, 160, 30))
        self.btn_vendor.setObjectName("btn_vendor")
        self.btn_fwless.setGeometry(QRect(10, 110, 160, 30))
        self.btn_fwless.setObjectName("btn_fwless")
        # Actions
        self.btn_fw.setChecked(True)

    def file_dropper(self):
        """
        GroupBox: Drop files
        """
        self.groupbox_drop.setGeometry(QRect(270, 20, 320, 140))
        self.groupbox_drop.setObjectName("groupbox_drop")
        self.groupbox_drop.setAcceptDrops(True)
        self.label_drop.setGeometry(QRect(0, 30, 320, 111))
        # self.label_drop.setFrameShape(QFrame.Box)
        # self.label_drop.setFrameShadow(QFrame.Sunken)
        # self.label_drop.setLineWidth(2)
        self.label_drop.setAlignment(Qt.AlignCenter)
        self.label_drop.setObjectName("label_drop")

    def status_frame(self):
        """
        Frame: Status
        """
        self.frame.setGeometry(QRect(10, 170, 580, 80))
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.btn_select.setGeometry(QRect(125, 20, 105, 35))
        self.btn_select.setObjectName("btn_select")
        self.btn_select.setStatusTip("action_open_zip_tip")
        self.btn_url.setGeometry(QRect(240, 20, 105, 35))
        self.btn_url.setObjectName("btn_url")
        self.btn_url.setStatusTip("action_zip_url_tip")
        self.btn_create.setGeometry(QRect(355, 20, 105, 35))
        self.btn_create.setObjectName("btn_create")
        self.btn_create.setStatusTip("btn_create_tip")
        self.status_box.setGeometry(QRect(10, 250, 580, 40))
        self.status_box.setObjectName("status_box")
        # self.status_box.setFrameShape(QFrame.Box)
        # self.status_box.setFrameShadow(QFrame.Sunken)
        self.status_box.setReadOnly(True)
        self.status_box.setOverwriteMode(True)
        self.status_box.setObjectName("status_box")
        self.progress_bar.setGeometry(QRect(10, 300, 580, 40))
        self.progress_bar.setObjectName("progress_bar")
        self.progress_bar.setValue(0)

        # Action
        self.btn_select.clicked.connect(self.select_file)
        self.btn_url.clicked.connect(self.enter_url)
        self.btn_create.clicked.connect(self.create_zip)

    def menu_bar(self):
        """
        Menubar
        """
        self.menubar.setGeometry(QRect(0, 0, 600, 32))
        self.menubar.setObjectName("menubar")
        self.menu_file.setObjectName("menu_file")
        self.menu_language.setObjectName("menu_language")
        self.menu_help.setObjectName("menu_help")
        self.setMenuBar(self.menubar)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.action_open_zip.setObjectName("action_open_zip")
        self.action_open_zip.setStatusTip("action_open_zip_tip")
        self.action_open_remote_zip.setObjectName("action_open_remote_zip")
        self.action_open_remote_zip.setStatusTip("action_open_remote_zip")
        self.action_quit.setObjectName("action_quit")
        self.action_quit.setStatusTip("action_quit_tip")
        self.action_language_sq.setObjectName("action_language_sq")
        self.action_language_ar.setObjectName("action_language_ar")
        self.action_language_ca.setObjectName("action_language_ca")
        self.action_language_zh_CN.setObjectName("action_language_zh_CN")
        self.action_language_hr.setObjectName("action_language_hr")
        self.action_language_cs.setObjectName("action_language_cs")
        self.action_language_nl.setObjectName("action_language_nl")
        self.action_language_en.setObjectName("action_language_en")
        self.action_language_fr.setObjectName("action_language_fr")
        self.action_language_de.setObjectName("action_language_de")
        self.action_language_el.setObjectName("action_language_el")
        self.action_language_hi.setObjectName("action_language_hi")
        self.action_language_id.setObjectName("action_language_id")
        self.action_language_it.setObjectName("action_language_it")
        self.action_language_ms.setObjectName("action_language_ms")
        self.action_language_fa.setObjectName("action_language_fa")
        self.action_language_pl.setObjectName("action_language_pl")
        self.action_language_pt_BR.setObjectName("action_language_pt_BR")
        self.action_language_ro.setObjectName("action_language_ro")
        self.action_language_ru.setObjectName("action_language_ru")
        self.action_language_sl.setObjectName("action_language_sl")
        self.action_language_es_ES.setObjectName("action_language_es_ES")
        self.action_language_tr.setObjectName("action_language_tr")
        self.action_language_uk.setObjectName("action_language_uk")
        self.action_language_vi.setObjectName("action_language_vi")
        self.action_report_bug.setObjectName("action_report_bug")
        self.action_report_bug.setStatusTip("action_report_bug_tip")
        self.action_donate.setObjectName("action_donate")
        self.action_donate.setStatusTip("action_donate_tip")
        self.action_about.setObjectName("action_about")
        self.action_about.setStatusTip("action_about_tip")
        self.action_website.setObjectName("action_website")
        self.action_website.setStatusTip("action_website_tip")
        self.menu_file.addActions([
            self.action_open_zip, self.action_open_remote_zip, self.action_quit
        ])
        self.menu_language.addActions([
            self.action_language_sq, self.action_language_ar,
            self.action_language_ca, self.action_language_zh_CN,
            self.action_language_hr, self.action_language_cs,
            self.action_language_nl, self.action_language_en,
            self.action_language_fr, self.action_language_de,
            self.action_language_el, self.action_language_hi,
            self.action_language_id, self.action_language_it,
            self.action_language_ms, self.action_language_fa,
            self.action_language_pl, self.action_language_pt_BR,
            self.action_language_ro, self.action_language_ru,
            self.action_language_sl, self.action_language_es_ES,
            self.action_language_tr, self.action_language_uk,
            self.action_language_vi
        ])
        self.menu_help.addActions([
            self.action_report_bug, self.action_donate, self.action_about,
            self.action_website
        ])
        self.menubar.addActions([
            self.menu_file.menuAction(),
            self.menu_language.menuAction(),
            self.menu_help.menuAction()
        ])
        # Shortcuts
        self.action_open_zip.setShortcut('Ctrl+O')
        self.action_open_remote_zip.setShortcut('Ctrl+R')
        self.action_quit.setShortcut('Ctrl+Q')
        # Actions
        self.action_open_zip.triggered.connect(self.select_file)
        self.action_open_remote_zip.triggered.connect(self.enter_url)
        self.action_quit.triggered.connect(qApp.quit)
        self.action_language_sq.triggered.connect(
            lambda: self.change_language("sq"))
        self.action_language_ar.triggered.connect(
            lambda: self.change_language("ar"))
        self.action_language_ca.triggered.connect(
            lambda: self.change_language("ca"))
        self.action_language_zh_CN.triggered.connect(
            lambda: self.change_language("zh-CN"))
        self.action_language_hr.triggered.connect(
            lambda: self.change_language("hr"))
        self.action_language_cs.triggered.connect(
            lambda: self.change_language("cs"))
        self.action_language_nl.triggered.connect(
            lambda: self.change_language("nl"))
        self.action_language_en.triggered.connect(
            lambda: self.change_language("en_US"))
        self.action_language_fr.triggered.connect(
            lambda: self.change_language("fr"))
        self.action_language_de.triggered.connect(
            lambda: self.change_language("de"))
        self.action_language_el.triggered.connect(
            lambda: self.change_language("el"))
        self.action_language_hi.triggered.connect(
            lambda: self.change_language("hi"))
        self.action_language_id.triggered.connect(
            lambda: self.change_language("id"))
        self.action_language_it.triggered.connect(
            lambda: self.change_language("it"))
        self.action_language_ms.triggered.connect(
            lambda: self.change_language("ms"))
        self.action_language_fa.triggered.connect(
            lambda: self.change_language("fa"))
        self.action_language_pl.triggered.connect(
            lambda: self.change_language("pl"))
        self.action_language_pt_BR.triggered.connect(
            lambda: self.change_language("pt-BR"))
        self.action_language_ro.triggered.connect(
            lambda: self.change_language("ro"))
        self.action_language_ru.triggered.connect(
            lambda: self.change_language("ru"))
        self.action_language_sl.triggered.connect(
            lambda: self.change_language("sl"))
        self.action_language_es_ES.triggered.connect(
            lambda: self.change_language("es-ES"))
        self.action_language_tr.triggered.connect(
            lambda: self.change_language("tr"))
        self.action_language_uk.triggered.connect(
            lambda: self.change_language("uk"))
        self.action_language_vi.triggered.connect(
            lambda: self.change_language("vi"))
        self.action_about.triggered.connect(self.open_about)
        self.action_report_bug.triggered.connect(lambda: self.open_link(
            'https://github.com/XiaomiFirmwareUpdater/'
            'xiaomi-flashable-firmware-creator-gui/issues'))
        self.action_donate.triggered.connect(
            lambda: self.open_link('https://xiaomifirmwareupdater.com/donate'))
        self.action_website.triggered.connect(
            lambda: self.open_link('https://xiaomifirmwareupdater.com'))

    def re_translate_ui(self):
        """
        Items strings
        """
        self.setWindowTitle(
            self._translate("Title", "Xiaomi Flashable Firmware Creator"))
        self.process_type.setTitle(self._translate("Radio Buttons", "Process"))
        self.btn_fw.setText(self._translate("Radio Buttons", "Firmware"))
        self.btn_nonarb.setText(
            self._translate("Radio Buttons", "Non-ARB Firmware"))
        self.btn_vendor.setText(
            self._translate("Radio Buttons", "Firmware + Vendor"))
        self.btn_fwless.setText(
            self._translate("Radio Buttons", "Firmware-less ROM"))
        self.groupbox_drop.setTitle(
            self._translate("Drop space", "Drop a file"))
        self.label_drop.setText(
            self._translate(
                "Drop space", "<html><head/><body>"
                "<p align=\"center\">"
                "<span style=\" font-style:italic;\">"
                "Drop a rom zip file here"
                "</span></p></body></html>"))
        self.btn_select.setText(self._translate("Main Buttons", "Select file"))
        self.btn_select.setStatusTip(
            self._translate("Main Buttons", "Select MIUI Zip file"))
        self.btn_url.setText(self._translate("Main Buttons", "Enter URL"))
        self.btn_url.setStatusTip(
            self._translate("Main Buttons", "Enter a URL of a Zip file"))
        self.btn_create.setText(self._translate("Main Buttons", "Create"))
        self.btn_create.setStatusTip(
            self._translate("Main Buttons", "Create the selected output zip"))
        self.menu_file.setTitle(self._translate("Menu bar", "File"))
        self.menu_language.setTitle(self._translate("Menu bar", "Language"))
        self.menu_help.setTitle(self._translate("Menu bar", "Help"))
        self.action_open_zip.setText(self._translate("Menu bar", "Open ZIP"))
        self.action_open_zip.setStatusTip(
            self._translate("Menu bar", "Select MIUI Zip file"))
        self.action_open_remote_zip.setText(
            self._translate("Menu bar", "Enter URL"))
        self.action_open_remote_zip.setStatusTip(
            self._translate("Menu bar", "Enter a URL of a Zip file"))
        self.action_quit.setText(self._translate("Menu bar", "Quit"))
        self.action_quit.setStatusTip(
            self._translate("Menu bar", "Exits the application"))
        self.action_language_sq.setText(self._translate(
            "Menu bar", "Albanian"))
        self.action_language_ar.setText(self._translate("Menu bar", "Arabic"))
        self.action_language_ca.setText(self._translate("Menu bar", "Catalan"))
        self.action_language_zh_CN.setText(
            self._translate("Menu bar", "Chinese Simplified"))
        self.action_language_hr.setText(self._translate(
            "Menu bar", "Croatian"))
        self.action_language_cs.setText(self._translate("Menu bar", "Czech"))
        self.action_language_nl.setText(self._translate("Menu bar", "Dutch"))
        self.action_language_en.setText(self._translate("Menu bar", "English"))
        self.action_language_fr.setText(self._translate("Menu bar", "French"))
        self.action_language_de.setText(self._translate("Menu bar", "German"))
        self.action_language_el.setText(self._translate("Menu bar", "Greek"))
        self.action_language_hi.setText(self._translate("Menu bar", "Hindi"))
        self.action_language_id.setText(
            self._translate("Menu bar", "Indonesian"))
        self.action_language_it.setText(self._translate("Menu bar", "Italian"))
        self.action_language_ms.setText(self._translate("Menu bar", "Malay"))
        self.action_language_fa.setText(self._translate("Menu bar", "Persian"))
        self.action_language_pl.setText(self._translate("Menu bar", "Polish"))
        self.action_language_pt_BR.setText(
            self._translate("Menu bar", "Portuguese, Brazilian"))
        self.action_language_ro.setText(self._translate(
            "Menu bar", "Romanian"))
        self.action_language_ru.setText(self._translate("Menu bar", "Russian"))
        self.action_language_sl.setText(
            self._translate("Menu bar", "Slovenian"))
        self.action_language_es_ES.setText(
            self._translate("Menu bar", "Spanish"))
        self.action_language_tr.setText(self._translate("Menu bar", "Turkish"))
        self.action_language_uk.setText(
            self._translate("Menu bar", "Ukrainian"))
        self.action_language_vi.setText(
            self._translate("Menu bar", "Vietnamese"))
        self.action_report_bug.setText(
            self._translate("Menu bar", "Report Bug"))
        self.action_report_bug.setStatusTip(
            self._translate("Menu bar", "Submit an issue "
                            "in case anything is wrong"))
        self.action_donate.setText(self._translate("Menu bar", "Donate"))
        self.action_donate.setStatusTip(
            self._translate("Menu bar", "Show us some love"))
        self.action_about.setText(self._translate("Menu bar", "About"))
        self.action_about.setStatusTip(
            self._translate("Menu bar", "About this tool"))
        self.action_website.setText(self._translate("Menu bar", "Website"))
        self.action_website.setStatusTip(
            self._translate("Menu bar", "Visit tool website"))
        self.statusBar().showMessage(self._translate("Status Box", "Ready"))

    def center(self):
        """
        Dynamically center the window in screen
        """
        # https://gist.github.com/saleph/163d73e0933044d0e2c4
        # geometry of the main window
        window = self.frameGeometry()
        # center point of screen
        center_point = QDesktopWidget().availableGeometry().center()
        # move rectangle's center point to screen's center point
        window.moveCenter(center_point)
        # top left of rectangle becomes top left of window centering it
        self.move(window.topLeft())

    def change_language(self, lang: str):
        """
        Update strings language and settings
        """
        update_settings(dict({'language': lang}))
        adjust_layout_direction(self, lang)
        self._translateanslator.load(f'{current_dir}/i18n/{lang}.qm')
        self.re_translate_ui()
        logging.info(f'Language is switched to {lang}')

    def select_file(self):
        """
        Opens select file Dialog
        """
        dialog = QFileDialog()
        filepath = dialog.getOpenFileName(
            self, self._translate('Select Files Dialog',
                                  'Select MIUI zip'), '',
            self._translate('Select Files Dialog', 'MIUI zip files') +
            ' (*.zip)')[0]
        if not filepath:
            self.statusBar().showMessage(
                self._translate("Status Box", "Please select a file!"))
            self.status_box.setText(
                self._translate("Status Box", "Please select a file!"))
            return
        self.filepath = Path(filepath).absolute()
        self.filename = self.filepath.name
        self.status_box.setText(
            self._translate("Status Box", f"File {self.filename} is selected"))
        self.statusBar().showMessage(
            self._translate("Status Box", f"File {self.filename} is selected"))
        logging.info(f'File {self.filename} is selected')

    def enter_url(self):
        """
        Enter URL Dialog
        """
        dialog = InputDialog(self._translate('Enter URL Dialog',
                                             'Remote Zip URL'),
                             self._translate('Enter URL Dialog',
                                             'Enter a MIUI zip direct link:'),
                             self._translate('Enter URL Dialog', 'Set URL'),
                             self._translate('Enter URL Dialog', 'Cancel'),
                             parent=self.window_body)
        if dialog.exec_() == QDialog.Accepted:
            url = dialog.textValue()
            if "http" not in url or "ota.d.miui.com" not in url:
                message_box = MessageBox(
                    self._translate('Popup Message', 'Error'),
                    self._translate('Popup Message', 'Not a valid URL.'),
                    self._translate('Popup Message', 'OK'),
                    box_type="Warning",
                    parent=self.window_body)
                message_box.exec_()
                # if button_clicked == QMessageBox.Ok:
                #     pass
                return
            self.filepath = url
            self.filename = url.split("/")[-1]
            self.status_box.setText(
                self._translate("Status Box",
                                f"Remote file {self.filename} is selected."))
            logging.info(f'Remote file {self.filename} is selected')

    def create_zip(self):
        """
        creates output zip file
        """
        checked_radiobutton = None
        process = None
        if not self.filepath:
            error_box = MessageBox(self._translate('Popup Message', 'Error'),
                                   self._translate(
                                       'Popup Message',
                                       'You must select a ROM zip first!'),
                                   self._translate('Popup Message', 'OK'),
                                   box_type="Critical",
                                   parent=self.window_body)
            error_box.exec_()
            logging.info(f'No Zip error shown')
            return

        for button in self.process_type.findChildren(QRadioButton):
            if button.isChecked():
                checked_radiobutton = button.text()
                logging.info(f'Selected process ({button.text()})')
        if checked_radiobutton == 'Firmware':
            process = 'firmware'
        if checked_radiobutton == 'Non-ARB Firmware':
            process = 'nonarb'
        if checked_radiobutton == 'Firmware + Vendor':
            process = 'vendor'
        if checked_radiobutton == 'Firmware-less ROM':
            process = 'firmwareless'
        self.status_box.setText(
            self._translate("Status Box", f"Starting {process} job"))
        out_dir = Path(".").absolute() if isinstance(
            self.filepath, str) else self.filepath.parent
        firmware_creator = FlashableFirmwareCreator(str(self.filepath),
                                                    process, out_dir)
        self.progress_bar.setValue(1)
        logging.info(f'Starting extract job')
        self.progress_bar.setValue(5)
        self.status_box.setText(
            self._translate("Status Box", f"Unzipping MIUI ROM..."))
        self.progress_bar.setValue(20)
        logging.info(f'Unzipping {self.filename}')
        extracted = False
        try:
            firmware_creator.extract()
            extracted = True
        except RuntimeError as err:
            if str(err) == "Nothing found to extract!":
                message_box = MessageBox(
                    self._translate('Popup Message', 'Error'),
                    self._translate('Popup Message',
                                    'Unsupported operation for MTK!'),
                    self._translate('Popup Message', 'OK'),
                    box_type="Warning",
                    parent=self.window_body)
                message_box.exec_()
                self.status_box.setText(
                    self._translate("Status Box",
                                    "Error: Unsupported operation for MTK!"))
                logging.warning(f'Unsupported operation for MTK')
                firmware_creator.close()
                self.progress_bar.setValue(100)
            else:
                raise err
        if extracted:
            self.progress_bar.setValue(45)
            self.status_box.setText(
                self._translate("Status Box", "Generating updater-script..."))
            self.progress_bar.setValue(55)
            logging.info(f'Creating updater-script')
            firmware_creator.generate_updater_script()
            self.status_box.setText(
                self._translate("Status Box", "Creating zip.."))
            self.progress_bar.setValue(75)
            logging.info(f'Creating output zip')
            new_zip = firmware_creator.make_zip()
            firmware_creator.cleanup()
            firmware_creator.close()
            self.progress_bar.setValue(100)
            message_box = OutputMessageBox(
                self._translate('Popup Message', 'Done'),
                self._translate('Popup Message',
                                f'All Done! Output zip is {new_zip}'),
                self._translate('Popup Message', 'OK'),
                self._translate('Popup Message', 'Show in folder'),
                self.filepath,
                parent=self.window_body)
            clicked = message_box.exec_()
            if clicked:
                browse_file_directory(self.filepath)
            logging.info(f'Done')
            self.status_box.setText(self._translate("Status Box", "Ready"))
            self.statusBar().showMessage(self._translate(
                "Status Box", "Ready"))

    @staticmethod
    def open_link(link):
        """
        Opens link in browser
        """
        QDesktopServices.openUrl(QUrl(link))
        logging.info(f'{link} opened')

    def open_about(self):
        """
        Opens About box
        """
        about_box = AboutBox(self.lang)
        about_box.setup_ui()
        about_box.exec_()
Esempio n. 47
0
class QMainPlotterTemplate(QMainWindow):
    def __init__(self):
        super().__init__()

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.setWindowIcon(QIcon(':/assets/icon.svg'))

        with open('C:/HyPro/hyprosettings.json', 'r') as file:
            params = json.loads(file.read())
        theme = params['theme']

        if params['theme'] == 'normal':
            plt.style.use(style.mplstyle['normal'])
        else:
            plt.style.use(style.mplstyle['dark'])

        self.init_ui()

        self.setStyleSheet(style.stylesheet[theme])

    def init_ui(self):
        self.setFont(QFont('Segoe UI'))

        self.setGeometry(0, 0, 780, 820)
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        self.setWindowTitle('HyPro - Plotting Window')

        self.qvbox_layout = QVBoxLayout()
        self.qvbox_frame_holder = QFrame()
        self.qvbox_frame_holder.setLayout(self.qvbox_layout)
        self.grid_layout = QGridLayout()

        self.main_menu = self.menuBar()
        self.file_menu = self.main_menu.addMenu('File')
        self.edit_menu = self.main_menu.addMenu('Edit')

        export = QAction(QIcon(':/assets/archivebox.svg'), 'Export Plot', self)
        export.triggered.connect(self.export_plot)
        self.file_menu.addAction(export)

        copy = QAction(QIcon(':/assets/newdoc.svg'), 'Copy', self)
        copy.triggered.connect(self.copy_plot)
        self.edit_menu.addAction(copy)

        self.run_list_label = QLabel('Select Run:', self)
        self.run_list = QListWidget(self)
        self.run_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.run_list.setMaximumWidth(120)

        self.show_bad_data = QCheckBox('Show bad data', self)

        self.mark_bad_data = QCheckBox('Mark bad data', self)

        self.apply_button = QPushButton('Apply', self)

        self.figure = plt.figure()
        self.figure.set_tight_layout(tight=True)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)

        self.main_plot = self.figure.add_subplot(111)

        for x in self.main_plot.get_xticklabels():
            x.set_fontsize(12)
        for y in self.main_plot.get_yticklabels():
            y.set_fontsize(12)

        self.grid_layout.addWidget(self.canvas, 0, 1)
        self.grid_layout.addWidget(self.qvbox_frame_holder, 0, 0)

        self.qvbox_layout.addWidget(self.run_list_label)
        self.qvbox_layout.addWidget(self.run_list)
        self.qvbox_layout.addWidget(self.show_bad_data)
        self.qvbox_layout.addWidget(self.mark_bad_data)
        self.qvbox_layout.addWidget(self.apply_button)

        self.centralWidget().setLayout(self.grid_layout)

    def export_plot(self):
        filedialog = QFileDialog.getSaveFileName(None, 'Save Plot', '', '.png')
        if filedialog[0]:
            self.figure.savefig(filedialog[0] + filedialog[1], dpi=300)

    def copy_plot(self):
        buffer = io.BytesIO()
        self.figure.savefig(buffer, dpi=300)
        QApplication.clipboard().setImage(QImage.fromData(buffer.getvalue()))

    def base_on_pick(self, event, database, runs, peak_nums, nutrient=None, oxygen=None, salinity=None):
        plotted_data_index = event.ind[0]
        picked_run_number = runs[plotted_data_index]
        picked_peak_number = peak_nums[plotted_data_index]

        conn = sqlite3.connect(database)

        if nutrient:
            c = conn.cursor()
            c.execute('SELECT * FROM %sData WHERE runNumber = ? and peakNumber = ?' % nutrient,
                      (picked_run_number, picked_peak_number))
            data = list(c.fetchall())[0]
            conn.close()
            self.picked_peak_dialog = traceSelection(data[2], data[1], data[3], data[5], data[6], data[10], data[11], 'Plot')

        else:
            c = conn.cursor()
            if oxygen:
                c.execute('SELECT * from oxygenData WHERE deployment = ? and rosettePosition = ?', (picked_run_number,
                                                                                                    picked_peak_number))
                data = list(c.fetchall())[0]
                conn.close()
                self.picked_bottle_dialog = bottleSelection(data[0], data[15], data[16], data[4], round(data[9], 3), data[14])

            elif salinity:
                c.execute('SELECT * from salinityData WHERE deployment = ? and rosettePosition = ?', (picked_run_number,
                                                                                                    picked_peak_number))
                data = list(c.fetchall())[0]
                conn.close()
                self.picked_bottle_dialog = bottleSelection(data[0], data[10], data[11], data[2], data[6], data[9])
Esempio n. 48
0
    def __init__(self, parent=None):
        """ 
        """
        print("Skeet")

        super(FITSBrowse, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("FITSBrowse")

        self.current_directory = CurrentDirectory(
            "/data/lemi-archive-2016-04/20160427")
        self.model = FitsFileTableModel(self.current_directory)
        self.d_model = DirectoryListModel(self.current_directory)
        self.main_widget = QWidget(self)

        self.dir_text = "Current Directory: {0}".format(
            self.current_directory.cur_dir_path)
        self.cur_dir_label = QLabel(self.dir_text, self)

        self.listLabel = QLabel("&Directories")

        self.list_view = QListView()
        self.listLabel.setBuddy(self.list_view)
        self.list_view.setModel(self.d_model)
        self.list_view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)

        self.list_view.setMinimumWidth(self.list_view.sizeHintForColumn(0))
        self.list_view.setMaximumWidth(self.list_view.sizeHintForColumn(0))

        self.list_view_sm = self.list_view.selectionModel()
        self.list_view.doubleClicked.connect(self.change_directory)

        self.table_view = QTableView()
        self.table_view.setModel(self.model)
        self.table_view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.table_view_sm = self.table_view.selectionModel()
        self.table_view.doubleClicked.connect(self.display_image)

        list_vbox = QVBoxLayout()
        list_vbox.addWidget(self.listLabel)
        list_vbox.addWidget(self.list_view)
        self.list_widget = QWidget()
        self.list_widget.setLayout(list_vbox)

        #self.list_view.size

        main_layout = QHBoxLayout()
        main_layout.addWidget(self.list_widget)
        main_layout.addWidget(self.table_view)

        button_layout = QHBoxLayout()
        quit_button = QPushButton('Quit', self)
        quit_button.setToolTip('This button quits FITSBrowse')
        quit_button.clicked.connect(QApplication.instance().quit)
        button_layout.addStretch()
        button_layout.addWidget(quit_button)

        sep_line = QFrame()
        sep_line.setFrameShape(QFrame.HLine)

        super_layout = QVBoxLayout(self.main_widget)
        super_layout.addWidget(self.cur_dir_label)
        super_layout.addWidget(sep_line)
        super_layout.addLayout(main_layout)
        super_layout.addLayout(button_layout)

        self.setCentralWidget(self.main_widget)
        QtCore.QTimer.singleShot(0, self.initialLoad)
        x = self.table_view.frameSize()
        x = x.width()
        self.table_view.setMinimumWidth(x)
        self.main_widget.setMinimumHeight(500)
Esempio n. 49
0
    def initUI(self):
        hbox = QHBoxLayout(self)

        topleft = QFrame(self)
        # 使用一个风格框架为了看到QFrame小部件之间的界限
        topleft.setFrameShape(QFrame.StyledPanel)

        topright = QFrame(self)
        topright.setFrameShape(QFrame.StyledPanel)

        bottom = QFrame(self)
        bottom.setFrameShape(QFrame.StyledPanel)

        splitter1 = QSplitter(Qt.Horizontal)
        splitter1.addWidget(topleft)
        splitter1.addWidget(topright)

        splitter2 = QSplitter(Qt.Vertical)
        splitter2.addWidget(splitter1)
        splitter2.addWidget(bottom)

        hbox.addWidget(splitter2)
        self.setLayout(hbox)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QSplitter')
        self.show()
Esempio n. 50
0
class MovieLayout(QWidget):

    def __init__(self, url, movieID, user):
        super().__init__()
        self.controller = MovieController(url)
        self.url = url
        self.user = user
        self.setWindowTitle("Movie Player")
        self.movieID = movieID
        # creating a basic vlc instance
        self.instance = vlc.Instance()
        # creating an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()
        self.isPaused = True
        

#        self.moviebox = QVBoxLayout()
#        self.moviebox.addWidget(self.widget)
#        self.widget.setLayout(self.moviebox)
#        print("here")
        
        self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor (QPalette.Window,
                                QColor(0,0,0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)


        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        
        self.vboxlayout = QVBoxLayout()
      
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

    
        self.comment = QPlainTextEdit()
        

        
        self.comment.setPlaceholderText("Type Comment Here ...")
        self.comment.setFixedHeight(50)
        self.commentbox = QVBoxLayout()
        
        self.commentSubmit = QPushButton("Comment")
        self.commentSubmit.clicked.connect(lambda: self.submitComment())
        self.commentbox.addWidget(self.comment)
        self.commentbox.addWidget(self.commentSubmit)
        
        self.commentSection = QLabel("Comments:\n")
        self.commentSection.setFixedHeight(10)
        self.commentbox.addWidget(self.commentSection)
        self.commentSection_comments = QTextEdit("No Comments Yet")
        self.commentSection_comments.setStyleSheet("QTextEdit {color:black;font-size:13px;font-family: \"Times New Roman\", Times, serif;background-color:transparent;border-style: none}")
        self.commentSection_comments.setReadOnly(True)
        self.commentSection_comments.setFixedHeight(50)
        
        self.commentbox.addWidget(self.commentSection_comments)
        self.vboxlayout.addLayout(self.commentbox)
        
        
        self.setLayout(self.vboxlayout)
        self.playbutton.clicked.connect(lambda: self.PlayPause())
        self.stopbutton.clicked.connect(lambda: self.Stop())

        self.resize(640,480)
       
        self.timer = QTimer(self)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.updateUI)   
        
        
        
        self.loaded = False
        self.video = pafy.new(self.url) 
        
        self.best = self.video.getbest() 
            
        self.media = self.instance.media_new(self.best.url)
        
        self.mediaplayer.set_media(self.media)
        
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32": # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin": # for MacOS
            self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
            
        
        self.LoadComments()

    
   
    def submitComment(self):
        if(self.comment.toPlainText() != ""):
            result = self.controller.submitComment(self.movieID, self.comment.toPlainText(), self.user.username)
            if(result == 1):
                self.commentSection_comments.setPlainText(self.user.username + ": " + self.comment.toPlainText() + "\n" + self.commentSection_comments.toPlainText())
    
    
    def LoadComments(self):
        comments = self.controller.getComments(self.movieID)
        comment = ""
        for i in comments:
            comment += i[1] + ": " + i[0] + "\n"
        self.commentSection_comments.setPlainText(comment)
 
    #Plays and pauses the movie, same button changes status from play to pause
    def PlayPause(self):
        print("Play Pause")
        if(self.loaded == False):     
            self.loaded = True     

        if self.mediaplayer.is_playing():
            
            self.mediaplayer.pause()
            self.playbutton.setText("Play")
            self.isPaused = True
        else:
            
            self.mediaplayer.play()
            self.playbutton.setText("Pause")
            self.timer.start()
            self.isPaused = False

    #stops the movie, unloads it, pressing this requires loading the movie again
    def Stop(self):
        self.mediaplayer.stop()
        self.playbutton.setText("Play")

    #Opens the movie from youtube and sets it in the appropriate layout item to be showcased
    #TODO: add and use param (string youtube_url) 
    def OpenFile(self, filename=None):
      
        self.video = pafy.new(self.url) 
        self.best = self.video.getbest()
        self.media = self.instance.media_new(self.best.url)
        self.mediaplayer.set_media(self.media)
        
        if sys.platform.startswith('linux'): # for Linux using the X Server
                self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32": # for Windows
                self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin": # for MacOS
                self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
    
        
    #Changes the volume of the media player
    def setVolume(self, Volume):
        #Set the volume 
        self.mediaplayer.audio_set_volume(Volume)

    #Sets the position of the video slider, responsible for going to different times in the movie
    def setPosition(self, position):        
        # setting the position to where the slider was dragged
        self.mediaplayer.set_position(position / 1000.0)
        # the vlc MediaPlayer needs a float value between 0 and 1, Qt
        # uses integer variables, so you need a factor; the higher the
        # factor, the more precise are the results
        # (1000 should be enough)

    #function used by timer to keep the movie's time slider indicator in the right position
    def updateUI(self):
        # setting the slider to the desired position     
        self.positionslider.setValue(self.mediaplayer.get_position() * 1000)
Esempio n. 51
0
 def __init__(self, lang, translator):
     super().__init__()
     # Init
     self.lang = lang
     self._translateanslator = translator
     self._translate = QApplication.translate
     self.window_body = QWidget(self)
     self.process_type = QGroupBox(self.window_body)
     self.btn_fw = QRadioButton(self.process_type)
     self.btn_nonarb = QRadioButton(self.process_type)
     self.btn_vendor = QRadioButton(self.process_type)
     self.btn_fwless = QRadioButton(self.process_type)
     self.frame = QFrame(self.window_body)
     self.btn_select = QPushButton(self.frame)
     self.btn_url = QPushButton(self.frame)
     self.btn_create = QPushButton(self.frame)
     self.menubar = QMenuBar(self)
     self.status_box = QTextEdit(self.window_body)
     self.groupbox_drop = DropSpace(self.window_body, self.status_box,
                                    self._translate)
     self.label_drop = QLabel(self.groupbox_drop)
     self.progress_bar = QProgressBar(self.window_body)
     self.menu_file = QMenu(self.menubar)
     self.statusbar = QStatusBar(self)
     self.menu_language = QMenu(self.menubar)
     self.menu_help = QMenu(self.menubar)
     self.action_open_zip = QAction(self)
     self.action_open_remote_zip = QAction(self)
     self.action_quit = QAction(self)
     # languages
     self.action_language_sq = QAction(self)
     self.action_language_ar = QAction(self)
     self.action_language_ca = QAction(self)
     self.action_language_zh_CN = QAction(self)
     self.action_language_hr = QAction(self)
     self.action_language_cs = QAction(self)
     self.action_language_nl = QAction(self)
     self.action_language_en = QAction(self)
     self.action_language_fr = QAction(self)
     self.action_language_de = QAction(self)
     self.action_language_el = QAction(self)
     self.action_language_hi = QAction(self)
     self.action_language_id = QAction(self)
     self.action_language_it = QAction(self)
     self.action_language_fa = QAction(self)
     self.action_language_ms = QAction(self)
     self.action_language_pl = QAction(self)
     self.action_language_pt_BR = QAction(self)
     self.action_language_ro = QAction(self)
     self.action_language_ru = QAction(self)
     self.action_language_sl = QAction(self)
     self.action_language_es_ES = QAction(self)
     self.action_language_tr = QAction(self)
     self.action_language_uk = QAction(self)
     self.action_language_vi = QAction(self)
     self.action_donate = QAction(self)
     self.action_about = QAction(self)
     self.action_report_bug = QAction(self)
     self.action_website = QAction(self)
     # vars
     self.filepath = None
     self.filename = ''
     # setup
     self.setup_ui()
     self.setWindowIcon(QIcon(f'{current_dir}/icon.png'))
     self.center()
     adjust_layout_direction(self, lang)
     self.show()
Esempio n. 52
0
 def __init__(self, parent=None):
     QWidget.__init__(self)
     self.capitalLog = []
     self.luckyLog = []
     self.unluckyLog = []
     self.lucky = []
     self.unlucky = []
     self.capital = []
     self.sitex = []
     self.sitey = []
     self.talent = []
     self.displayTarget = ""
     self.epochs = 0
     self.displayGrand = 0
     self.outdir = "file:///" + os.getcwd().replace('\\', '/') + "/data/"
     self.setWindowTitle('Talent vs Luck')
     self.setWindowIcon(QtGui.QIcon('title.ico'))
     self.resize(851, 535)
     self.setMinimumSize(851, 535)
     self.setMaximumSize(851, 535)
     self.gridLayoutWidget = QWidget(self)
     self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 191, 511))
     self.gridLayout_2 = QGridLayout(self.gridLayoutWidget)
     self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
     self.M_lab = QLabel("地图规模", self.gridLayoutWidget)
     self.M_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.M_lab, 0, 0, 1, 1)
     self.T_avg = QComboBox(self.gridLayoutWidget)
     for i in range(1, 10):
         self.T_avg.addItem(str(i / 10))
     self.gridLayout_2.addWidget(self.T_avg, 5, 1, 1, 1)
     self.avg_lab = QLabel("talent均值", self.gridLayoutWidget)
     self.avg_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.avg_lab, 5, 0, 1, 1)
     self.T_std = QComboBox(self.gridLayoutWidget)
     for i in range(1, 10):
         self.T_std.addItem(str(i / 10))
     self.gridLayout_2.addWidget(self.T_std, 6, 1, 1, 1)
     self.std_lab = QLabel("talent标准差", self.gridLayoutWidget)
     self.std_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.std_lab, 6, 0, 1, 1)
     self.grand_lab = QLabel("图表粒度", self.gridLayoutWidget)
     self.grand_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.grand_lab, 7, 0, 1, 1)
     self.grand = QComboBox(self.gridLayoutWidget)
     for i in range(1, 5):
         self.grand.addItem(str(i * 10))
     self.gridLayout_2.addWidget(self.grand, 7, 1, 1, 1)
     self.luck = QComboBox(self.gridLayoutWidget)
     for i in range(1, 10):
         self.luck.addItem(str(i * 100))
     self.gridLayout_2.addWidget(self.luck, 2, 1, 1, 1)
     self.step = QComboBox(self.gridLayoutWidget)
     for i in range(1, 7):
         self.step.addItem(str(i * 50))
     self.gridLayout_2.addWidget(self.step, 4, 1, 1, 1)
     self.map = QComboBox(self.gridLayoutWidget)
     for i in range(1, 7):
         self.map.addItem(str(i * 100) + "x" + str(i * 100))
     self.gridLayout_2.addWidget(self.map, 0, 1, 1, 1)
     self.unluck = QComboBox(self.gridLayoutWidget)
     for i in range(1, 10):
         self.unluck.addItem(str(i * 100))
     self.gridLayout_2.addWidget(self.unluck, 3, 1, 1, 1)
     self.N_lab = QLabel("人数", self.gridLayoutWidget)
     self.N_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.N_lab, 1, 0, 1, 1)
     self.unluck_lab = QLabel("不幸事件", self.gridLayoutWidget)
     self.unluck_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.unluck_lab, 3, 0, 1, 1)
     self.luck_lab = QLabel("幸运事件", self.gridLayoutWidget)
     self.luck_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.luck_lab, 2, 0, 1, 1)
     self.s_lab = QLabel("迭代次数", self.gridLayoutWidget)
     self.s_lab.setAlignment(QtCore.Qt.AlignCenter)
     self.gridLayout_2.addWidget(self.s_lab, 4, 0, 1, 1)
     self.N = QComboBox(self.gridLayoutWidget)
     for i in range(1, 7):
         self.N.addItem(str(i * 500))
     self.gridLayout_2.addWidget(self.N, 1, 1, 1, 1)
     self.line = QFrame(self)
     self.line.setGeometry(QtCore.QRect(210, 10, 20, 511))
     self.line.setFrameShape(QFrame.VLine)
     self.line.setFrameShadow(QFrame.Sunken)
     self.line_2 = QFrame(self)
     self.line_2.setGeometry(QtCore.QRect(340, 10, 20, 511))
     self.line_2.setFrameShape(QFrame.VLine)
     self.line_2.setFrameShadow(QFrame.Sunken)
     self.verticalLayoutWidget = QWidget(self)
     self.verticalLayoutWidget.setGeometry(QtCore.QRect(230, 10, 101, 511))
     self.verticalLayout_2 = QVBoxLayout(self.verticalLayoutWidget)
     self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
     self.start = QPushButton("Start", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.start)
     self.TN = QPushButton("T-N", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.TN)
     self.LN = QPushButton("L-N", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.LN)
     self.CN = QPushButton("C-N", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.CN)
     self.CT = QPushButton("C-T", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.CT)
     self.TC = QPushButton("T-C", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.TC)
     self.LC = QPushButton("L-C", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.LC)
     self.CL = QPushButton("C-L", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.CL)
     self.UC = QPushButton("U-C", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.UC)
     self.CU = QPushButton("C-U", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.CU)
     self.CmaxTime = QPushButton("Cmax-Time", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.CmaxTime)
     self.CmaxEvent = QPushButton("Cmax-Event", self.verticalLayoutWidget)
     self.verticalLayout_2.addWidget(self.CmaxEvent)
     self.verticalLayoutWidget_2 = QWidget(self)
     self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(
         360, 10, 471, 511))
     self.verticalLayout_3 = QVBoxLayout(self.verticalLayoutWidget_2)
     self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
     self.slider = QSlider(self.verticalLayoutWidget_2)
     self.slider.setMinimum(0)
     self.slider.setOrientation(QtCore.Qt.Horizontal)
     self.verticalLayout_3.addWidget(self.slider)
     self.screen = QWebEngineView(self.verticalLayoutWidget_2)
     self.verticalLayout_3.addWidget(self.screen)
     self.start.clicked.connect(self.startAction)
     self.TN.clicked.connect(self.TNAction)
     self.LN.clicked.connect(self.LNAction)
     self.CN.clicked.connect(self.CNAction)
     self.CT.clicked.connect(self.CTAction)
     self.TC.clicked.connect(self.TCAction)
     self.LC.clicked.connect(self.LCAction)
     self.CL.clicked.connect(self.CLAction)
     self.UC.clicked.connect(self.UCAction)
     self.CU.clicked.connect(self.CUAction)
     self.CmaxTime.clicked.connect(self.CmaxTimeAction)
     self.CmaxEvent.clicked.connect(self.CmaxEventAction)
     self.slider.valueChanged[int].connect(self.sliderAction)
     self.TN.setEnabled(False)
     self.LN.setEnabled(False)
     self.CN.setEnabled(False)
     self.CT.setEnabled(False)
     self.TC.setEnabled(False)
     self.LC.setEnabled(False)
     self.CL.setEnabled(False)
     self.UC.setEnabled(False)
     self.CU.setEnabled(False)
     self.CmaxTime.setEnabled(False)
     self.CmaxEvent.setEnabled(False)
     self.slider.setEnabled(False)
     self.screen.setHtml("please set configuration")
Esempio n. 53
0
def make_line(parent_widget: QWidget):
    line = QFrame(parent_widget)
    line.setFrameShape(QFrame.HLine)
    return line
Esempio n. 54
0
class GuiRingPlayerStats(QSplitter):
    def __init__(self, config, querylist, mainwin, debug=True):
        QSplitter.__init__(self, None)
        self.debug = debug
        self.conf = config
        self.main_window = mainwin
        self.sql = querylist

        self.liststore = [
        ]  # gtk.ListStore[]         stores the contents of the grids
        self.listcols = [
        ]  # gtk.TreeViewColumn[][]  stores the columns in the grids

        self.MYSQL_INNODB = 2
        self.PGSQL = 3
        self.SQLITE = 4

        # create new db connection to avoid conflicts with other threads
        self.db = Database.Database(self.conf, sql=self.sql)
        self.cursor = self.db.cursor

        settings = {}
        settings.update(self.conf.get_db_parameters())
        settings.update(self.conf.get_import_parameters())
        settings.update(self.conf.get_default_paths())

        # text used on screen stored here so that it can be configured
        self.filterText = {
            'handhead': _('Hand Breakdown for all levels listed above')
        }

        filters_display = {
            "Heroes": True,
            "Sites": True,
            "Games": True,
            "Currencies": True,
            "Limits": True,
            "LimitSep": True,
            "LimitType": True,
            "Type": True,
            "Seats": True,
            "SeatSep": True,
            "Dates": True,
            "Groups": True,
            "GroupsAll": True,
            "Button1": True,
            "Button2": True
        }

        self.filters = Filters.Filters(self.db, display=filters_display)
        self.filters.registerButton1Name(_("Filters"))
        self.filters.registerButton1Callback(self.showDetailFilter)
        self.filters.registerButton2Name(_("Refresh Stats"))
        self.filters.registerButton2Callback(self.refreshStats)

        scroll = QScrollArea()
        scroll.setWidget(self.filters)

        # ToDo: store in config
        # ToDo: create popup to adjust column config
        # columns to display, keys match column name returned by sql, values in tuple are:
        #     is column displayed(summary then position), column heading, xalignment, formatting, celltype
        self.columns = self.conf.get_gui_cash_stat_params()

        # Detail filters:  This holds the data used in the popup window, extra values are
        # added at the end of these lists during processing
        #                  sql test,              screen description,        min, max
        self.handtests = [  # already in filter class : ['h.seats', 'Number of Players', 2, 10]
            ['gt.maxSeats', 'Size of Table', 2, 10],
            ['h.playersVpi', 'Players who VPI', 0, 10],
            ['h.playersAtStreet1', 'Players at Flop', 0, 10],
            ['h.playersAtStreet2', 'Players at Turn', 0, 10],
            ['h.playersAtStreet3', 'Players at River', 0, 10],
            ['h.playersAtStreet4', 'Players at Street7', 0, 10],
            ['h.playersAtShowdown', 'Players at Showdown', 0, 10],
            ['h.street0Raises', 'Bets to See Flop', 0, 5],
            ['h.street1Raises', 'Bets to See Turn', 0, 5],
            ['h.street2Raises', 'Bets to See River', 0, 5],
            ['h.street3Raises', 'Bets to See Street7', 0, 5],
            ['h.street4Raises', 'Bets to See Showdown', 0, 5]
        ]

        self.cardstests = [
            [Card.DATABASE_FILTERS['pair'],
             _('Pocket pairs')],
            [Card.DATABASE_FILTERS['suited'],
             _('Suited')],
            [
                Card.DATABASE_FILTERS['suited_connectors'],
                _('Suited connectors')
            ],
            [Card.DATABASE_FILTERS['offsuit'],
             _('Offsuit')],
            [
                Card.DATABASE_FILTERS['offsuit_connectors'],
                _('Offsuit connectors')
            ],
        ]
        self.stats_frame = None
        self.stats_vbox = None
        self.detailFilters = []  # the data used to enhance the sql select
        self.cardsFilters = []

        self.stats_frame = QFrame()
        self.stats_frame.setLayout(QVBoxLayout())

        self.stats_vbox = QSplitter(Qt.Vertical)
        self.stats_frame.layout().addWidget(self.stats_vbox)

        self.addWidget(scroll)
        self.addWidget(self.stats_frame)
        self.setStretchFactor(0, 0)
        self.setStretchFactor(1, 1)

        # Make sure Hand column is not displayed.
        hand_column = (x for x in self.columns if x[0] == 'hand').next()
        hand_column[colshowsumm] = hand_column[colshowposn] = False

        # If rfi and steal both on for summaries, turn rfi off.
        rfi_column = (x for x in self.columns if x[0] == 'rfi').next()
        steals_column = (x for x in self.columns if x[0] == 'steals').next()
        if rfi_column[colshowsumm] and steals_column[colshowsumm]:
            rfi_column[colshowsumm] = False

        # If rfi and steal both on for position breakdowns, turn steals off.
        if rfi_column[colshowposn] and steals_column[colshowposn]:
            steals_column[colshowposn] = False

    def refreshStats(self, checkState):
        self.liststore = []
        self.listcols = []
        self.stats_frame.layout().removeWidget(self.stats_vbox)
        self.stats_vbox.setParent(None)
        self.stats_vbox = QSplitter(Qt.Vertical)
        self.stats_frame.layout().addWidget(self.stats_vbox)
        self.fillStatsFrame(self.stats_vbox)

        if self.liststore:
            topsize = self.stats_vbox.widget(0).sizeHint().height()
            self.stats_vbox.setSizes(
                [topsize, self.stats_vbox.height() - topsize])
            self.stats_vbox.setStretchFactor(0, 0)
            self.stats_vbox.setStretchFactor(1, 1)

    def fillStatsFrame(self, vbox):
        sites = self.filters.getSites()
        heroes = self.filters.getHeroes()
        siteids = self.filters.getSiteIds()
        limits = self.filters.getLimits()
        seats = self.filters.getSeats()
        groups = self.filters.getGroups()
        dates = self.filters.getDates()
        games = self.filters.getGames()
        currencies = self.filters.getCurrencies()
        sitenos = []
        playerids = []

        # Which sites are selected?
        for site in sites:
            sitenos.append(siteids[site])
            _hname = Charset.to_utf8(heroes[site])
            result = self.db.get_player_id(self.conf, site, _hname)
            if result is not None:
                playerids.append(int(result))

        if not sitenos:
            #Should probably pop up here.
            print _("No sites selected - defaulting to PokerStars")
            sitenos = [2]
        if not playerids:
            print _("No player ids found")
            return
        if not limits:
            print _("No limits found")
            return

        self.createStatsTable(vbox, playerids, sitenos, limits, seats, groups,
                              dates, games, currencies)

    def createStatsTable(self, vbox, playerids, sitenos, limits, seats, groups,
                         dates, games, currencies):
        startTime = time()
        show_detail = True

        #        # Display summary table at top of page
        #        # 3rd parameter passes extra flags, currently includes:
        #        #   holecards - whether to display card breakdown (True/False)
        #        #   numhands  - min number hands required when displaying all players
        #        #   gridnum   - index for grid data structures
        flags = [False, self.filters.getNumHands(), 0]
        self.addGrid(vbox, 'playerDetailedStats', flags, playerids, sitenos,
                     limits, seats, groups, dates, games, currencies)

        if 'allplayers' in groups:
            # can't currently do this combination so skip detailed table
            show_detail = False

        if show_detail:
            # Separator
            frame = QWidget()
            vbox2 = QVBoxLayout()
            vbox2.setContentsMargins(0, 0, 0, 0)
            frame.setLayout(vbox2)
            vbox.addWidget(frame)
            heading = QLabel(self.filterText['handhead'])
            heading.setAlignment(Qt.AlignHCenter)
            vbox2.addWidget(heading)

            # Detailed table
            flags[0] = True
            flags[2] = 1
            self.addGrid(vbox2, 'playerDetailedStats', flags, playerids,
                         sitenos, limits, seats, groups, dates, games,
                         currencies)

        self.db.rollback()
        print(
            _("Stats page displayed in %4.2f seconds") % (time() - startTime))

    def addGrid(self, vbox, query, flags, playerids, sitenos, limits, seats,
                groups, dates, games, currencies):
        sqlrow = 0
        if not flags: holecards, grid = False, 0
        else: holecards, grid = flags[0], flags[2]

        tmp = self.sql.query[query]
        tmp = self.refineQuery(tmp, flags, playerids, sitenos, limits, seats,
                               groups, dates, games, currencies)
        self.cursor.execute(tmp)
        result = self.cursor.fetchall()
        colnames = [desc[0].lower() for desc in self.cursor.description]

        # pre-fetch some constant values:
        colshow = colshowsumm
        if 'posn' in groups: colshow = colshowposn
        self.cols_to_show = [x for x in self.columns if x[colshow]]
        hgametypeid_idx = colnames.index('hgametypeid')

        assert len(self.liststore) == grid, "len(self.liststore)=" + str(
            len(self.liststore)) + " grid-1=" + str(grid)
        view = QTableView()
        self.liststore.append(
            QStandardItemModel(0, len(self.cols_to_show), view))
        self.liststore[grid].setSortRole(Qt.UserRole)
        view.setModel(self.liststore[grid])
        view.verticalHeader().hide()
        vbox.addWidget(view)
        self.listcols.append([])

        # Create header row   eg column: ("game",     True, "Game",     0.0, "%s")
        for col, column in enumerate(self.cols_to_show):
            if column[colalias] == 'game' and holecards:
                s = [x for x in self.columns
                     if x[colalias] == 'hand'][0][colheading]
            else:
                s = column[colheading]
            self.listcols[grid].append(s)
        self.liststore[grid].setHorizontalHeaderLabels(self.listcols[grid])

        rows = len(result)  # +1 for title row

        while sqlrow < rows:
            treerow = []
            for col, column in enumerate(self.cols_to_show):
                if column[colalias] in colnames:
                    value = result[sqlrow][colnames.index(column[colalias])]
                    if column[colalias] == 'plposition':
                        if value == 'B':
                            value = 'BB'
                        elif value == 'S':
                            value = 'SB'
                        elif value == '0':
                            value = 'Btn'
                else:
                    if column[colalias] == 'game':
                        if holecards:
                            value = Card.decodeStartHandValue(
                                result[sqlrow][colnames.index('category')],
                                result[sqlrow][hgametypeid_idx])
                        else:
                            minbb = result[sqlrow][colnames.index(
                                'minbigblind')]
                            maxbb = result[sqlrow][colnames.index(
                                'maxbigblind')]
                            value = result[sqlrow][colnames.index('limittype')] + ' ' \
                                    + result[sqlrow][colnames.index('category')].title() + ' ' \
                                    + result[sqlrow][colnames.index('name')] + ' ' \
                                    + result[sqlrow][colnames.index('currency')] + ' '
                            if 100 * int(minbb / 100.0) != minbb:
                                value += '%.2f' % (minbb / 100.0)
                            else:
                                value += '%.0f' % (minbb / 100.0)
                            if minbb != maxbb:
                                if 100 * int(maxbb / 100.0) != maxbb:
                                    value += ' - %.2f' % (maxbb / 100.0)
                                else:
                                    value += ' - %.0f' % (maxbb / 100.0)
                            ante = result[sqlrow][colnames.index('ante')]
                            if ante > 0:
                                value += ' ante: %.2f' % (ante / 100.0)
                            if result[sqlrow][colnames.index('fast')] == 1:
                                value += ' ' + fast_names[result[sqlrow][
                                    colnames.index('name')]]
                    else:
                        continue
                item = QStandardItem('')
                sortValue = -1e9
                if value is not None and value != -999:
                    item = QStandardItem(column[colformat] % value)
                    if column[colalias] == 'game' and holecards:
                        if result[sqlrow][colnames.index(
                                'category')] == 'holdem':
                            sortValue = 1000 * ranks[value[0]] + 10 * ranks[
                                value[1]] + (1 if len(value) == 3
                                             and value[2] == 's' else 0)
                        else:
                            sortValue = -1
                    elif column[colalias] in ('game', 'pname'):
                        sortValue = value
                    elif column[colalias] == 'plposition':
                        sortValue = [
                            'BB', 'SB', 'Btn', '1', '2', '3', '4', '5', '6',
                            '7'
                        ].index(value)
                    else:
                        sortValue = float(value)
                item.setData(sortValue, Qt.UserRole)
                item.setEditable(False)
                if col != 0:
                    item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                if column[colalias] != 'game':
                    item.setToolTip('<big>%s for %s</big><br/><i>%s</i>' %
                                    (column[colheading], treerow[0].text(),
                                     onlinehelp[column[colheading]]))
                treerow.append(item)
            self.liststore[grid].appendRow(treerow)
            sqlrow += 1

        view.resizeColumnsToContents()
        view.setSortingEnabled(
            True
        )  # do this after resizing columns, otherwise it leaves room for the sorting triangle in every heading
        view.resizeColumnToContents(
            0
        )  # we want room for the sorting triangle in column 0 where it starts.
        view.resizeRowsToContents()

    def refineQuery(self, query, flags, playerids, sitenos, limits, seats,
                    groups, dates, games, currencies):
        having = ''
        if not flags:
            holecards = False
            numhands = 0
        else:
            holecards = flags[0]
            numhands = flags[1]
        colshow = colshowsumm
        if 'posn' in groups: colshow = colshowposn

        pname_column = (x for x in self.columns if x[0] == 'pname').next()
        if 'allplayers' in groups:
            nametest = "(hp.playerId)"
            if holecards or 'posn' in groups:
                pname = "'all players'"
                # set flag in self.columns to not show player name column
                pname_column[colshow] = False
                # can't do this yet (re-write doing more maths in python instead of sql?)
                if numhands:
                    nametest = "(-1)"
            else:
                pname = "p.name"
                # set flag in self.columns to show player name column
                pname_column[colshow] = True
                if numhands:
                    having = ' and count(1) > %d ' % (numhands, )
        else:
            if playerids:
                nametest = str(tuple(playerids))
                nametest = nametest.replace("L", "")
                nametest = nametest.replace(",)", ")")
            else:
                nametest = "1 = 2"
            pname = "p.name"
            # set flag in self.columns to not show player name column
            pname_column[colshow] = False
        query = query.replace("<player_test>", nametest)
        query = query.replace("<playerName>", pname)
        query = query.replace("<havingclause>", having)

        gametest = ""
        for m in self.filters.display.items():
            if m[0] == 'Games' and m[1]:
                if len(games) > 0:
                    gametest = str(tuple(games))
                    gametest = gametest.replace("L", "")
                    gametest = gametest.replace(",)", ")")
                    gametest = gametest.replace("u'", "'")
                    gametest = "and gt.category in %s" % gametest
                else:
                    gametest = "and gt.category IS NULL"
        query = query.replace("<game_test>", gametest)

        currencytest = str(tuple(currencies))
        currencytest = currencytest.replace(",)", ")")
        currencytest = currencytest.replace("u'", "'")
        currencytest = "AND gt.currency in %s" % currencytest
        query = query.replace("<currency_test>", currencytest)

        sitetest = ""
        for m in self.filters.display.items():
            if m[0] == 'Sites' and m[1]:
                if len(sitenos) > 0:
                    sitetest = str(tuple(sitenos))
                    sitetest = sitetest.replace("L", "")
                    sitetest = sitetest.replace(",)", ")")
                    sitetest = sitetest.replace("u'", "'")
                    sitetest = "and gt.siteId in %s" % sitetest
                else:
                    sitetest = "and gt.siteId IS NULL"
        query = query.replace("<site_test>", sitetest)

        if seats:
            query = query.replace(
                '<seats_test>',
                'between ' + str(seats['from']) + ' and ' + str(seats['to']))
            if 'seats' in groups:
                query = query.replace('<groupbyseats>', ',h.seats')
                query = query.replace('<orderbyseats>', ',h.seats')
            else:
                query = query.replace('<groupbyseats>', '')
                query = query.replace('<orderbyseats>', '')
        else:
            query = query.replace('<seats_test>', 'between 0 and 100')
            query = query.replace('<groupbyseats>', '')
            query = query.replace('<orderbyseats>', '')

        bbtest = self.filters.get_limits_where_clause(limits)

        query = query.replace("<gtbigBlind_test>", bbtest)

        if holecards:  # re-use level variables for hole card query
            query = query.replace("<hgametypeId>", "hp.startcards")
            query = query.replace(
                "<orderbyhgametypeId>",
                ",case when floor((hp.startcards-1)/13) >= mod((hp.startcards-1),13) then hp.startcards + 0.1 "
                +
                " else 13*mod((hp.startcards-1),13) + floor((hp.startcards-1)/13) + 1 "
                + " end desc ")
        else:
            query = query.replace("<orderbyhgametypeId>", "")
            groupLevels = 'limits' not in groups
            if groupLevels:
                query = query.replace(
                    "<hgametypeId>", "p.name"
                )  # need to use p.name for sqlite posn stats to work
            else:
                query = query.replace("<hgametypeId>", "h.gametypeId")

        # process self.detailFilters (a list of tuples)
        flagtest = ''
        if self.detailFilters:
            for f in self.detailFilters:
                if len(f) == 3:
                    # X between Y and Z
                    flagtest += ' and %s between %s and %s ' % (f[0], str(
                        f[1]), str(f[2]))
        query = query.replace("<flagtest>", flagtest)
        if self.cardsFilters:
            cardstests = []

            for cardFilter in self.cardsFilters:
                cardstests.append(cardFilter)
            cardstests = ''.join(('and (', ' or '.join(cardstests), ')'))
        else:
            cardstests = ''
        query = query.replace("<cardstest>", cardstests)
        # allow for differences in sql cast() function:
        if self.db.backend == self.MYSQL_INNODB:
            query = query.replace("<signed>", 'signed ')
        else:
            query = query.replace("<signed>", '')

        # Filter on dates
        query = query.replace(
            "<datestest>",
            " between '" + dates[0] + "' and '" + dates[1] + "'")

        # Group by position?
        plposition_column = (x for x in self.columns
                             if x[0] == 'plposition').next()
        if 'posn' in groups:
            query = query.replace("<position>", "hp.position")
            plposition_column[colshow] = True
        else:
            query = query.replace("<position>", "gt.base")
            plposition_column[colshow] = False

        return (query)

    def showDetailFilter(self, checkState):
        detailDialog = QDialog(self.main_window)
        detailDialog.setWindowTitle(_("Detailed Filters"))

        handbox = QVBoxLayout()
        detailDialog.setLayout(handbox)

        label = QLabel(_("Hand Filters:"))
        handbox.addWidget(label)
        label.setAlignment(Qt.AlignCenter)

        grid = QGridLayout()
        handbox.addLayout(grid)
        for row, htest in enumerate(self.handtests):
            cb = QCheckBox()
            lbl_from = QLabel(htest[1])
            lbl_tween = QLabel(_('between'))
            lbl_to = QLabel(_('and'))
            sb1 = QSpinBox()
            sb1.setRange(0, 10)
            sb1.setValue(htest[2])
            sb2 = QSpinBox()
            sb2.setRange(2, 10)
            sb2.setValue(htest[3])

            for df in self.detailFilters:
                if df[0] == htest[0]:
                    cb.setChecked(True)
                    break

            grid.addWidget(cb, row, 0)
            grid.addWidget(lbl_from, row, 1, Qt.AlignLeft)
            grid.addWidget(lbl_tween, row, 2)
            grid.addWidget(sb1, row, 3)
            grid.addWidget(lbl_to, row, 4)
            grid.addWidget(sb2, row, 5)

            htest[4:7] = [cb, sb1, sb2]

        label = QLabel(_('Restrict to hand types:'))
        handbox.addWidget(label)
        for ctest in self.cardstests:
            hbox = QHBoxLayout()
            handbox.addLayout(hbox)
            cb = QCheckBox()
            if ctest[0] in self.cardsFilters:
                cb.setChecked(True)
            label = QLabel(ctest[1])
            hbox.addWidget(cb)
            hbox.addWidget(label)
            ctest[2:3] = [cb]
        btnBox = QDialogButtonBox(QDialogButtonBox.Ok
                                  | QDialogButtonBox.Cancel)
        handbox.addWidget(btnBox)
        btnBox.accepted.connect(detailDialog.accept)
        btnBox.rejected.connect(detailDialog.reject)
        response = detailDialog.exec_()

        if response:
            self.detailFilters = []
            for ht in self.handtests:
                if ht[4].isChecked():
                    self.detailFilters.append(
                        (ht[0], ht[5].value(), ht[6].value()))
                ht[2], ht[3] = ht[5].value(), ht[6].value()
            self.cardsFilters = []
            for ct in self.cardstests:
                if ct[2].isChecked():
                    self.cardsFilters.append(ct[0])
            self.refreshStats(None)
Esempio n. 55
0
    def build_contents(self):
        """Initialize all the ui components."""
        # self.setLayout(QGridLayout())
        # self.layout().setContentsMargins(0,0,0,0)
        self.setLayout(QVBoxLayout())

        # --- POSITION ---
        position_frame = QFrame()
        grid_layout = QGridLayout()
        grid_layout.setContentsMargins(0, 0, 0, 0)
        position_frame.setLayout(grid_layout)
        col = 0
        for p in position_params:
            if p != '.':
                value = self.cs8.get(p)
                label_text = p
                label = QLabel(label_text)
                label.font().setPointSize(8)
                widget = QDoubleSpinBox()
                widget.setFixedWidth(100)
                widget.setMinimum(-99999)
                widget.setMaximum(99999)
                widget.setValue(float(value))
                controller = WidgetController(self, p, widget)
                widget.setEnabled(False)
                grid_layout.addWidget(label, 0, col)
                grid_layout.addWidget(widget, 1, col)
                col += 1
                self.widget_controllers[p] = controller
        # self.layout().addWidget(position_frame,0,0)
        self.layout().addWidget(position_frame)

        # --- STATE ---
        state_frame = QFrame()
        grid_layout = QGridLayout()
        grid_layout.setContentsMargins(0, 0, 0, 0)
        state_frame.setLayout(grid_layout)
        row = 0
        col = 0
        for p in state_params:
            value = self.cs8.get(p)
            label_text = None
            if len(p) < 30:
                label_text = p
            elif len(p) < 50:
                label_text = p[:25] + '\n' + p[25:]
            elif len(p) < 75:
                label_text = p[:25] + '\n' + p[25:50] + '\n' + p[50:]
            elif len(p) < 100:
                label_text = p[:25] + '\n' + p[25:50] + \
                    '\n' + p[50:75] + '\n' + p[75:]
            label = QLabel(label_text)
            label.font().setPointSize(8)
            controller = None

            if p.endswith('NAME'):
                widget = QLineEdit()
                widget.setFixedWidth(100)
                controller = WidgetController(self, p, widget)
                widget.setEnabled(False)
            elif p.endswith('1_0'):
                # It is a boolean flag
                widget = QCheckBox()
                widget.setFixedSize(15, 15)
                checked = (value == '1')
                widget.setChecked(checked)
                controller = WidgetController(self, p, widget)
                widget.setEnabled(False)
            else:
                widget = QDoubleSpinBox()
                widget.setFixedWidth(100)
                widget.setMinimum(-99999.0)
                widget.setMaximum(99999.0)
                widget.setValue(float(value))
                controller = WidgetController(self, p, widget)
                widget.setEnabled(False)
            grid_layout.addWidget(label, row, col)
            grid_layout.addWidget(widget, row, col + 1)
            col += 2
            if col == 8:
                col = 0
                row += 1
            self.widget_controllers[p] = controller
        state_sa = QScrollArea(self)
        state_sa.setWidget(state_frame)
        state_label = QLabel('State')
        # self.layout().addWidget(state_sa,1,0)
        self.layout().addWidget(state_sa)

        # --- DI ---
        di_frame = QFrame()
        grid_layout = QGridLayout()
        grid_layout.setContentsMargins(0, 0, 0, 0)
        di_frame.setLayout(grid_layout)
        row = 0
        col = 0
        for p in di_params:
            if p != '.':
                value = self.cs8.get(p)
                label_text = p
                label = QLabel(label_text)
                label.font().setPointSize(8)
                if label_text.startswith('PRI'):
                    label.font().setBold(True)
                widget = QCheckBox()
                widget.setFixedSize(15, 15)
                checked = (value == '1')
                widget.setChecked(checked)
                param_help = di_help[p]
                tooltip = 'Unchecked: %s\nChecked: %s' % (
                    param_help[0], param_help[1])
                widget.setToolTip(tooltip)
                label.setToolTip(tooltip)
                controller = WidgetController(self, p, widget)
                widget.setEnabled(False)
                di_frame.layout().addWidget(widget, row, col)
                di_frame.layout().addWidget(label, row, col + 1)
                col += 2
                if col == 12:
                    col = 0
                    row += 1
                self.widget_controllers[p] = controller

        di_sa = QScrollArea(self)
        di_sa.setWidget(di_frame)
        di_label = QLabel('Digital Inputs')
        # self.layout().addWidget(di_sa,2,0)
        self.layout().addWidget(di_sa)

        # --- DO ---
        do_frame = QFrame()
        grid_layout = QGridLayout()
        grid_layout.setContentsMargins(0, 0, 0, 0)
        do_frame.setLayout(grid_layout)
        row = 0
        col = 0
        for p in do_params:
            if p != '.':
                value = self.cs8.get(p)
                label_text = p
                label = QLabel(label_text)
                label.font().setPointSize(8)
                # 01/06/2011 JJ requirement, for USED PROs, set it bold
                if label_text.startswith(
                        'PRO') and not label_text.startswith('PROCESS'):
                    label.font().setBold(True)
                widget = QCheckBox()
                widget.setFixedSize(15, 15)
                checked = (value == '1')
                widget.setChecked(checked)
                param_help = do_help[p]
                tooltip = 'Unchecked: %s\nChecked: %s' % (
                    param_help[0], param_help[1])
                widget.setToolTip(tooltip)
                label.setToolTip(tooltip)
                controller = WidgetController(self, p, widget)
                widget.setEnabled(False)
                grid_layout.addWidget(widget, row, col)
                grid_layout.addWidget(label, row, col + 1)
                col += 2
                if col == 14:
                    col = 0
                    row += 1
                self.widget_controllers[p] = controller
        do_sa = QScrollArea(self)
        do_sa.setWidget(do_frame)
        do_label = QLabel('Digital Outputs')
        # self.layout().addWidget(do_sa,3,0)
        self.layout().addWidget(do_sa)

        # --- LOG ---
        self.log = QTextEdit()
        # self.layout().addWidget(self.log,4,0)
        self.layout().addWidget(self.log)

        # --- STATUS MESSAGE ---
        self.msg_lbl = QLabel()
        p = 'message'
        controller = WidgetController(self, p, self.msg_lbl)
        self.widget_controllers[p] = controller
        # self.layout().addWidget(self.msg_lbl,5,0)
        self.layout().addWidget(self.msg_lbl)
Esempio n. 56
0
class Player(QMainWindow):
    """A simple Media Player using VLC and Qt
    """
    def __init__(self, master=None):
        QMainWindow.__init__(self, master)
        self.setWindowTitle("Media Player")

        # creating a basic vlc instance
        self.instance = vlc.Instance()
        # creating an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()

        self.createUI()
        self.isPaused = False

    def createUI(self):
        """Set up the user interface, signals & slots
        """
        self.widget = QWidget(self)
        self.setCentralWidget(self.widget)

        # In this widget, the video will be drawn
        if sys.platform == "darwin":  # for MacOS
            from PyQt5.QtWidgets import QMacCocoaViewContainer
            self.videoframe = QMacCocoaViewContainer(0)
        else:
            self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0, 0, 0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)
        self.playbutton.clicked.connect(self.PlayPause)

        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

        self.widget.setLayout(self.vboxlayout)

        open = QAction("&Open", self)
        open.triggered.connect(self.OpenFile)
        exit = QAction("&Exit", self)
        exit.triggered.connect(sys.exit)
        menubar = self.menuBar()
        filemenu = menubar.addMenu("&File")
        filemenu.addAction(open)
        filemenu.addSeparator()
        filemenu.addAction(exit)

        self.timer = QTimer(self)
        self.timer.setInterval(200)
        self.timer.timeout.connect(self.updateUI)

    def PlayPause(self):
        """Toggle play/pause status
        """
        if self.mediaplayer.is_playing():
            self.mediaplayer.pause()
            self.playbutton.setText("Play")
            self.isPaused = True
        else:
            if self.mediaplayer.play() == -1:
                self.OpenFile()
                return
            self.mediaplayer.play()
            self.playbutton.setText("Pause")
            self.timer.start()
            self.isPaused = False

    def Stop(self):
        """Stop player
        """
        self.mediaplayer.stop()
        self.playbutton.setText("Play")

    def OpenFile(self, filename=None):
        """Open a media file in a MediaPlayer
        """
        #OPEN VIDEO FROM COMP
        """if filename is None:
            filename = QFileDialog.getOpenFileName(self, "Open File", os.path.expanduser('~'))[0]
        if not filename:
            return """
        #Open SPECIFIED VIDEO
        filename = "H:\\Projects\\object detection using SSD\\sample\\horses_in_desert.mp4"

        # create the media

        self.media = self.instance.media_new(filename)
        # put the media in the media player
        self.mediaplayer.set_media(self.media)

        # parse the metadata of the file
        self.media.parse()
        # set the title of the track as window title
        self.setWindowTitle(self.media.get_meta(0))

        # the media player has to be 'connected' to the QFrame
        # (otherwise a video would be displayed in it's own window)
        # this is platform specific!
        # you have to give the id of the QFrame (or similar object) to
        # vlc, different platforms have different functions for this
        if sys.platform.startswith('linux'):  # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":  # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
        self.PlayPause()

    def setVolume(self, Volume):
        """Set the volume
        """
        self.mediaplayer.audio_set_volume(Volume)

    def setPosition(self, position):
        """Set the position
        """
        # setting the position to where the slider was dragged
        self.mediaplayer.set_position(position / 1000.0)
        # the vlc MediaPlayer needs a float value between 0 and 1, Qt
        # uses integer variables, so you need a factor; the higher the
        # factor, the more precise are the results
        # (1000 should be enough)

    def updateUI(self):
        """updates the user interface"""
        # setting the slider to the desired position
        self.positionslider.setValue(self.mediaplayer.get_position() * 1000)

        if not self.mediaplayer.is_playing():
            # no need to call this function if nothing is played
            self.timer.stop()
            if not self.isPaused:
                # after the video finished, the play button stills shows
                # "Pause", not the desired behavior of a media player
                # this will fix it
                self.Stop()
class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.initUi()

    def initUi(self):
        self.paintArea = PaintArea()

        # 4
        self.shapeLabel = QLabel("形状: ")
        comboxItems = [
            ["Point", shape.Point],
            ["Line", shape.Line],
            ["Rectangle", shape.Rectangle],
            ["Ellipse", shape.Ellipse],
        ]
        self.shapeComboBox = QComboBox()
        for comboxItem in comboxItems:
            self.shapeComboBox.addItem(*comboxItem)
        # 连接
        self.shapeComboBox.activated.connect(self.paintArea.setShape)

        self.penColorLabel = QLabel("画笔颜色: ")
        self.penColorFrame = QFrame()
        self.penColorFrame.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.penColorFrame.setAutoFillBackground(True)
        self.penColorFrame.setPalette(QPalette(DefaultPenColor))
        self.penColorBtn = QPushButton("更改")
        self.penColorBtn.clicked.connect(self.setPenColor)

        self.penWidthLabel = QLabel("画笔宽度: ")
        self.penWidthSpinBox = QSpinBox()
        self.penWidthSpinBox.setRange(0, 20)
        self.penWidthSpinBox.setValue(DefaultPenSize)
        self.penWidthSpinBox.valueChanged.connect(self.setPenWidth)

        self.penStyleLabel = QLabel("画笔风格: ")
        self.penStyleComboBox = QComboBox()

        # TODO: functionlize
        styleItems = [
            ["SolidLine", int(Qt.SolidLine)],
            ["DashLine", int(Qt.DashLine)],
            ["DotLine", int(Qt.DotLine)],
            ["DashDotLine", int(Qt.DashDotLine)],
            ["DashDotDotLine", int(Qt.DashDotDotLine)],
            ["CustomDashLine", int(Qt.CustomDashLine)],
        ]
        for styleItem in styleItems:
            self.penStyleComboBox.addItem(*styleItem)

        self.penStyleComboBox.activated.connect(self.setPenStyle)

        self.penCapLabel = QLabel("画笔顶帽: ")
        self.penJoinLabel = QLabel("画笔连接点:  ")
        self.fillRuleLavel = QLabel("填充模式: ")
        self.fillRuleComboBox = QComboBox()
        self.fillRuleComboBox.addItem("Odd Even", Qt.OddEvenFill)
        self.fillRuleComboBox.addItem("Winding", Qt.WindingFill)
        self.fillRuleComboBox.activated.connect(self.setFillRule)

        self.brushColorLabel = QLabel("画刷颜色: ")
        self.brushColorFrame = QFrame()
        self.brushColorFrame.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.brushColorFrame.setAutoFillBackground(True)
        self.brushColorFrame.setPalette(QPalette(DefaultPenColor))
        self.brushColorBtn = QPushButton("更改")
        self.brushColorBtn.clicked.connect(self.setBrushColor)

        self.brushStyleLabel = QLabel("画刷风格: ")
        self.brushStyleComboBox = QComboBox()

        brushStyleItems = [
            ["NoBrush",
             int(Qt.NoBrush)], ["SolidPattern",
                                int(Qt.SolidPattern)],
            ["Dense1Pattern", int(Qt.Dense1Pattern)],
            ["Dense2Pattern", int(Qt.Dense2Pattern)],
            ["Dense3Pattern", int(Qt.Dense3Pattern)],
            ["Dense4Pattern", int(Qt.Dense4Pattern)],
            ["Dense5Pattern", int(Qt.Dense5Pattern)],
            ["Dense6Pattern", int(Qt.Dense6Pattern)],
            ["Dense7Pattern", int(Qt.Dense7Pattern)],
            ["HorPattern", int(Qt.HorPattern)],
            ["VerPattern", int(Qt.VerPattern)],
            ["CrossPattern", int(Qt.CrossPattern)],
            ["BDiagPattern", int(Qt.BDiagPattern)],
            ["FDiagPattern", int(Qt.FDiagPattern)],
            ["DiagCrossPattern", int(Qt.DiagCrossPattern)],
            ["LinearGradientPattern",
             int(Qt.LinearGradientPattern)],
            ["ConicalGradientPattern",
             int(Qt.ConicalGradientPattern)],
            ["RadialGradientPattern",
             int(Qt.RadialGradientPattern)],
            ["TexturePattern", int(Qt.TexturePattern)]
        ]
        for styleItem in brushStyleItems:
            self.brushStyleComboBox.addItem(*styleItem)

        self.brushStyleComboBox.activated.connect(self.setBrushStyle)

        self.selectPicBtn = QPushButton("选择图片")
        self.selectPicBtn.clicked.connect(self.openPic)

        # tag: create and set widgets
        self.cleanBtn = QPushButton("清屏")
        self.cleanBtn.clicked.connect(self.cleanAll)
        # 3

        # 2

        # left area gen
        self.rightLayout = QGridLayout()
        rightWidgets = [
            [self.shapeLabel, self.shapeComboBox],
            [self.penColorLabel, self.penColorFrame, self.penColorBtn],
            [self.penWidthLabel, self.penWidthSpinBox],
            [self.fillRuleLavel, self.fillRuleComboBox],
            [self.penStyleLabel, self.penStyleComboBox],
            [self.brushColorLabel, self.brushColorFrame, self.brushColorBtn],
            [self.brushStyleLabel, self.brushStyleComboBox],
            [self.cleanBtn],
            [self.selectPicBtn],
        ]
        # tag: add and show widgets
        for r in range(len(rightWidgets)):
            for c in range(len(rightWidgets[r])):
                self.rightLayout.addWidget(rightWidgets[r][c], r, c)
        # 1
        self.mainLayout = QHBoxLayout(self)
        self.mainLayout.addWidget(self.paintArea)
        self.mainLayout.addLayout(self.rightLayout)

        #
        self.mainLayout.setStretchFactor(self.paintArea, 1)
        self.mainLayout.setStretchFactor(self.rightLayout, 0)

    def setPenColor(self):

        tmpColor = QColorDialog.getColor()
        self.penColorFrame.setPalette(QPalette(tmpColor))
        self.paintArea.initPoint()
        self.paintArea.pen.setColor(tmpColor)  # use this

    def setPenWidth(self, value):
        tmpWidth = value
        self.paintArea.initPoint()

        self.paintArea.pen.setWidth(tmpWidth)

    def setFillRule(self, value):
        rule = Qt.FillRule(
            int(
                self.fillRuleComboBox.itemData(
                    self.fillRuleComboBox.currentIndex(), Qt.UserRole)))
        self.paintArea.setFilRule(rule)

    def setPenStyle(self, value):
        style = Qt.PenStyle(
            int(self.penStyleComboBox.itemData(value, Qt.UserRole)))
        self.paintArea.initPoint()
        self.paintArea.pen.setStyle(style)

    def openPic(self):
        name = QFileDialog.getOpenFileName(self, "打开", "/", "*")

        self.paintArea.pix = QPixmap(name[0])

    def setBrushColor(self):
        """setBrushColor
        """
        tmpColor = QColorDialog.getColor()
        self.brushColorFrame.setPalette(QPalette(tmpColor))
        self.paintArea.initPoint()
        self.paintArea.brush.setColor(tmpColor)  # use this

    def setBrushStyle(self, value):
        """setBrushStyle
        """
        style = Qt.BrushStyle(
            int(self.brushStyleComboBox.itemData(value, Qt.UserRole)))
        self.paintArea.initPoint()
        self.paintArea.brush = QBrush(style)

    # tag: next func
    def cleanAll(self):
        """should i do this?
        """
        self.paintArea.pix.fill(Qt.white)
        self.paintArea.initPoint()
        self.paintArea.update()
Esempio n. 58
0
def make_separator(parent, direction='vertical'):
    "Makes a separator line"
    sep = QFrame(parent)
    sep.setFrameShape(QFrame.VLine if direction ==
                      'vertical' else QFrame.HLine)
    return sep
Esempio n. 59
0
    def createUI(self):
        """Set up the user interface, signals & slots
        """
        self.widget = QWidget(self)
        self.setCentralWidget(self.widget)

        # In this widget, the video will be drawn
        if sys.platform == "darwin":  # for MacOS
            from PyQt5.QtWidgets import QMacCocoaViewContainer
            self.videoframe = QMacCocoaViewContainer(0)
        else:
            self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0, 0, 0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)
        self.playbutton.clicked.connect(self.PlayPause)

        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.time_label = QLabel("<center>0</center>")
        self.coordinates = QLabel("<center>x, y</center>")
        self.hbuttonbox.addWidget(self.time_label)
        self.hbuttonbox.addWidget(self.coordinates)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

        self.widget.setLayout(self.vboxlayout)

        open = QAction("&Open", self)
        open.triggered.connect(self.OpenFile)
        exit = QAction("&Exit", self)
        exit.triggered.connect(sys.exit)
        menubar = self.menuBar()
        filemenu = menubar.addMenu("&File")
        filemenu.addAction(open)
        filemenu.addSeparator()
        filemenu.addAction(exit)

        self.timer = QTimer(self)
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.updateUI)
Esempio n. 60
0
    def init_ui(self):
        self.setFont(QFont('Segoe UI'))

        grid_layout = QGridLayout()
        grid_layout.setSpacing(10)

        self.setGeometry(0, 0, 385, 750)
        qtRectangle = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        menu_bar = self.menuBar()
        file_menu = menu_bar.addMenu('File')
        plot_menu = menu_bar.addMenu('Plots')

        create_new_db = QAction('Create Database', self)
        create_new_db.triggered.connect(self.create_database)
        file_menu.addAction(create_new_db)

        self.create_plots = QAction('View Plots', self)
        self.create_plots.triggered.connect(self.generate_plots)
        plot_menu.addAction(self.create_plots)

        self.create_plots.setDisabled(True)

        self.setWindowTitle('Nutrient Stock Standard Tracker')

        database_path_label = QLabel('Path to Database File:')

        self.database_path_field = QLineEdit()

        database_browse = QPushButton('Browse')
        database_browse.clicked.connect(self.path_browse)

        linesep1 = QFrame()
        linesep1.setFrameShape(QFrame.HLine)
        linesep1.setFrameShadow(QFrame.Sunken)

        past_entries_label = QLabel('Previous Entries: ')

        self.standard_entries = QListWidget()

        self.view_entry = QPushButton('View')
        self.view_entry.clicked.connect(self.view_existing)

        self.new_entry = QPushButton('New')
        self.new_entry.clicked.connect(self.enter_new)
        self.new_entry.setDisabled(True)

        grid_layout.addWidget(database_path_label, 0, 0, 1, 2)
        grid_layout.addWidget(self.database_path_field, 1, 0, 1, 2)
        grid_layout.addWidget(database_browse, 2, 1, 1, 1)

        grid_layout.addWidget(linesep1, 3, 0, 1, 2)

        grid_layout.addWidget(past_entries_label, 4, 0, 1, 2)
        grid_layout.addWidget(self.standard_entries, 5, 0, 8, 2)

        grid_layout.addWidget(self.view_entry, 13, 0, 1, 2)
        grid_layout.addWidget(self.new_entry, 14, 0, 1, 2)

        self.centralWidget().setLayout(grid_layout)

        appdata_path = os.getenv('LOCALAPPDATA')

        if os.path.isdir(appdata_path + '/' + 'Stocks Tracker'):
            if os.path.isfile(appdata_path + '/' + 'Stocks Tracker' + '/' + 'path_memory.txt'):
                with open(appdata_path + '/' + 'Stocks Tracker' + '/' + 'path_memory.txt', 'r') as file:
                    remembered_path = file.read()
                    self.database_path_field.setText(remembered_path)
                    self.populate_list()

        else:
            os.mkdir(appdata_path + '/' + 'Stocks Tracker')
            with open(appdata_path + '/' + 'Stocks Tracker' + '/' + 'path_memory.txt', 'w+') as file:
                pass

        self.show()