def actionCalled(self):
        """
        Prikazuje dijalog za unos imena nove knjige, kreira novu instancu knjige sa unetim imenom
        """
        parent = QApplication.instance().model
        newName, ok = QInputDialog.getText(None, "New Book name",
                                           "Enter desired new name")
        if ok:
            if parent.isValidName(newName):
                newBook = Book(newName)
                book = QApplication.instance().mainWindow.newTab(newBook)
                parent.addChild(book)

            else:
                while not parent.isValidName(newName):
                    dialog = QMessageBox()
                    dialog.setWindowTitle("Error")
                    dialog.setText("That name is not valid")
                    dialog.setWindowIcon(QIcon("src/notification.png"))
                    dialog.setModal(True)
                    dialog.exec_()
                    newName, cancel = QInputDialog.getText(
                        None, "New Book name", "Enter desired new name")
                    if not cancel:
                        break
                    else:
                        if parent.isValidName(newName):
                            newBook = Book(newName)
                            book = QApplication.instance().mainWindow.newTab(
                                newBook)
                            parent.addChild(book)
                            break
Example #2
0
 def setDarkTheme(cls):
     """
     Switch UI to a dark theme
     """
     QApplication.instance().setStyleSheet(getStyleSheet())
     QApplication.instance().setPalette(
         QApplication.style().standardPalette())
Example #3
0
 def initGlobalStyle(cls, *args):
     """
     Initialize style that will be used across the application
     """
     QApplication.instance().setStyleSheet("")
     QApplication.instance().setPalette(
         QApplication.style().standardPalette())
Example #4
0
def show(path: str, second_screen: bool = False) -> int:
    if not QApplication.instance():
        app = QApplication()
    else:
        app = QApplication.instance()
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    # setup asyncio loop
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    # create widget
    widget = SketchViewer(pathlib.Path(path))

    # handle window sizing
    screens = app.screens()
    if second_screen and len(screens) > 1:
        widget.windowHandle().setScreen(screens[1])
        r = screens[1].geometry()
        widget.move(r.topLeft())
        widget.resize(r.width(), r.height())
    else:
        sz = app.primaryScreen().availableSize()
        widget.move(int(sz.width() * 0.05), int(sz.height() * 0.1))
        widget.resize(int(sz.width() * 0.9), int(sz.height() * 0.8))

    # run
    widget.show()
    return app.exec_()
