Exemplo n.º 1
0
def main():
    # Qml gui style
    #os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
    #os.environ["QT_QUICK_CONTROLS_MATERIAL_VARIANT"] = "Dense"

    # Define paths
    current_path = os.path.dirname(os.path.abspath(__file__))
    main_qml_path = QUrl.fromLocalFile(
        os.path.join(current_path, "Gui", "main.qml"))
    gui_path = str(QUrl.fromLocalFile(os.path.join(current_path)).toString())
    easyAppGui_path = easyappgui.__path__[0]
    #print("current_path", current_path)
    #print("main_qml_path", main_qml_path)
    #print("gui_path", gui_path)
    #print("easyAppGui_path", easyAppGui_path)

    # Create a proxy object between python logic and QML GUI
    py_qml_proxy_obj = PyQmlProxy()

    # Create application
    app = QApplication(sys.argv)
    app.setApplicationName(py_qml_proxy_obj.appName)

    # Create qml application engine
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("_pyQmlProxyObj", py_qml_proxy_obj)
    engine.addImportPath(easyAppGui_path)
    engine.addImportPath(gui_path)
    engine.load(main_qml_path)

    # Event loop
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
Exemplo n.º 2
0
def main():
    # Define paths
    current_path = os.path.dirname(os.path.abspath(__file__))
    # current_path = os.path.dirname(sys.argv[0])
    main_qml_path = QUrl.fromLocalFile(
        os.path.join(current_path, "Gui", "main.qml"))
    gui_path = str(QUrl.fromLocalFile(os.path.join(current_path)).toString())
    easyAppGui_path = easyAppGui.__path__[0]
    #print("current_path", current_path)
    #print("main_qml_path", main_qml_path)
    #print("gui_path", gui_path)
    #print("easyAppGui_path", easyAppGui_path)

    # Create a proxy object between python logic and QML GUI
    py_qml_proxy_obj = PyQmlProxy()

    # Create application
    app = QApplication(sys.argv)
    app.setApplicationName(py_qml_proxy_obj.appName)

    # Create qml application engine
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty(
        "_screenshotPath",
        os.path.join(current_path, "..", "dist", "screenshot.png"))
    engine.rootContext().setContextProperty("_pyQmlProxyObj", py_qml_proxy_obj)
    engine.addImportPath(easyAppGui_path)
    engine.addImportPath(gui_path)
    engine.load(main_qml_path)

    # Event loop
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
Exemplo n.º 3
0
 def get(self, key):
     img = self._images.get(key)
     if img is None:
         img = FutureImage(key, self._img_file(key), self._img_url(key),
                           self._http_session)
         self._images[key] = img
         img.available.connect(self._on_new_img)
     if img.image:
         return QUrl.fromLocalFile(img._filename)
     else:
         return QUrl.fromLocalFile(self._default_image)
Exemplo n.º 4
0
 def last_save_dir_handler(self) -> None:
     """
     Handler for last save dir button.
     :return None:
     """
     self._logger.debug("running")
     if self._save_dir == "":
         QDesktopServices.openUrl(QUrl.fromLocalFile(QDir().homePath()))
     else:
         QDesktopServices.openUrl(QUrl.fromLocalFile(self._save_dir))
     self._logger.debug("done")
Exemplo n.º 5
0
 def selectFile(self, file):
     self.fileName = file[len(self.prefix):]
     self.colorImage = QUrl.fromLocalFile(self.fileName)
     self.image = cv2.imread(self.fileName, cv2.IMREAD_GRAYSCALE)
     path = Path(self.fileName)
     newFileName = self.tmp_dir + "/" + path.name[:-len(
         path.suffix)] + "_bw" + path.suffix
     cv2.imwrite(newFileName, self.image)
     self.bwImage = QUrl.fromLocalFile(newFileName)
     self.showProcessImage()
     self.showContours()
     self.showColor()
Exemplo n.º 6
0
    def __open_last_save_dir(self):
        """
        Opens native file manager to the last directory used for an experiment.
        If no experiment has been performed, opens default home path.
        :return:
        """

        self.logger.debug("running")
        if self.__save_dir == "":
            QDesktopServices.openUrl(QUrl.fromLocalFile(QDir().homePath()))
        else:
            QDesktopServices.openUrl(QUrl.fromLocalFile(self.__save_dir))
        self.logger.debug("done")
Exemplo n.º 7
0
    def play_sound(self, sound: Sound) -> None:
        if sound.playback_threshold > self.threshold:
            logger.trace("Ignoring sound {!r} because of threshold", sound)
            return

        if sound.loop is Loop.Start:
            self._loop_sound = sound
            # New looping sound, rebuild playlist
            self._loop_playlist.clear()
            for file in sound.files:
                media = QUrl.fromLocalFile(file.file_name)
                self._loop_playlist.addMedia(media)

            # Select file based on weight and set the matching playlist index
            weights = [file.weight for file in sound.files]
            file = random.choices(sound.files, weights)[0]
            index = sound.files.index(file)
            self._loop_playlist.setCurrentIndex(index)

            logger.trace("Adjusting loop player volume by {}db",
                         file.volume_adjustment)
            self._loop_volume_adjustment = self.adjust_player_volume_by_decibel(
                self._loop_player, file.volume_adjustment)
            logger.trace("Adjusted One-shot player volume by {}db",
                         self._loop_volume_adjustment)
            self._loop_player.play()
            logger.trace(
                "Loop player playing file: {!r} at playlist index: {}",
                file,
                index,
            )
            return
        if sound.loop is Loop.Stop:
            logger.trace("Stopping loop player")
            self._loop_sound = None
            self._loop_playlist.clear()
            self._loop_player.stop()
        else:
            logger.trace("Pausing loop player for one-shot sound")
            self._loop_player.pause()

        file = random.choices(sound.files,
                              [file.weight for file in sound.files])[0]
        media = QUrl.fromLocalFile(file.file_name)
        self._one_shot_player.setMedia(media)
        self._one_shot_volume_adjustment = self.adjust_player_volume_by_decibel(
            self._one_shot_player, file.volume_adjustment)
        logger.trace("Adjusted one-shot player volume by {}db",
                     self._one_shot_volume_adjustment)
        self._one_shot_player.play()
        logger.trace("One-shot player playing file: {!r}", file)
Exemplo n.º 8
0
    def setName(self, alist):
        pfrom = PurePath(alist[1]).parent
        pto = PurePath(alist[2]).parent
        namefrom = PurePath(pfrom).parts[-1]
        nameto = PurePath(pto).parts[-1]

        path1 = QUrl.fromLocalFile(f'{pfrom}').toString()
        path1 = f'''<a href='{path1}'>{namefrom}</a>'''

        path2 = QUrl.fromLocalFile(f'{pto}').toString()
        path2 = f'''<a href='{path2}'>{nameto}</a>'''

        self.ui.label_5.setText(f'Из {path1} в {path2}')
        self.ui.label.setText(f'Имя: {alist[0]}')
Exemplo n.º 9
0
    def __init__(
        self,
        parent: QObject,
        manager: Manager,
        artists_model,
        tasks_model,
        artist_selection_model,
        tasks_selection_model,
    ):
        super().__init__(parent)

        self.setWindowTitle("Assignments")

        self._manager = manager

        # Build widgets
        self.widget_gantt = QQuickWidget(self)
        self.widget_gantt.setResizeMode(QQuickWidget.SizeRootObjectToView)
        root_context = self.widget_gantt.rootContext()
        root_context.setContextProperty("manager", self._manager)
        root_context.setContextProperty("artists", artists_model)
        root_context.setContextProperty("tasks", tasks_model)
        root_context.setContextProperty("artistsSelectionModel",
                                        artist_selection_model)
        root_context.setContextProperty("tasksSelectionModel",
                                        tasks_selection_model)
        self.widget_gantt.setSource(QUrl.fromLocalFile(_QML))

        # Build layout
        self.setWidget(self.widget_gantt)
Exemplo n.º 10
0
    def __init__(self, parent=None):
        QtWidgets.QGroupBox.__init__(self, "Details", parent=parent)

        view = QtQuickWidgets.QQuickWidget()
        rc = view.rootContext()

        self.manager = Manager()
        rc.setContextProperty('manager', self.manager)

        self.markersModel = MarkersModel()
        rc.setContextProperty('markersModel', self.markersModel)

        self.linesModel = LinesModel()
        rc.setContextProperty('linesModel', self.linesModel)

        self.polygonsModel = PolygonsModel()
        rc.setContextProperty('polygonsModel', self.polygonsModel)

        url = QUrl.fromLocalFile(
            os.path.join(os.path.abspath(os.path.dirname(__file__)),
                         "summary_details.qml"))
        view.setSource(url)
        view.setResizeMode(QtQuickWidgets.QQuickWidget.SizeRootObjectToView)
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)
        vbox.addWidget(view)
Exemplo n.º 11
0
 def open_action_triggered(self):
     files = QFileDialog.getOpenFileNames(self.window,
                                          "Add songs to playlist")
     for i in range(len(files[0])):
         self.music_playlist.addMedia(QUrl.fromLocalFile(str(files[0][i])))
     self.music_playlist.setCurrentIndex(0)
     self.music_player.setPlaylist(self.music_playlist)