Example #5
0
    def __init__(self):
        WizardPage.__init__(self)
        self.fetch_config = None
        self.app_model = QStringListModel(
            REGISTRY.names(
                lambda klass: not getattr(klass, "disable_in_gui", None)))
        self.ui.app_combo.setModel(self.app_model)
        if mozinfo.bits == 64:
            if mozinfo.os == "mac":
                self.bits_model = QStringListModel(["64"])
                bits_index = 0
            else:
                self.bits_model = QStringListModel(["32", "64"])
                bits_index = 1
        elif mozinfo.bits == 32:
            self.bits_model = QStringListModel(["32"])
            bits_index = 0
        self.ui.bits_combo.setModel(self.bits_model)
        self.ui.bits_combo.setCurrentIndex(bits_index)
        self.build_type_model = QStringListModel()

        self.ui.app_combo.currentIndexChanged.connect(self._set_fetch_config)
        self.ui.bits_combo.currentIndexChanged.connect(self._set_fetch_config)
        self.ui.app_combo.setCurrentIndex(
            self.ui.app_combo.findText("firefox"))

        self.ui.repository.textChanged.connect(self._on_repo_changed)

        completer = QCompleter(sorted(get_branches()), self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.ui.repository.setCompleter(completer)
        QApplication.instance().focusChanged.connect(self._on_focus_changed)
Example #6
0
 def __init__(self,
              parent=None,
              command="/bin/bash",
              font_name="Monospace",
              font_size=18):
     super(TerminalWidget, self).__init__(parent)
     self.parent().setTabOrder(self, self)
     self.setFocusPolicy(Qt.WheelFocus)
     self.setAutoFillBackground(False)
     self.setAttribute(Qt.WA_OpaquePaintEvent, True)
     self.setCursor(Qt.IBeamCursor)
     font = QFont(font_name)
     font.setPixelSize(font_size)
     self.setFont(font)
     self._session = None
     self._last_update = None
     self._screen = []
     self._text = []
     self._cursor_rect = None
     self._cursor_col = 0
     self._cursor_row = 0
     self._dirty = False
     self._blink = False
     self._press_pos = None
     self._selection = None
     self._clipboard = QApplication.clipboard()
     QApplication.instance().lastWindowClosed.connect(Session.close_all)
     if command:
         self.execute()
 def testCustomScene(self):  # For PYSIDE-868, see above
     scene = CustomScene()
     view = QGraphicsView(scene)
     view.show()
     while scene.dpi == 0:
         QApplication.instance().processEvents()
     view.hide()
Example #8
0
 def run(self):
     while (1):
         print(type(QtCore.SIGNAL("UPDATE()")))
         # SIGNAL is application wide
         QApplication.instance().emit(QtCore.SIGNAL("UPDATE()"))
         #             self.app.emit(QtCore.SIGNAL("UPDATE()"))
         time.sleep(self.fDelay)
Example #9
0
    def wait_for_sound(self, sound, fail=False, play=True, playing=False):
        # Tracked while loading
        self.assertIn(sound, QApplication.instance().tracked)

        def delayed_play():
            if not self.played:
                self.played = True
                QTimer.singleShot(0, sound.play)

        if play and not playing:
            sound._Sound__player.mediaStatusChanged.connect(delayed_play)
            sound.set_volume(0)

        # Record tracked set before pausing sound
        tracked = set([])
        QTimer.singleShot(
            200, lambda: tracked.update(QApplication.instance().tracked))
        QTimer.singleShot(300, sound.rewind)
        QApplication.instance().exec_()

        self.assertEqual(sound._Sound__sound_loaded, not fail)
        if fail or not (play or playing):
            self.assertNotIn(sound, tracked)
        elif play:
            # Sound was tracked before pausing
            self.assertIn(sound, tracked)

        self.assertEqual(sound._Sound__player.state(),
                         QMediaPlayer.StoppedState)
    def openMenu(self, position):
        """
        Metoda povezana na customContextMenuRequested. Kreira kontekstni meni sa akcijama dodavanja, brisanja i promene naziva elemenata.
        Kontekstni meni se prikazuje na poziciji na kojoj se nalazio kursor misa.

        Args:
            position(QPoint): pozicija kursora misa

        """
        self.contextMenu = QMenu()

        actionManager = QApplication.instance().actionManager

        tmp = QApplication.instance().selectionModel
        if not isinstance(tmp, Text) and not isinstance(tmp, Picture):
            self.contextMenu.addAction(actionManager.addChildAction)
            self.contextMenu.addAction(actionManager.addAtAction)
            self.contextMenu.addAction(actionManager.addBefore)
            self.contextMenu.addSeparator()
            if not isinstance(tmp, Page):
                self.contextMenu.addAction(actionManager.renameNodeAction)
        #if isinstance(tmp, Picture):
        #self.contextMenu.addAction(actionManager.renameNodeAction)
        self.contextMenu.addAction(actionManager.removeChildAction)

        # prikaz kontekstnog menija
        self.contextMenu.exec_(self.viewport().mapToGlobal(position))
Example #11
0
 def onExit(self):  # release resources
     if self.thread_script is not None: self.thread_script.terminate()
     self.thread_io.terminate()
     self.thread_image.terminate()
     self.logger.info("Resource cleared, program will exit.")
     self.thread_log.terminate()
     QApplication.instance().quit()
Example #12
0
    def __init__(self, fileName: str, parent: QWidget = None):
        """
        :param fileName: name of the file to read.
        :param parent: parent widget.
        """
        self.viewer = QRemoteDesktop(800, 600)
        super().__init__(self.viewer, parent)
        QApplication.instance().aboutToQuit.connect(self.onClose)

        self.fileName = fileName
        self.file = open(self.fileName, "rb")
        self.eventHandler = PlayerMessageHandler(self.widget, self.text)

        replay = Replay(self.file)
        self.thread = ReplayThread(replay)
        self.thread.eventReached.connect(self.readEvent)
        self.thread.timeUpdated.connect(self.onTimeUpdated)
        self.thread.clearNeeded.connect(self.clear)
        self.thread.start()

        self.controlBar = ReplayBar(replay.duration)
        self.controlBar.play.connect(self.thread.play)
        self.controlBar.pause.connect(self.thread.pause)
        self.controlBar.seek.connect(self.thread.seek)
        self.controlBar.speedChanged.connect(self.thread.setSpeed)

        self.layout().insertWidget(0, self.controlBar)

        self.player = PlayerMessageLayer()
        self.player.addObserver(self.eventHandler)
Example #13
0
    def initGlobalStyle(cls, *args):
        """
        Initialize style that will be used across the application

        .. note::

            A limited set of pre-defined styles are available

            If desired it is possible to create a completely custom style, see
            the links below...

            Best left for major application creation in C++,
            not recommended for Python

            https://doc.qt.io/qt-5/qstyle.html#creating-a-custom-style
            https://doc.qt.io/qt-5/qstyleplugin.html
            https://doc.qt.io/qt-5/qstylefactory.html

        """
        print("\n\nAvailable styles: " +
              ", ".join(sorted(QStyleFactory.keys())))
        style = "Fusion"
        for arg in args:
            if arg.lower() in [k.lower() for k in QStyleFactory.keys()]:
                style = arg
        style = QStyleFactory.create(style)
        QApplication.instance().setStyle(style)
Example #14
0
    def __init__(self, fileName: str, parent: QWidget):
        """
        :param fileName: name of the file to read.
        :param parent: parent widget.
        """
        self.viewer = QRemoteDesktop(800, 600, parent)
        super().__init__(self.viewer, parent)
        QApplication.instance().aboutToQuit.connect(self.onClose)

        self.fileName = fileName
        self.file = open(self.fileName, "rb")
        self.eventHandler = PlayerEventHandler(self.widget, self.text)

        replay = Replay(self.file)
        self.reader = ReplayReader(replay)
        self.thread = ReplayThread(replay)
        self.thread.eventReached.connect(self.readEvent)
        self.thread.timeUpdated.connect(self.onTimeUpdated)
        self.thread.clearNeeded.connect(self.clear)
        self.thread.start()

        self.controlBar = ReplayBar(replay.duration)
        self.controlBar.play.connect(self.thread.play)
        self.controlBar.pause.connect(self.thread.pause)
        self.controlBar.seek.connect(self.thread.seek)
        self.controlBar.speedChanged.connect(self.thread.setSpeed)
        self.controlBar.scaleCheckbox.stateChanged.connect(
            self.setScaleToWindow)
        self.controlBar.button.setDefault(True)

        self.tabLayout.insertWidget(0, self.controlBar)
Example #15
0
 def testInstanceObject(self):
     TestObject.createApp()
     app1 = QApplication.instance()
     app2 = QApplication.instance()
     app1.setObjectName("MyApp")
     self.assertEqual(app1, app2)
     self.assertEqual(app2.objectName(), app1.objectName())
     app1.destroyed.connect(self.appDestroyed)
Example #16
0
    def __init__(self, address, port, parent: QWidget = None):
        super().__init__(parent)
        QApplication.instance().aboutToQuit.connect(self.onClose)

        self.server = LiveThread(address, port, self.onConnection)
        self.server.start()
        self.connectionReceived.connect(self.createLivePlayerTab)
        self.queue = Queue()
Example #17
0
 def testInstanceObject(self):
     TestObject.createApp()
     app1 = QApplication.instance()
     app2 = QApplication.instance()
     app1.setObjectName("MyApp")
     self.assertEqual(app1, app2)
     self.assertEqual(app2.objectName(), app1.objectName())
     app1.destroyed.connect(self.appDestroyed)
Example #18
0
 def __init__(self, interval):
     # make sure we actually have a qapp
     if QApplication.instance() is None:
         QApplication(sys.argv)
     Thread.__init__(self)
     self.interval = interval
     self.event = Event()
     self.qtapp = QApplication.instance()
    def setup_connections(self):
        self.search_box.textChanged.connect(self.search_food)
        self.add_to_fridge_btn.clicked.connect(self.add_to_fridge)

        QApplication.instance().focusChanged.connect(self.focus_changed)

        add_shortcut = QShortcut(QKeySequence(Qt.Key_Return), self.search_view)
        add_shortcut.activated.connect(self.add_to_fridge)
Example #20
0
    def __init__(self):
        super().__init__()
        self.mainUI = QUiLoader().load(mainWindowPath)
        self.subUI = QUiLoader().load(subWindowPath)
        self.mainUI.setWindowTitle('EDAutopilot v2')
        # self.logger = Logger(self.mainUI.logText,toFile=True) # start logger
        self.thread_log = LogThread()
        self.logger = self.thread_log.getLogger()
        self.thread_log._logSignal.connect(self.onReceiveLog)
        self.thread_log.start()

        self.config = Config(logger=self.logger)
        if self.config.get('Main', 'log_to_file'):
            self.thread_log.initFile(
                self.config.get('Main', 'override_previous_logs'))
        self.keysDict = init_keybinds(self.logger)

        self.mainUI.actionScriptName.setDisabled(True)

        self.thread_io = IOThread(self.usingWatchdog, logger=self.logger)
        self.thread_io._ioSignal.connect(self.updateStatus)
        self.thread_io.start()

        self.image_templates = Image(logger=self.logger, config=self.config)
        self.thread_image = ImageThread(logger=self.logger)
        self.thread_image._imageSignal.connect(self.updateImage)
        self.thread_image.start()
        self.thread_script = None  # initialize in loadScript()

        self.mainUI.logText.customContextMenuRequested.connect(
            self._onRightClickLog
        )  # connect to ContextMenu in logging area (Copy, debug view, clear screen...)

        self.mainUI.actionLoadScript.triggered.connect(
            lambda: self.loadScript(None))
        self.mainUI.actionStopScript.triggered.connect(self.stopScript)
        self.mainUI.actionSettings.triggered.connect(self.onSettings)
        self.mainUI.actionAbout.triggered.connect(self.onAbout)
        self.mainUI.actionExit.triggered.connect(self.onExit)
        QApplication.instance().aboutToQuit.connect(self.onExit)

        self.mainUI.actionScriptName.setText('(Empty)')
        self.locationLabel = QLabel('Loc: None'.ljust(49))
        self.targetLabel = QLabel('Target: None'.ljust(49))
        self.alignedLabel = QLabel('Align: 0'.ljust(9))
        self.fpsLabel = QLabel('FPS: 0'.ljust(8))
        self.scriptStatusLabel = QLabel('Idle'.ljust(20))
        self.mainUI.statusBar().addWidget(self.locationLabel)
        self.mainUI.statusBar().addWidget(self.targetLabel)
        self.mainUI.statusBar().addWidget(self.alignedLabel)
        self.mainUI.statusBar().addWidget(self.fpsLabel)
        self.mainUI.statusBar().addWidget(self.scriptStatusLabel)

        self._setScriptActionsState(True)

        if self.config.get('GUI', 'load_default_on_startup'):
            defaultPath = self.config.get('GUI', 'default_script')
            if defaultPath is not None: self.loadScript(path=defaultPath)
    def __init__(self,parent = None):
        super().__init__()
        
        self.parent = parent

        self.setText(str(1 + int(numpy.random.random() * 10)))        
        self.show()
        
        QApplication.instance().connect(QtCore.SIGNAL("CHANGE_COLOR(QColor)"),self.ChangeColor)
Example #22
0
    def __init__(self):
        super().__init__()

        if QApplication.instance():
            self.palette = QApplication.instance().palette()
        else:
            self.palette = QPalette()

        self.color = None
Example #23
0
 def canceled(self):
     self.model.requestInterruption()
     self.progress.setLabelText("Cancelling...")
     self.progress.setEnabled(False)
     self.progress.show()
     self.progress.activateWindow()
     QApplication.instance().processEvents()
     while self.model.isRunning():  #wait until model is finished
         pass
     self.progress.hide()
    def run_button_clicked(self):
        self.clear_console()
        options = QApplication.instance().main_window.centerWidget.layout(
        ).inputs_layout.get_options()
        controller = QApplication.instance().controller
        self.progress.show()
        function = options["function"]
        num_var = options["num_var"]

        ga(function, int(num_var), options, controller)
    def __init__(self):
        QSplashScreen.__init__(self)
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        height = QApplication.instance().primaryScreen().size().height() * .25
        width = QApplication.instance().primaryScreen().size().width() * .25

        logo = QPixmap('../resources/splash_screen_02.png').scaledToHeight(
            height)

        self.setPixmap(logo)
Example #26
0
 def initGlobalStyle(cls, *args):
     """
     Initialize style that will be used across the application
     """
     QApplication.instance().setStyleSheet(getStyleSheet())
     # For the purposes of demo'ing If a palette has been applied previously
     # as well as reset back to standard, simply running setStyleSheet() will
     # unexpectedly re-apply palette settings!
     QApplication.instance().setPalette(
         QApplication.style().standardPalette())
Example #27
0
 def __init__(self, 引擎名称, parent=None):
     super().__init__(parent)
     self.持续录音 = True
     self.正在运行 = 0
     self.引擎名称 = 引擎名称
     self.得到引擎信息()
     self.tokenId = 0
     self.tokenExpireTime = 0
     self.构建按键发送器()
     QApplication.instance().aboutToQuit.connect(self.要退出了)
    def _setup_qApp(self):
        """
        Only one qApp can exist at a time, so check before creating one.

        Returns:
            QApplication: a setup QApplication

        There are three classes:
            * QCoreApplication - base class. Used in command line applications.
            * QGuiApplication - base class + GUI capabilities. Used in QML applications.
            * QApplication - base class + GUI + support for widgets. Use it in QtWidgets applications.

        See:
            * https://forum.qt.io/topic/94834/differences-between-qapplication-qguiappication-qcoreapplication-classes/3
            * https://github.com/matplotlib/matplotlib/blob/9984f9c4db7bfb02ffca53b7823acb8f8e223f6a/lib/matplotlib/backends/backend_qt5.py#L98
        """

        self.qApp = QApplication.instance()

        if self.qApp is None:
            self.logger.warning("QApplication.instance is None.")

            # Kickstart()

            # Did it work now
            self.qApp = QApplication.instance()

            if self.qApp is None:

                self.logger.error(r"""ERROR: QApplication.instance is None.
                Did you run a cell with the magic in IPython?
                ```python
                    %gui qt
                ```
                This command allows IPython to integrate itself with the Qt event loop,
                so you can use both a GUI and an interactive prompt together.
                Reference: https://ipython.readthedocs.io/en/stable/config/eventloops.html
                """)

        # for window platofrms only
        # QApplication.platformName() -- on mac: 'cocoa'
        if os.name.startswith('nt'):
            # Arbitrary string, needed for icon in taskbar to be custom set proper
            # https://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7
            import ctypes
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                self._myappid)

        app = self.qApp
        if app:
            app.setOrganizationName(r"IBM Quantum Metal")
            app.setOrganizationDomain(r"https://www.ibm.com/quantum-computing")
            app.setApplicationName(r"Qiskit Metal")

        return self.qApp