Exemplo n.º 12
0
    def threadWorker(self):
        self.app = QGuiApplication()
        self.view = QQuickView()
        self.view.setResizeMode(QQuickView.SizeRootObjectToView)

        #Load the QML file
        qml_file = os.path.join(os.path.dirname(__file__), "view.qml")
        self.view.setSource(QUrl.fromLocalFile(os.path.abspath(qml_file)))

        root = self.view.rootObject()

        ioHandler = Handler(self.moveQueue)
        context = self.view.rootContext()
        context.setContextProperty("handler", ioHandler)

        #Show the window
        if self.view.status() == QQuickView.Error:
            sys.exit(-1)

        ioSignaler = ioObject(root)

        input_thread = threading.Thread(target=self.ioThread,
                                        args=(self.inputQueue, ioSignaler))
        input_thread.start()

        self.view.show()
        self.app.exec_()

        self.inputQueue.put({"type": UIMessageType.QUIT})
        input_thread.join()
        self.outputQueue.put({"type": UICommandType.QUIT})
        self.moveQueue.put({"x": -1, "y": -1})
Exemplo n.º 13
0
    def init_video(self):
        self.old_bpm = 1.0

        self.video_widget = VideoWidget(self,
                                        self.show_video_preview,
                                        self.screen)
        self.media_player = QMediaPlayer(self.central)
        self.media_player.setVideoOutput(self.video_widget)

        self.playlist = QMediaPlaylist(self.media_player)
        dir_path = os.path.dirname(os.path.realpath(__file__))
        file_location = dir_path + "/resources/video_long.mp4"
        self.video_file = QUrl.fromLocalFile(file_location)
        self.playlist.addMedia(self.video_file)
        self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        self.playlist.setCurrentIndex(0)
        self.media_player.setPlaylist(self.playlist)
        self.media_player.mediaStatusChanged.connect(self.handle_media_state_changed)

        self.media_player.play()

        self.change_playback_rate(self.video_loop_bpm)

        if not self.show_video_preview:
            self.video_widget.hide()
Exemplo n.º 14
0
    def removeRecentProjectFile(self, projectFile):
        if not isinstance(projectFile, (QUrl, pyCompatibility.basestring)):
            raise TypeError("Unexpected data type: {}".format(
                projectFile.__class__))
        if isinstance(projectFile, QUrl):
            projectFileNorm = projectFile.toLocalFile()
            if not projectFileNorm:
                projectFileNorm = projectFile.toString()
        else:
            projectFileNorm = QUrl(projectFile).toLocalFile()
            if not projectFileNorm:
                projectFileNorm = QUrl.fromLocalFile(projectFile).toLocalFile()

        projects = self._recentProjectFiles()

        # remove duplicates while preserving order
        from collections import OrderedDict
        uniqueProjects = OrderedDict.fromkeys(projects)
        projects = list(uniqueProjects)
        # remove previous usage of the value
        if projectFileNorm not in uniqueProjects:
            return

        projects.remove(projectFileNorm)

        settings = QSettings()
        settings.beginGroup("RecentFiles")
        size = settings.beginWriteArray("Projects")
        for i, p in enumerate(projects):
            settings.setArrayIndex(i)
            settings.setValue("filepath", p)
        settings.endArray()
        settings.sync()

        self.recentProjectFilesChanged.emit()
Exemplo n.º 15
0
    def openLink(self, key, arg="", fileArg=None):
        """Use `QDesktopServices` to open an url using
        the system default applications

        Parameters:
            key: the entry key or the link (if `arg` == "link")
            arg:
                if `arg` == "file", `fileArg` must be the file name
                if `arg` == "link", `key` must be the link to be opened
                for any other values, the link will be generated using
                    the `physbiblio.view.viewWntry.getLink` method
            fileArg: the file name if `arg` == "file", or
                the argument passed to `physbiblio.view.viewWntry.getLink`
                if needed
        """
        if isinstance(key, list):
            for k in key:
                self.openLink(k, arg, fileArg)
        else:
            if arg == "file":
                url = QUrl.fromLocalFile(fileArg)
            elif arg == "link":
                url = QUrl(key)
            else:
                link = self.getLink(key, arg=arg, fileArg=fileArg)
                url = QUrl(link)
            if QDesktopServices.openUrl(url):
                pBLogger.debug(ccstr.openSuccess % (url.toString(), key))
            else:
                pBLogger.warning(ccstr.openFailed % key)