Example #29
0
 def initGlobalStyle(cls, *args):
     """
     Initialize style that will be used across the application
     """
     palette = QPalette()
     palette.setColor(QPalette.WindowText, QColor(150, 150, 255))
     palette.setBrush(QPalette.Window,
                      QBrush(Qt.darkMagenta, Qt.Dense7Pattern))
     palette.setColor(QPalette.Base, Qt.darkGreen)
     palette.setColor(QPalette.AlternateBase, Qt.darkMagenta)
     QApplication.instance().setPalette(palette)
Example #30
0
    def __init__(self, address: str, port: int, updateCountSignal: Signal,
                 options: Dict[str, object], parent: QWidget):
        super().__init__(options, parent)

        QApplication.instance().aboutToQuit.connect(self.onClose)

        self.server = LiveThread(address, port, self.onConnection)
        self.server.start()
        self.connectionReceived.connect(self.createLivePlayerTab)
        self.queue = Queue()
        self.updateCountSignal = updateCountSignal
Example #31
0
 def testSetProxyStyle(self):
     label = QLabel("QtWidgets/ProxyStyle test")
     baseStyle = QStyleFactory.create(
         QApplication.instance().style().objectName())
     self.assertTrue(baseStyle)
     proxyStyle = ProxyStyle(baseStyle)
     label.setStyle(proxyStyle)
     label.show()
     while not label.windowHandle().isExposed():
         QApplication.instance().processEvents()
     self.assertTrue(proxyStyle.polished > 0)