Exemplo n.º 16
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.decoder = QAudioDecoder()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.decoded_audio = {}
        self.only_samples = []
        self.decoding_is_finished = False
        self.max_bits = 32768
        self.signed = False
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        self.decode_audio()
        self.np_data = np.array(self.only_samples)
        if not self.signed:  # don't ask me why this fixes 8 bit samples...
            self.np_data = self.np_data - self.max_bits / 2
        print(len(self.only_samples))
        print(self.max_bits)
        self.isvalid = True
Exemplo n.º 17
0
def main():
    from misc.ui_generator import UiGenerator
    import example.constants as const
    ui_generator = UiGenerator(ui_dir=const.UI_FILE_DIR,
                               rc_dir=const.RC_FILE_DIR,
                               out_dir=const.GUI_COMPILE_OUTPUT)
    ui_generator.compile_all()

    import example.gui.rc_qml as rc_qml
    rc_qml.qInitResources()

    from misc.debug import qt_message_handler
    QtCore.qInstallMessageHandler(qt_message_handler)
    app = ExampleApp(sys.argv)

    engine = QQmlApplicationEngine()
    qmlRegisterType(QmlOpenGLWindowInteractor, "QmlVTK", 1, 0, "Interactor")

    context = engine.rootContext()
    main_window = MainWindow()
    engine.setContextForObject(main_window, context)
    context.setContextProperty("mainWindow", main_window)

    engine.load(QUrl.fromLocalFile(":/qml/app.qml"))

    if len(engine.rootObjects()) == 0:
        logging.error("No QML file is loaded. Application Exit!")
        return

    sys.exit(app.exec_())
Exemplo n.º 18
0
def main():
    global dbus
    parser = ArgumentParser()
    parser.add_argument("-v",
                        "--verbose",
                        help="increase output verbosity",
                        action="store_true")
    args = parser.parse_args()
    QtQml.qmlRegisterType(QmlPage, "djpdf", 1, 0, "DjpdfPage")
    app = QApplication([])
    app.setWindowIcon(QIcon.fromTheme("com.github.unrud.djpdf"))
    engine = QQmlApplicationEngine()
    thumbnail_image_provider = ThumbnailImageProvider()
    engine.addImageProvider("thumbnails", thumbnail_image_provider)
    ctx = engine.rootContext()
    pages_model = QmlPagesModel(verbose=args.verbose)
    if os.environ.get("DJPDF_PLATFORM") == "flatpak":
        import dbus
        import dbus.mainloop.glib
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SessionBus()
        platform_integration = QmlFlatpakPlatformIntegration(bus)
    else:
        platform_integration = QmlPlatformIntegration()
    ctx.setContextProperty("pagesModel", pages_model)
    ctx.setContextProperty("platformIntegration", platform_integration)
    engine.load(QUrl.fromLocalFile(os.path.join(QML_DIR, "main.qml")))
    platform_integration.window = engine.rootObjects()[0]
    exit(app.exec_())
Exemplo n.º 19
0
 def testMetaData(self):
     self.view = QWebView()
     QObject.connect(self.view, SIGNAL('loadFinished(bool)'),
                     self.load_finished)
     url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__))
     self.view.setUrl(url)
     self.app.exec_()
Exemplo n.º 20
0
    def __init__(self):

        super().__init__()

        self.width = 75
        self.height = self.width
        self.x = 0
        self.y = 0

        self.board_tile_width = 0
        self.board_tile_height = self.board_tile_width

        self.sides = 6

        self.dice_initialized = False
        self.draw_dice = False

        self.dice_amount = 0
        self.audio_player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.audio_player.setMedia(
            QUrl.fromLocalFile(
                definitions.ROOT_DIR +
                "/Trivial_Purfuit/resources/audio/dice_roll.mp3"))
        self.audio_player.setVolume(50)
        self.image_path = definitions.ROOT_DIR + "/Trivial_Purfuit/src/die/"
Exemplo n.º 21
0
def main():
    app = QGuiApplication(sys.argv)

    manager = Manager()

    for i in range(200):
        manager.model.append_item(
            Item(
                name=f"name{i}",
                checked=i % 2 == 0,
                x=random.randint(-100, 100),
                y=random.randint(0, 100),
            ))

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("manager", manager)

    filename = os.path.join(CURRENT_DIR, "main.qml")
    url = QUrl.fromLocalFile(filename)

    def handle_object_created(obj, objUrl):
        if not obj and url == objUrl:
            QCoreApplication.exit(-1)

    engine.objectCreated.connect(handle_object_created, Qt.QueuedConnection)
    engine.load(url)

    ret = app.exec_()
    sys.exit(ret)
Exemplo n.º 22
0
def main():
    global dbus
    parser = ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")
    args = parser.parse_args()
    QtQml.qmlRegisterType(QmlPage, "djpdf", 1, 0, "DjpdfPage")
    app = QApplication([])
    engine = QQmlApplicationEngine()
    thumbnail_image_provider = ThumbnailImageProvider()
    engine.addImageProvider("thumbnails", thumbnail_image_provider)
    ctx = engine.rootContext()
    pages_model = QmlPagesModel(verbose=args.verbose)
    if os.environ.get("DJPDF_PLATFORM_INTEGRATION", "") == "flatpak":
        import dbus
        import dbus.mainloop.glib
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SessionBus()
        platform_integration = QmlFlatpakPlatformIntegration(bus)
    else:
        platform_integration = QmlPlatformIntegration()
    ctx.setContextProperty("pagesModel", pages_model)
    ctx.setContextProperty("platformIntegration", platform_integration)
    engine.load(QUrl.fromLocalFile(
        os.path.join(QML_DIR, "main.qml")))
    if os.environ.get("DJPDF_PLATFORM_INTEGRATION", "") == "flatpak":
        platform_integration.win_id = engine.rootObjects()[0].winId()
    exit(app.exec_())
Exemplo n.º 23
0
 def testMetaData(self):
     self.view = QWebView()
     QObject.connect(self.view, SIGNAL('loadFinished(bool)'),
                     self.load_finished)
     url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__))
     self.view.setUrl(url)
     self.app.exec_()
Exemplo n.º 24
0
 def hCopy(self):
     """
     # slot for action copy_to_clipboard
     """
     sel = self.listWdg.selectedItems()
     ####################
     # test code
     l = []
     for item in sel:
         # get url from path
         l.append(QUrl.fromLocalFile(item.data(Qt.UserRole)[0]))
     # init clipboard data
     q = QMimeData()
     # set some Windows magic values for copying files from system clipboard : Don't modify
     # 1 : copy; 2 : move
     q.setData("Preferred DropEffect", QByteArray(1, "2"))
     q.setUrls(l)
     # end of test code
     #####################
     # copy image to clipboard
     item = sel[0]
     filename = item.data(Qt.UserRole)[0]
     if filename.endswith(IMAGE_FILE_EXTENSIONS):
         q.setImageData(QImage(sel[0].data(Qt.UserRole)[0]))
     QApplication.clipboard().clear()
     QApplication.clipboard().setMimeData(q)
    def testIncubateWhileCall(self):
        app = QGuiApplication(sys.argv)
        view = QQuickView()
        controller = CustomIncubationController(self)
        view.engine().setIncubationController(controller)
        view.setResizeMode(QQuickView.SizeRootObjectToView)
        view.setSource(
            QUrl.fromLocalFile(
                adjust_filename('qqmlincubator_incubateWhile.qml', __file__)))
        view.show()

        root = view.rootObject()
        # The QML code will issue an interrupt signal after half of its items are loaded.
        root.shouldInterrupt.connect(controller.interrupter)
        res = app.exec_()

        itemsToCreate = root.property("itemsToCreate")
        loadedItems = root.property("loadedItems")
        self.assertEqual(loadedItems, itemsToCreate / 2)

        # Finish incubating the remaining items.
        controller.incubateFor(1000)
        loadedItems = root.property("loadedItems")
        self.assertEqual(loadedItems, itemsToCreate)

        # Deleting the view before it goes out of scope is required to make sure all child QML
        # instances are destroyed in the correct order.
        del view
        del app
Exemplo n.º 26
0
def test():
    url = QUrl.fromLocalFile("D:/test/1.mov")
    content = QMediaContent(url)
    player = QMediaPlayer()
    player.setMedia(content)
    # player.setVolume(Sound_level)
    player.play()