Example #32
0
def createNextWebView():
    global functionID

    nListCount = len(FUNCTIONS_LIST) - 1
    functionID = functionID + 1
    print functionID

    if functionID < nListCount:
        createWebView( functionID )
    else:
        QTimer.singleShot(300, QApplication.instance().quit)
Example #33
0
    def createActions(self):

        self.newAct = QAction(QIcon.fromTheme("document-new", QIcon(':/images/new.png')), "&New", self,
                shortcut=QKeySequence.New, statusTip="Create a new file",
                triggered=self.newFile)

        self.openAct = QAction(QIcon.fromTheme("document-open", QIcon(':/images/open.png')), "&Open...", self,
                shortcut=QKeySequence.Open, statusTip="Open an existing file",
                triggered=self.open)

        self.saveAct = QAction(QIcon.fromTheme("document-save", QIcon(':/images/save.png')), "&Save", self,
                shortcut=QKeySequence.Save,
                statusTip="Save the document to disk", triggered=self.save)

        self.saveAsAct = QAction("Save &As...", self,
                shortcut=QKeySequence.SaveAs,
                statusTip="Save the document under a new name",
                triggered=self.saveAs)

        self.exitAct = QAction("E&xit", self, shortcut=QKeySequence.Quit,
                statusTip="Exit the application",
                triggered=QApplication.instance().closeAllWindows)

        self.cutAct = QAction(QIcon.fromTheme("edit-cut", QIcon(':/images/cut.png')), "Cu&t", self,
                shortcut=QKeySequence.Cut,
                statusTip="Cut the current selection's contents to the clipboard",
                triggered=self.cut)

        self.copyAct = QAction(QIcon.fromTheme("edit-copy", QIcon(':/images/copy.png')), "&Copy", self,
                shortcut=QKeySequence.Copy,
                statusTip="Copy the current selection's contents to the clipboard",
                triggered=self.copy)

        self.pasteAct = QAction(QIcon.fromTheme("edit-paste", QIcon(':/images/paste.png')), "&Paste", self,
                shortcut=QKeySequence.Paste,
                statusTip="Paste the clipboard's contents into the current selection",
                triggered=self.paste)

        self.closeAct = QAction("Cl&ose", self,
                statusTip="Close the active window",
                triggered=self.mdiArea.closeActiveSubWindow)

        self.closeAllAct = QAction("Close &All", self,
                statusTip="Close all the windows",
                triggered=self.mdiArea.closeAllSubWindows)

        self.tileAct = QAction("&Tile", self, statusTip="Tile the windows",
                triggered=self.mdiArea.tileSubWindows)

        self.cascadeAct = QAction("&Cascade", self,
                statusTip="Cascade the windows",
                triggered=self.mdiArea.cascadeSubWindows)

        self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild,
                statusTip="Move the focus to the next window",
                triggered=self.mdiArea.activateNextSubWindow)

        self.previousAct = QAction("Pre&vious", self,
                shortcut=QKeySequence.PreviousChild,
                statusTip="Move the focus to the previous window",
                triggered=self.mdiArea.activatePreviousSubWindow)

        self.separatorAct = QAction(self)
        self.separatorAct.setSeparator(True)

        self.aboutAct = QAction("&About", self,
                statusTip="Show the application's About box",
                triggered=self.about)

        self.aboutQtAct = QAction("About &Qt", self,
                statusTip="Show the Qt library's About box",
                triggered=QApplication.instance().aboutQt)