Exemplo n.º 27
0
 def __init__(self):
     QMainWindow.__init__(self)
     Ui_MainWindow.__init__(self)
     self.setupUi(self)
     self.videoWidget = QVideoWidget()
     self.mediaPlayer = QMediaPlayer()
     self.mediaPlaylist = QMediaPlaylist()
     # Add the video file path
     self.mediaPlaylist.addMedia(QUrl.fromLocalFile(os.path.abspath("./sample_data/sampleVideo.mp4")))
     # Set the video to played in a loop once it ends.
     self.mediaPlaylist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
     # Set the QMediaPlaylist for the QMediaPlayer.
     self.mediaPlayer.setPlaylist(self.mediaPlaylist)
     # Add the QVideoWidget in the GridLayout.
     self.playerLayout.addWidget(self.videoWidget)
     # Set the video output from the QMediaPlayer to the QVideoWidget.
     self.mediaPlayer.setVideoOutput(self.videoWidget)
     # Set the QPushButtons to play, pause and stop the video in the QVideoWidget.
     self.playButton.clicked.connect(self.play_video)
     self.pauseButton.clicked.connect(self.pause_video)
     self.stopButton.clicked.connect(self.stop_video)
     # Set the total range for the QSlider.
     self.mediaPlayer.durationChanged.connect(self.change_duration)
     # Set the current value for the QSlider.
     self.mediaPlayer.positionChanged.connect(self.change_position)
     # Set the video position in QMediaPlayer based on the QSlider position.
     self.horizontalSlider.sliderMoved.connect(self.video_position)
Exemplo n.º 28
0
 def mouseMoveEvent(self, event):
     """Start dragging action if needed."""
     if not event.buttons() & Qt.LeftButton:
         return
     if not self.drag_start_pos:
         return
     if not self.drag_indexes:
         return
     if (event.pos() - self.drag_start_pos
         ).manhattanLength() < QApplication.startDragDistance():
         return
     drag = QDrag(self)
     mimeData = QMimeData()
     urls = list()
     for index in self.drag_indexes:
         file_path = index.data(Qt.UserRole)
         urls.append(QUrl.fromLocalFile(file_path))
     mimeData.setUrls(urls)
     drag.setMimeData(mimeData)
     icon = self.drag_indexes[0].data(Qt.DecorationRole)
     if icon:
         pixmap = icon.pixmap(32, 32)
         drag.setPixmap(pixmap)
         drag.setHotSpot(pixmap.rect().center())
     drag.exec_()
Exemplo n.º 29
0
 def rechKeyWord(self):
     self.ui.tWResults.setRowCount(0)
     kWToTest = self.listKeyWord()
     klen = len(kWToTest)
     n = self.ui.tableWidget.rowCount()
     for cv in range(0, n):
         nomCV = self.ui.tableWidget.item(cv, 0).text()
         currentTable = self.ui.tableWidget.item(cv, 0).toolTip()
         cvATester = QUrl.fromLocalFile(currentTable)
         cvATestPath = QUrl.toLocalFile(cvATester)
         text = parser.from_file(cvATestPath)
         cvTransfText = text['content']
         cvAcompare = cvTransfText.lower()
         cptKw = 0
         for k in range(0, klen):
             kWSearch = kWToTest[k]
             # (r'{}\[^a-z]'.format(kWSearch))
             if re.search(r'\W{}\W'.format(kWSearch), cvAcompare) != None:
                 # if kWSearch in cvAcompare:
                 cptKw += 1
         if cptKw != 0:
             if self.ui.tWResults.rowCount() == 0:
                 self.ui.tWResults.insertRow(0)
                 self.ui.tWResults.setItem(0, 0, QTableWidgetItem(nomCV))
                 self.ui.tWResults.setItem(0, 1,
                                           QTableWidgetItem(str(cptKw)))
             else:
                 lgTable = self.ui.tWResults.rowCount()
                 self.ui.tWResults.insertRow(lgTable)
                 self.ui.tWResults.setItem(lgTable, 0,
                                           QTableWidgetItem(nomCV))
                 self.ui.tWResults.setItem(lgTable, 1,
                                           QTableWidgetItem(str(cptKw)))
     self.ui.tWResults.sortItems(1, order=Qt.DescendingOrder)
Exemplo n.º 30
0
    def __init__(self, sys_argv):
        super().__init__(sys_argv)

        # Show main window
        self.view = QMainWindow()

        self.centralWidget = QWidget(self.view)

        self.gridLayout = QGridLayout(self.centralWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(0)

        self.video_item = QVideoWidget()

        self.gridLayout.addWidget(self.video_item)

        self.view.setCentralWidget(self.centralWidget)

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        self.grabber = VideoFrameGrabber(self.video_item, self)
        self.mediaPlayer.setVideoOutput(self.grabber)

        self.grabber.frameAvailable.connect(self.process_frame)

        self.mediaPlayer.durationChanged.connect(self.update_duration)
        self.mediaPlayer.positionChanged.connect(self.update_slider_position)

        local = QUrl.fromLocalFile('D:\\SampleData\\albamonSample.mp4')
        media = QMediaContent(local)
        self.mediaPlayer.setMedia(media)
        self.mediaPlayer.play()

        self.view.show()
Exemplo n.º 31
0
 def testAbstractItemModelTransferToQML(self):
     view = QQuickView()
     model = ListModel()
     view.rootContext().setContextProperty("pythonModel", model)
     view.setSource(QUrl.fromLocalFile(adjust_filename('bug_814.qml', __file__)))
     root = view.rootObject()
     view.show()
Exemplo n.º 32
0
 def rechKeyWord(self):
     kWToTest = self.listKeyWord()
     klen = len(kWToTest)
     print("liste à tester", kWToTest)
     n = self.ui.tableWidget.rowCount()
     for cv in range(0, n):
         nomCV = self.ui.tableWidget.item(cv, 0).text()
         currentTable = self.ui.tableWidget.item(cv, 0).toolTip()
         cvATester = QUrl.fromLocalFile(currentTable)
         cvATestPath = QUrl.toLocalFile(cvATester)
         text = parser.from_file(cvATestPath)
         cvTransfText = text['content']
         cvAcompare = cvTransfText.lower()
         cptKw = 0
         # listCV = {"nom", }
         for k in range(0, klen):
             if kWToTest[k] in cvAcompare:
                 cptKw += 1
                 # listCV.append(currentTable)
                 print("Trouvé")
             else:
                 print("pas trouvé")
         if self.ui.tWResults.rowCount() == 0:
             self.ui.tWResults.insertRow(0)
             self.ui.tWResults.setItem(0, 0, QTableWidgetItem(nomCV))
             self.ui.tWResults.setItem(0, 1, QTableWidgetItem(str(cptKw)))
         else:
             lgTable = self.ui.tWResults.rowCount()
             print(lgTable)
             self.ui.tWResults.insertRow(lgTable)
             self.ui.tWResults.setItem(lgTable, 0, QTableWidgetItem(nomCV))
             self.ui.tWResults.setItem(lgTable, 1,
                                       QTableWidgetItem(str(cptKw)))
Exemplo n.º 33
0
    def open_project(self, project_folder_path):
        """Opens a project.

        Args:
          project_folder_path: folder of the project which should be opened.

        """
        self.project_folder_path = project_folder_path
        self.media_file = file_util.get_file(self.project_folder_path,
                                             c.CON_COPY_POSTFIX)
        if self.media_file is None:
            self.hide()
            return
        self.media_player.setMedia(
            QMediaContent(QUrl.fromLocalFile(self.media_file)))

        self.transcription_path = file_util.get_file(self.project_folder_path,
                                                     c.TRANSCRIPTION)
        if self.transcription_path is None:
            self.hide()
            return
        with open(self.transcription_path, 'r') as f:
            text = f.read()
        self.text.setPlainText(text)
        self.transcription_meta_data = file_util.get_value_from_shelve(
            self.project_folder_path, c.TRANSCRIPTION_META_DATA)
        print(self.transcription_meta_data)
Exemplo n.º 34
0
 def testAbstractItemModelTransferToQML(self):
     view = QQuickView()
     view.setSource(QUrl.fromLocalFile(adjust_filename('bug_814.qml', __file__)))
     root = view.rootObject()
     model = ListModel()
     root.setProperty('model', model)
     view.show()
Exemplo n.º 35
0
    def testSignalEmission(self):
        qmlRegisterType(MyItem, "my.item", 1, 0, "MyItem")

        view = QQuickView()
        view.setSource(QUrl.fromLocalFile(adjust_filename('bug_951.qml', __file__)))

        self.app.exec_()
        self.assertTrue(MyItem.COMPONENT_COMPLETE_CALLED)
Exemplo n.º 36
0
def main():
    app = QApplication([])
    QtWebEngine.initialize()
    engine = QQmlApplicationEngine()
    qml_file_path = os.path.join(os.path.dirname(__file__), 'browser.qml')
    qml_url = QUrl.fromLocalFile(os.path.abspath(qml_file_path))
    engine.load(qml_url)
    app.exec_()
Exemplo n.º 37
0
 def testIt(self):
     app = QGuiApplication([])
     qmlRegisterType(MyClass,'Example',1,0,'MyClass')
     view = QQuickView()
     view.setSource(QUrl.fromLocalFile(adjust_filename('bug_926.qml', __file__)))
     self.assertEqual(len(view.errors()), 0)
     view.show()
     QTimer.singleShot(0, app.quit)
     app.exec_()
Exemplo n.º 38
0
    def test_qml_type(self):
        qmlRegisterType(TestClass, "JavaScriptExceptions", 1, 0, "JavaScriptExceptions")

        view = QQuickView()
        qml_url = QUrl.fromLocalFile(adjust_filename("javascript_exceptions.qml", __file__))

        view.setSource(qml_url)

        self.assertTrue(test_1)
        self.assertTrue(test_2)
Exemplo n.º 39
0
    def testQDeclarativeNetworkFactory(self):
        view = QDeclarativeView()

        url = QUrl.fromLocalFile(adjust_filename('hw.qml', __file__))

        view.setSource(url)
        view.show()

        self.assertEqual(view.status(), QDeclarativeView.Ready)

        self.app.exec_()
Exemplo n.º 40
0
    def testModelExport(self):
        view = QDeclarativeView()
        dataList = [MyObject("Item 1"), MyObject("Item 2"), MyObject("Item 3"), MyObject("Item 4")]

        ctxt = view.rootContext()
        ctxt.setContextProperty("myModel", dataList)

        url = QUrl.fromLocalFile(adjust_filename('viewmodel.qml', __file__))
        view.setSource(url)
        view.show()

        self.assertEqual(view.status(), QDeclarativeView.Ready)
Exemplo n.º 41
0
    def testIt(self):
        app = QGuiApplication([])

        qmlRegisterType(PieChart, 'Charts', 1, 0, 'PieChart');
        qmlRegisterType(PieSlice, "Charts", 1, 0, "PieSlice");

        view = QQuickView()
        view.setSource(QUrl.fromLocalFile(helper.adjust_filename('registertype.qml', __file__)))
        view.show()
        QTimer.singleShot(250, view.close)
        app.exec_()
        self.assertTrue(appendCalled)
        self.assertTrue(paintCalled)
Exemplo n.º 42
0
    def testLoadFinishedFromFile(self):
        url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__))
        self.view.setUrl(url)
        self.app.exec_()

        self.assert_(self.called)
Exemplo n.º 43
0
 def __init__(self):
     QQuickView.__init__(self)
     self.setSource(QUrl.fromLocalFile(adjust_filename('bug_847.qml', __file__)))
     self.rootObject().setProperty('pythonObject', self)
Exemplo n.º 44
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.decoder = QAudioDecoder()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.decoded_audio = {}
        self.only_samples = []
        self.decoding_is_finished = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        #self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        #self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        #self.decode_audio()
        #self.np_data = np.array(self.only_samples)
        #self.np_data = np.abs(self.np_data / self.max_bits)
        # A simple normalisation, with this the samples should all be between 0 and 1
        # for i in self.decoded_audio.items():
        #     self.only_samples.extend(i[1][0])
        # t = []
        # for i in self.only_samples:
        #     if i != []:
        #         t.append(i + -(min(self.only_samples)))
        #
        # t2 = []
        # for i in t:
        #     t2.append(i / max(t))
        # self.only_samples = t2
        #print(len(self.only_samples))
        #print(self.max_bits)


        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(get_main_dir(), "ffmpeg.exe")
                    #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(self.soundfile, format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
Exemplo n.º 45
0
 def url(self):
     return QUrl.fromLocalFile(self._data["filename"])
Exemplo n.º 46
0
 def launch(self):
     QDesktopServices.openUrl(QUrl.fromLocalFile(self.fileName))
Exemplo n.º 47
0
 def open_file(file):
     QDesktopServices.openUrl(QUrl.fromLocalFile(file))
Exemplo n.º 48
0
        self._name = value

    colorChanged = Signal()
    color = Property(QColor, getColor, setColor, notify=colorChanged)
    name = Property(text_type, getName, setName)
    chartCleared = Signal()

    @Slot() # This should be something like @Invokable
    def clearChart(self):
        self.setColor(Qt.transparent)
        self.update()
        self.chartCleared.emit()

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

    qmlRegisterType(PieChart, 'Charts', 1, 0, 'PieChart');

    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    qmlFile = os.path.join(os.path.dirname(__file__), 'app.qml')
    view.setSource(QUrl.fromLocalFile(os.path.abspath(qmlFile)))
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.show()
    res = app.exec_()
    # Deleting the view before it goes out of scope is required to make sure all child QML instances
    # are destroyed in the correct order.
    del view
    sys.exit(res)
Exemplo n.º 49
0
import sys

from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlEngine, QQmlComponent

app = QGuiApplication(sys.argv)

engine = QQmlEngine()
component = QQmlComponent(engine)

# This should segfault if the QDeclarativeComponent has not QQmlEngine
component.loadUrl(QUrl.fromLocalFile('foo.qml'))

Exemplo n.º 50
0
 def testFindSelectText(self):
     url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__))
     self.page.mainFrame().load(url)
     self.app.exec_()
     self.assert_(self.called)