class View(object): def __init__(self, iface, chart): dir_path = os.path.dirname(os.path.realpath(__file__)) qml = os.path.join(dir_path, "qml", "scatterplot.qml") self.view = QQuickView() self.view.setResizeMode(QQuickView.SizeRootObjectToView) self.view.rootContext().setContextProperty("pychart", chart) self.view.setColor(QColor("#000000")) self.view.setSource(QUrl.fromLocalFile(qml)) self.container = QWidget.createWindowContainer(self.view) self.widget = QDockWidget() self.widget.setWidget(self.container) iface.addDockWidget(Qt.BottomDockWidgetArea, self.widget) self.read_settings() def read_settings(self, settings=None): if not settings: settings = Settings.Snapshot() self.view.setColor(QColor(settings.background_color)) def show(self): self.widget.show() def hide(self): self.widget.hide()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle('Read OpenVSLAM map') self.mapInfo = MapInfo() qml_view = QQuickView() qml_view.rootContext().setContextProperty('mapInfo', self.mapInfo) qml_view.setSource( QUrl( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'read_map.qml'))) qml_view.setResizeMode(QQuickView.SizeRootObjectToView) self.qml_gui = qml_view.rootObject() qml_view_container = QWidget.createWindowContainer(qml_view, self) qml_view_container.setMinimumSize(800, 200) self.setCentralWidget(qml_view_container) self.mapInfo.filenameChanged.connect(self.read_data) self.mapInfo.visualiseCloud.connect(self.pptk) self.mapInfo.visualiseTrajectory.connect(self.pyplot) self.mapInfo.exportCloud.connect(self.export_cloud) self.data = None self.cloud = None self.trajectory = None
def main(): argv = sys.argv app = QGuiApplication(argv) qmlRegisterType(FigureCanvasQTAggToolbar, "Backend", 1, 0, "FigureToolbar") imgProvider = MatplotlibIconProvider() view = QQuickView() view.engine().addImageProvider("mplIcons", imgProvider) view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource( QUrl( os.path.join(os.path.dirname(__file__), 'backend_qtquick5', 'FigureToolbar.qml'))) win = view.rootObject() fig = win.findChild(QObject, "figure").getFigure() ax = fig.add_subplot(111) x = np.linspace(-5, 5) ax.plot(x, np.sin(x)) view.show() rc = app.exec_() # There is some trouble arising when deleting all the objects here # but I have not figure out how to solve the error message. # It looks like 'app' is destroyed before some QObject sys.exit(rc)
def create_main_app(): # create the application main_app = QApplication(sys.argv) # internationalisation # see http://doc.qt.io/qt-5/internationalization.html # see http://pyqt.sourceforge.net/Docs/PyQt5/i18n.html translator = QTranslator() translator.load("arpi/res/i18n/arpi_" + QLocale.system().name()) main_app.installTranslator(translator) # create config global_config = GlobalConfig() # create speech output class global_config.say = Say(global_config) # create quick view view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) # start program AppOverview(view, loaded_apps, global_config).activate() view.show() # clean up main_app.exec_() sys.exit()
def create_qquick_view(script_root, qml_dirs=[], img_providers=[]): view = QQuickView() add_import_paths(view.engine(), qml_dirs) add_image_providers(view.engine(), img_providers) view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(QUrl.fromLocalFile(script_root)) return view
def main(): global app # sys.argv.extend(['-platform', 'eglfs']) # Qt Charts uses Qt Graphics View Framework for drawing, therefore QApplication must be used. app = QApplication(sys.argv) viewer = QQuickView() # The following are needed to make examples run without having to install the module # in desktop environments. extraImportPath = QGuiApplication.applicationDirPath() if sys.platform == 'win32': extraImportPath += "/../../../../qml" else: extraImportPath += "/../../../qml" viewer.engine().addImportPath(extraImportPath) viewer.engine().quit.connect(app.quit) viewer.setTitle("QML Oscilloscope") dataSource = datasource.DataSource(viewer) viewer.rootContext().setContextProperty("dataSource", dataSource) main_qml = path.dirname(__file__) + "/qml/qmloscilloscope/main.qml" viewer.setSource(QUrl(main_qml)) viewer.setResizeMode(QQuickView.SizeRootObjectToView) viewer.setColor(QColor("#404040")) viewer.show() return app.exec_()
def main(): argv = sys.argv # Trick to set the style / not found how to do it in pythonic way argv.extend(["-style", "universal"]) app = QGuiApplication(argv) qmlRegisterType(FigureCanvasQTAgg, "Backend", 1, 0, "FigureCanvas") view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource( QUrl( os.path.join(os.path.dirname(__file__), 'backend_qtquick5', 'Figure.qml'))) view.show() win = view.rootObject() fig = win.findChild(QObject, "figure").getFigure() print(fig) ax = fig.add_subplot(111) x = np.linspace(-5, 5) ax.plot(x, np.sin(x)) rc = app.exec_() # There is some trouble arising when deleting all the objects here # but I have not figure out how to solve the error message. # It looks like 'app' is destroyed before some QObject sys.exit(rc)
def quickView(url: str, parent=None): view = QQuickView(parent) view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(QUrl(url)) view.show() return view
def main(): app = QGuiApplication(sys.argv) view = QQuickView() view.setSource(QUrl.fromLocalFile('scene3d.qml')) view.setResizeMode(QQuickView.SizeRootObjectToView) view.show() sys.exit(app.exec_())
def run_qml(qmlpath): app = QGuiApplication(sys.argv) qmlRegisterType(QQuickGLItem, 'GLItem', 1, 0, 'GLItem') view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(QUrl(qmlpath)) view.show() sys.exit(app.exec_())
def run_qml(qmlpath): app = QGuiApplication(sys.argv) register_qml() view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(QUrl(qmlpath)) view.show() sys.exit(app.exec_())
def run_qml(qmlpath): app = QGuiApplication(sys.argv) qmlRegisterType(VideoView, 'PyQt5GLfwTest', 1, 0, 'VideoView') view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(QUrl(qmlpath)) view.show() sys.exit(app.exec_())
class LoginWin(QtCore.QObject): def __init__(self, state, app): QtCore.QObject.__init__(self) self.state = state self.app = app # Create the QML user interface. self.login_win = QQuickView() self.login_win.setTitle(self.tr("Xiami Login")) self.login_win.setSource(QUrl('login.qml')) self.login_win.setResizeMode(QQuickView.SizeRootObjectToView) self.login_win.show() # Connect signals self.root_obj = self.login_win.rootObject() self.root_obj.loginClicked.connect(self.login_clicked) self.root_obj.exitClicked.connect(self.exit_clicked) def set_state(self, msg): self.root_obj.setStatus(msg) def exit_clicked(self): sys.exit(0) def login_clicked(self, username, password): code = self.root_obj.getVerificationCode() if code != "": try: login.login_with_code(self.state, self.key, code) except Exception as e: self.set_state(e.message) self.root_obj.hideCode() return self.ok() else: try: ret = login.login(self.state, username, password) except Exception as e: self.set_state(e.message) return if not ret[0]: with open(login.img_path, 'wb') as imgf: imgf.write(ret[2]) self.set_state(self.tr("Please enter verification code")) self.root_obj.setVerificationImage("file://%s" % login.img_path) self.key = ret[1] else: self.ok() def ok(self): self.login_win.close() self.app.auth_ok()
def __init__(self): super(QmlStartPage, self).__init__() box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) # View view = QQuickView() view.setSource(QUrl.fromLocalFile(PATH_QML)) view.setResizeMode(QQuickView.SizeRootObjectToView) # Root object self._root = view.rootObject() widget_container = QWidget.createWindowContainer(view) box.addWidget(widget_container) self._root.animationFinished.connect(self._on_animation_finished)
def main(): app = QGuiApplication(sys.argv) view = QQuickView() schema = [ "pyLabel", "pyColor", ] model = Model(schema) items = [{ "pyLabel": "First Item", "pyColor": "white", }, { "pyLabel": "Second Item", "pyColor": "white", }] for item in items: model.append(item) engine = view.engine() context = engine.rootContext() context.setContextProperty("pyModel", model) view.setSource(QUrl("app.qml")) view.setResizeMode(view.SizeRootObjectToView) view.show() # Appending to the model QTimer.singleShot( 2000, lambda: model.append({ "pyLabel": "Third Item", "pyColor": "steelblue" })) # Modifying an item in the model QTimer.singleShot( 3000, lambda: model.setData( model.createIndex(1, 0), # 1th item, 0th column "New pLabel!", schema.index("pyLabel"), )) app.exec_()
class TabletShortcuts(QGuiApplication): def __init__(self, argv): QGuiApplication.__init__(self, argv) self.view = QQuickView() self.bus = QDBusConnection.sessionBus() self.server = MyDBUSServer(self) self.bus.registerObject("/app", self.server) self.bus.registerService("sevanteri.TabletShortcuts") self.view.setTitle("TabletShortcuts") self.view.setResizeMode(QQuickView.SizeRootObjectToView) self.view.setSource(QUrl('main.qml')) self.root = self.view.rootObject() self.showView() self.root.runCommand.connect(self.run) self.root.hideView.connect(self.view.hide) self.view.engine().quit.connect(self.quit) def run(self, cmd): return Popen(shlex.split(cmd)) def quit(self): self.exit() def showView(self): if self.view.isVisible(): self.view.hide() else: # width, height = TabletShortcuts.getScreenGeometry() # self.view.setGeometry(1, 1, width, height) self.view.show() def getScreenGeometry(): output = Popen("xrandr | grep 'current'", shell=True, stdout=PIPE)\ .communicate()[0].decode('UTF-8') m = re.search('current.([0-9]+).x.([0-9]+)', output) width = int(m.group(1)) height = int(m.group(2)) return (width, height)
def main(): import sys QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QCoreApplication.setOrganizationName("QtExamples") app = QGuiApplication(sys.argv) view = QQuickView() view.engine().quit.connect(app.quit) view.setSource(QUrl("qrc:/demos/clocks/clocks.qml")) if view.status() == QQuickView.Error: sys.exit(-1) view.setResizeMode(QQuickView.SizeRootObjectToView) view.show() sys.exit(app.exec_())
def __init__(self): super(StartPage, self).__init__() vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) view = QQuickView() qml = os.path.join(settings.QML_PATH, "StartPage.qml") view.setSource(QUrl.fromLocalFile(qml)) view.setResizeMode(QQuickView.SizeRootObjectToView) widget = QWidget.createWindowContainer(view) vbox.addWidget(widget) self.__root = view.rootObject() # Connections self.__root.openDatabase.connect(self.__open_database) self.__root.newDatabase.connect(self.__new_database) self.__root.removeCurrent.connect(self.__remove_current)
def __init__(self, parent=None): super(MessageError, self).__init__(parent, Qt.Dialog | Qt.FramelessWindowHint) self._parent = parent self.setModal(True) self.setFixedHeight(150) self.setFixedWidth(350) box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) view = QQuickView() qml = os.path.join(settings.QML_PATH, "MessageError.qml") view.setSource(QUrl.fromLocalFile(qml)) view.setResizeMode(QQuickView.SizeRootObjectToView) self.widget = QWidget.createWindowContainer(view) box.addWidget(self.widget) self._root = view.rootObject() self._root.close.connect(self.close)
def main(): mainView = "qrc:///main.qml" application = QGuiApplication(sys.argv) qmlRegisterType(ElHamalEncryptor, 'elhamal', 1, 0, 'Encryptor') qmlRegisterType(ElHamalDecryptor, 'elhamal', 1, 0, 'Decryptor') qmlRegisterType(ElHamalKeysGenerator, 'elhamal', 1, 0, 'KeysGenerator') qInstallMessageHandler(handleStatusChange) it = QDirIterator(":", QDirIterator.Subdirectories) while it.hasNext(): print(it.next()) view = QQuickView() view.setResizeMode(QQuickView.SizeViewToRootObject) view.setSource(QUrl(mainView)) sys.exit(application.exec_())
class CountdownApp(QObject): QMLFILE = 'main.qml' def __init__(self): super(QObject, self).__init__() self.app = QGuiApplication(sys.argv) self.view = QQuickView() self.view.setResizeMode(QQuickView.SizeRootObjectToView) #self.view.engine().quit.connect(self.app.quit) self.cds = CountdownList() self.cdt = [] for name, targetDatetime in { "silvester": datetime(2018, 1, 1, 0, 0, 0), "geburtstag": datetime(2018, 3, 12, 0, 0, 0) }.items(): cdobj = CountdownData() countdown = CountdownTimer(cdobj, targetDatetime, name) countdown.start() self.cds.append(cdobj) self.cdt.append(countdown) self.view.rootContext().setContextProperty('countdowns', self.cds) self.view.setSource(QUrl(self.QMLFILE)) self.t = QTimer() self.t.timeout.connect(self.addCountdown) self.t.start(10000) def run(self): self.view.show() sys.exit(self.app.exec_()) @pyqtSlot() def addCountdown(self): for name, targetDatetime in { "antrittsvorlesung": datetime(2018, 1, 19, 0, 0, 0) }.items(): cdobj = CountdownData() countdown = CountdownTimer(cdobj, targetDatetime, name) countdown.start() self.cds.append(cdobj) self.cdt.append(countdown)
def __init__(self): super(StartPage, self).__init__() vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) view = QQuickView() qml = os.path.join(settings.QML_PATH, "StartPage.qml") view.setSource(QUrl.fromLocalFile(qml)) view.setResizeMode(QQuickView.SizeRootObjectToView) widget = QWidget.createWindowContainer(view) vbox.addWidget(widget) self.__root = view.rootObject() # Connections self.__root.openRecentDatabase.connect(self.__open_database) self.__root.openPreferences.connect(self.__open_preferences) self.__root.openExample.connect(self.__open_example) self.__root.openDatabase.connect(self.__open_database) self.__root.newDatabase.connect(self.__new_database) self.__root.removeCurrent.connect(self.__remove_current)
def run_app(): app = QGuiApplication(sys.argv) app.setApplicationName("Worship Prototype") view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'main.qml'))) view.show() root = view.rootObject() preview = DefaultScreen() preview.wire_to_gui(root, 'previewScreen') preview.show_background(VideoBackground(os.path.join(os.path.dirname(__file__), '../echo.mp4'))) # preview_live = DefaultScreen() # live = DefaultScreen() modules = [ LyricsModule(SongsList(), root, preview), ] sys.exit(app.exec_())
def main(): # os.environ["QML_IMPORT_TRACE"] = "1" app = QGuiApplication(argv) qmlRegisterType(MainBusModel, 'Snowman', 1, 0, 'MainBusModel') qmlRegisterType(DsksModel, 'Snowman', 1, 0, 'DsksModel') view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) sourceFile = os.path.join(os.path.dirname(__file__), 'app.qml') view.setSource(QUrl.fromLocalFile(sourceFile)) mainBus = view.rootObject().findChild(QQuickItem, 'mainBusModel') mainBus.setProperty('manager', ManagerConnection(5555, 5556)) dsks = view.rootObject().findChild(QQuickItem, 'dsksModel') dsks.setProperty('manager', ManagerConnection(5555, 5556)) view.show() exit(app.exec_())
class VVSQMLApp(QObject): QMLFILE = 'gui.qml' def __init__(self, connections): super(QObject, self).__init__() self.app = QGuiApplication(sys.argv) self.view = QQuickView() self.view.setResizeMode(QQuickView.SizeRootObjectToView) if settings['alwaysOnTop']: self.view.setFlags(Qt.WindowStaysOnTopHint) self.con = [] for connection in connections: updaterThread = VVSConnectionUpdater( connection[0], connection[1], connection[2], updateDelay=settings['updateDelay']) updaterThread.start() self.con.append(updaterThread) #print(connection) #self.con = VVSConnectionUpdater('5006021', 'X60', 'Leonberg Bf') #self.con.start() #print(self.con) self.view.rootContext().setContextProperty('con', self.con) self.view.setSource(QUrl(self.QMLFILE)) #Setup notifications VVSNotifier.setup(self.con) def run(self): if settings['fullscreen']: self.view.showFullScreen() else: self.view.show() sys.exit(self.app.exec_())
class P2CQMLApplication(QGuiApplication): def __init__(self, list_of_str): super().__init__(list_of_str) self._current_category = None self._current_torrent = None self._current_torrent_info = None self._status_timer = QTimer(self) self._movies_thread = None self._search_thread = None def run_view(self): self._view = QQuickView() self._view.engine().addImportPath("qml") self._rctx = self._view.rootContext() self._view.setResizeMode(QQuickView.SizeRootObjectToView) # set context variables self.categories = [] self._rctx.setContextProperty("categoriesModel", self.categories) self.tiles = [] self.torrents = [] self._rctx.setContextProperty("moviesModel", self.tiles) self._set_loading(False) self._view.setSource(QUrl('qrc:/qml.qml')) self._view.showFullScreen() # self._view.show() def connect_daemon(self, daemon: P2CDaemon): self._daemon = daemon self._set_categories() self._connect_signals() def play(self, movie: Movie): self._set_movie_status("Ready to play!") self._set_media(movie) self._daemon.play(movie) self._set_additional_media_info() def buffer(self, movie: Movie): seconds = self._current_torrent.get_seconds_to_buffer() info = "just started" if seconds: if seconds < 15: info = "just a moment" else: # rount to minutes minutes = int(seconds / 60) + 1 if minutes == 1: info = "1 minute" else: info = "{} minutes".format(minutes) self._set_movie_status("Buffering... ({})".format(info)) self._daemon.buffer(movie) self._set_additional_media_info() def wait_for_metadata(self): self._set_movie_status("Getting metadata...") if self._current_torrent: self._set_additional_media_info(self._current_torrent.name) def select_movie(self, torrent: Torrent) -> Movie: movies = torrent.get_movies() if len(movies) == 0: return # TODO: show dialog with movie selecting instead of doing it automatically return max(movies, key=lambda x: x.size) def update_status(self): torrent = self._current_torrent if torrent: if(torrent.has_torrent_info()): movie = self.select_movie(torrent) if not movie: self._set_movie_status("No movie in this torrent. Please, select another.") return torrent.download_file(movie.path) self._set_duration(movie) if not self._daemon.is_playing(movie): if(movie.can_play()): # print(movie.get_subtitles()) self.play(movie) else: self.buffer(movie) ### DEBUG INFO text = "s: %s, num p: %s, rate: %s kbs, p_rate: %s kbs" % ( torrent.get_status()['state'], torrent.get_status()['num_peers'], int(torrent.get_status()['download_rate'] / 1024), int(torrent.get_status()['download_payload_rate'] / 1024), ) self._view.rootObject().setProperty("debugText", text) ### END DEBUG INFO else: self.wait_for_metadata() else: self.wait_for_metadata() def on_category_clicked(self, index): # clear list self._set_torrents([], loading=True) category = self._daemon.get_categories()[index] self._current_category = category if self._current_category: self._search_thread = None self._movies_thread = SetMoviesThread(self._current_category) self._movies_thread.start() self._movies_thread.got_movies.connect(self._threaded_set_torrents) def on_movie_clicked(self, index): self._view.rootObject().setProperty("isMovieScene", True) torrent_ui = self.torrents[index] self._current_torrent = self._daemon.get_torrent(torrent_ui) self._current_torrent_info = torrent_ui self.update_status() def on_search(self, query): if len(query) < 3: return # clear list self._set_torrents([], loading=True) self._movies_thread = None self._search_thread = SearchThread(query, self._daemon.search) self._search_thread.start() self._search_thread.got_movies.connect(self._threaded_set_torrents) def on_exit(self): self.quit() def _connect_signals(self): self._view.rootObject().categoryClicked.connect( self.on_category_clicked) self._view.rootObject().movieClicked.connect(self.on_movie_clicked) self._view.rootObject().movieClicked.connect(self.on_movie_clicked) self._view.rootObject().searchQuery.connect(self.on_search) self._view.rootObject().exitAction.connect(self.on_exit) self._status_timer.timeout.connect(self.update_status) self._status_timer.start(500) def _set_movie_status(self, text): self._rctx.setContextProperty("movieStatus", text) def _set_media(self, movie: Movie): file_name = movie.get_target_path() self._rctx.setContextProperty("movieSource", QUrl.fromLocalFile(file_name)) def _set_additional_media_info(self, title=None): self._rctx.setContextProperty("title", title or self._current_torrent_info.title or self._current_torrent_info.label) self._rctx.setContextProperty("poster", self._current_torrent_info.poster if self._current_torrent_info and self._current_torrent_info.poster else '') def _set_categories(self): data = [] for category in self._daemon.get_categories(): data.append(Tile(category.label, category.service.name)) self._rctx.setContextProperty("categoriesModel", data) self.categories = data def _threaded_set_torrents(self, data, thread): # if latest action if thread == self._movies_thread or thread == self._search_thread: self._set_torrents(data) def _set_torrents(self, data, loading=False): # only existing tiles for (tile, torrent_info) in zip(self.tiles, data[:len(self.tiles)]): if torrent_info.title: tile.name = torrent_info.title tile.source = torrent_info.label else: tile.name = torrent_info.label tile.source = None tile.poster = torrent_info.poster tile.description = torrent_info.description if len(data) != len(self.tiles): for torrent_info in data[len(self.tiles):]: if torrent_info.title: tile = Tile(torrent_info.title, torrent_info.label, torrent_info.poster, torrent_info.description) else: tile = Tile(torrent_info.label, None, torrent_info.poster, torrent_info.description) self.tiles.append(tile) self._rctx.setContextProperty("moviesModel", self.tiles) self.torrents = data self._set_loading(loading) def _set_loading(self, loading): self._rctx.setContextProperty("loadingMask", loading) def _set_duration(self, movie:Movie): tdelta = movie.get_movie_duration() if tdelta: self._view.rootObject().setProperty("movieDuration", tdelta.seconds * 1000)
app.setOrganizationName("theseus") app.setOrganizationDomain("ariadne") app.setApplicationName("visualizer") win = QMainWindow() win.setStyleSheet("background-color:white") widget = QWidget(win) win.setCentralWidget(widget) layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0,0,0,0) widget.setLayout(layout) #qml top panel view top_panel_view = QQuickView() top_panel_view.setResizeMode(QQuickView.SizeRootObjectToView) qml_top_panel_widget = QWidget.createWindowContainer(top_panel_view, win) qml_top_panel_widget.setFocusPolicy(Qt.WheelFocus) #qml bot panel view bot_panel_view = QQuickView() bot_panel_view.setResizeMode(QQuickView.SizeRootObjectToView) qml_bot_panel_widget = QWidget.createWindowContainer(bot_panel_view, win) qml_bot_panel_widget.setFocusPolicy(Qt.WheelFocus) basic_config = { "cache_path": "", "mode": "3d" } vis = Visualizer(basic_config, win)
try: from dbus.mainloop.glib import DBusGMainLoop dbus_loop = DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() session = bus.get_object('org.qoverview.config', '/org/qoverview/config') config = dbus.Interface(session, 'org.qoverview.config.iface') except dbus.DBusException as e: print(e) print('Unable to connect to config-server via DBUS') sys.exit(1) print('KDE Frameworks:', 'Yes' if KDE_FRAMEWORKS else 'No') qmlview = QQuickView(QUrl('/usr/lib/qoverview/ui.qml')) qmlview.setResizeMode(qmlview.SizeRootObjectToView) root = qmlview.rootObject() context = qmlview.rootContext() interface = PythonQMLInterface(view=qmlview, uid=uid, app=app) context.setContextProperty('Python', interface) qmlview.setTitle(interface.uid) print(interface.uid) qmlview.showFullScreen() app.exec_()
class View(object): shapes = ["rectangle", "ellipse", "image"] edgetypes = ["line", "curve"] def __init__(self): self._controller = Controller(self) self._gui = QGuiApplication(sys.argv) self._qml_dir = os.path.dirname(os.path.realpath(__file__)) self._main = QQuickView() self._main.setResizeMode(QQuickView.SizeRootObjectToView) self._main.setSource(QUrl(self._qml_dir + '/main.qml')) self._main.rootObject().create_node.connect( self._controller.create_node) self._main.rootObject().mouse_position.connect( self._controller.mouse_position) self._main.rootObject().save.connect( self._controller.save) self._main.rootObject().load.connect( self._controller.load) self._main.rootObject().lose_focus.connect( self._controller.lose_focus) self._main.rootObject().node_color_sel.connect( self._controller.node_color_sel) self._main.rootObject().edge_color_sel.connect( self._controller.edge_color_sel) self._main.rootObject().workspace_height_changed.connect( self._controller.workspace_height_changed) self._main.rootObject().workspace_width_changed.connect( self._controller.workspace_width_changed) self._main.rootObject().edge_type_sel.connect( self._controller.edge_type_sel) self._main.rootObject().node_shape_sel.connect( self._controller.node_shape_sel) self._main.rootObject().clear_workspace.connect( self._controller.clear_workspace) self._main.rootObject().node_width_changed.connect( self._controller.node_width_changed) self._main.rootObject().node_height_changed.connect( self._controller.node_height_changed) self._main.rootObject().node_text_color_sel.connect( self._controller.node_text_color_sel) self._main.rootObject().node_text_size_changed.connect( self._controller.node_text_size_changed) self._main.rootObject().edge_thickness_changed.connect( self._controller.edge_thickness_changed) self._main.rootObject().show_edge_controls.connect( self._controller.show_edge_controls) self._main.rootObject().hide_edge_controls.connect( self._controller.hide_edge_controls) self._main.rootObject().exporting.connect( self._controller.exporting) self._main.setProperty( "width", self._controller.project.workspace_width) self._main.setProperty( "height", self._controller.project.workspace_height) self._main.show() def run(self): return self._gui.exec_() def create_node(self, node): # Creates new node from source QML and puts it inside of main window qml_node = QQuickView(QUrl(self._qml_dir + '/shapes/' + self.shapes[node.shape] + '.qml'), self._main) workspace = self._main.rootObject().findChild(QQuickItem, "workspace") # Sets all properties qml_node.rootObject().setProperty("parent", workspace) qml_node.rootObject().setProperty("objectId", str(node.id)) qml_node.rootObject().setProperty("background", str(node.background)) qml_node.rootObject().setProperty("width", str(node.width)) qml_node.rootObject().setProperty("height", str(node.height)) qml_node.rootObject().setProperty("text", str(node.text.text)) qml_node.rootObject().setProperty("textFont", str(node.text.font)) qml_node.rootObject().setProperty("textSize", str(node.text.size)) qml_node.rootObject().setProperty("textColor", str(node.text.color)) # Sets drag boundaries qml_node.rootObject().setProperty("workspaceWidth", str(workspace.property("width"))) qml_node.rootObject().setProperty("workspaceHeight", str(workspace.property("height"))) # Signal connection qml_node.rootObject().node_delete.connect( self._controller.node_delete) qml_node.rootObject().node_text_changed.connect( self._controller.node_text_changed) qml_node.rootObject().node_position_changed.connect( self._controller.node_position_changed) qml_node.rootObject().node_connect.connect( self._controller.node_connect) qml_node.rootObject().node_focus.connect( self._controller.node_focus) if node.shape == 2: qml_node.rootObject().node_image_loaded.connect( self._controller.node_image_loaded) # Position to mouse click qml_node.rootObject().setX(node.x - node.width / 2) qml_node.rootObject().setY(node.y - node.height / 2) qml_node.rootObject().setZ(2) return qml_node def create_edge(self, edge, node1, node2): qml_edge = QQuickView(QUrl(self._qml_dir + '/edges/' + self.edgetypes[edge.type] + '.qml'), self._main) workspace = self._main.rootObject().findChild(QQuickItem, "workspace") qml_edge.rootObject().setProperty("parent", workspace) qml_edge.rootObject().setProperty("objectId", str(edge.id)) qml_edge.rootObject().setZ(1) qml_edge.rootObject().setProperty( "width", workspace.property("width")) qml_edge.rootObject().setProperty( "height", workspace.property("height")) qml_edge.rootObject().setProperty("ctrlX", str(edge.x)) qml_edge.rootObject().setProperty("ctrlY", str(edge.y)) qml_edge.rootObject().setProperty("startX", str(node1.x)) qml_edge.rootObject().setProperty("startY", str(node1.y)) qml_edge.rootObject().setProperty("endX", str(node2.x)) qml_edge.rootObject().setProperty("endY", str(node2.y)) qml_edge.rootObject().setProperty("color", str(edge.color)) qml_edge.rootObject().setProperty("thickness", str(edge.thickness)) qml_edge.rootObject().setProperty("spiked", str(edge.spiked)) qml_edge.rootObject().setProperty("arrow", str(edge.arrow)) # Sets drag boundaries qml_edge.rootObject().setProperty("workspaceWidth", str(workspace.property("width"))) qml_edge.rootObject().setProperty("workspaceHeight", str(workspace.property("height"))) # Signal connection qml_edge.rootObject().edge_delete.connect( self._controller.edge_delete) qml_edge.rootObject().edge_position_changed.connect( self._controller.edge_position_changed) qml_edge.rootObject().edge_focus.connect( self._controller.edge_focus) return qml_edge def node_update(self, node): pass
class Selector(QWidget): def __init__(self, goal_context, config_path, experimentlogger): self.path = config_path super(Selector, self).__init__() self.ros_timer = QTimer() self.ros_timer.timeout.connect(self.ros_poller) self.setup_ui() self.AUTOEXECUTE = False self.ignore_move_events = False self.context = goal_context self.planner = None self.current_plan = None self.current_action_succeeded = False self.current_action_index = 0 self.current_menu_index = 0 self.task = None self.planner = planning.Planner(goal_context.init, self.path) self.ros_handler = None self.experiment_logger = experimentlogger self.init_menu() self.show_goal_ui() def ros_poller(self): # print "checking for ROS triggered changes in ROS event queue" if self.ros_handler and self.ros_handler.event_queue: # print "Processing events from ROS event queue. There are %d events" % len(self.ros_handler.event_queue) event = self.ros_handler.event_queue.pop(0) # print "popped ", str(event[0]) if "teleop" not in str(event[0]): event[0]( *event[1] ) # event is a pair (method,[params]) the asteriks unpacks parameters else: logger.debug( "HEY, don't teleoperate while actions are running: %s", str(event[0])) # print "executed ", str(event[0]) def setup_ui(self): self.view = QQuickView() self.view.setResizeMode(QQuickView.SizeRootObjectToView) container = QWidget.createWindowContainer(self.view) container.setFocusPolicy(Qt.StrongFocus) layout = QVBoxLayout() layout.addWidget(container) self.setLayout(layout) ctx = self.view.rootContext() ctx.setContextProperty("selector", self) ctx.setContextProperty("C", ui_constants) self.set_menu([]) self.set_plan([]) self.set_current(None) self.view.setSource(QUrl(self.path + 'ui.qml')) self.resize(800, 800) self.move(300, 300) self.setWindowTitle('Goal Planner GUI') self.setWindowIcon(QIcon('images/icon.png')) reload = QShortcut(QKeySequence("Ctrl+R"), self) reload.activated.connect(self.reload_ui) quit = QShortcut(QKeySequence("Ctrl+C"), self) quit.activated.connect(self.quit) quit = QShortcut(QKeySequence("Esc"), self) quit.activated.connect(self.quit) self.ros_timer.start(10) self.showMaximized() def test_populate(self): l = ["give", "grasp", "drop", "open", "close"] self.set_menu(l) def set_current(self, goal): ctx = self.view.rootContext() ctx.setContextProperty("currentGoal", QVariant(goal)) self.current = goal # do not free the list while it's in the model def set_menu(self, elems): ctx = self.view.rootContext() ctx.setContextProperty("selectionsModel", QVariant(elems)) self.elems = elems # do not free the list while it's in the model def set_plan(self, elems): ctx = self.view.rootContext() ctx.setContextProperty("planModel", QVariant(elems)) self.plans = elems # do not free the list while it's in the model def activate_loading(self): compute_image_focus = self.view.rootObject().findChild( QObject, "compute_image_focus") compute_image_focus.turnOn() def deactivate_loading(self): compute_image_focus = self.view.rootObject().findChild( QObject, "compute_image_focus") compute_image_focus.turnOff() @pyqtSlot() def goal_menu(self): class create_goal_menu(QThread): def __init__(self, instance): QThread.__init__(self) self.instance = instance def __del__(self): self.wait() def run(self): if constants.SHOW_FUNCTION_GOALS: self.instance.next_goals = goals.FunctionGoal.initial_goals( self.instance.context ) + goals.ActionGoal.initial_goals(self.instance.context) else: self.instance.next_goals = goals.ActionGoal.initial_goals( self.instance.context) # logger2.debug("Next goals: %s", map(str, self.next_goals)) self.instance.next_goals = [ g for g in self.instance.next_goals if self.instance.filter_goal(g) ] """ Shows the selection of options """ self.experiment_logger.log_performance( "Goal Menu shows next goals ...") self.create_goal_menu_thread = create_goal_menu(self) self.create_goal_menu_thread.finished.connect( self.create_goal_menu_done) self.create_goal_menu_thread.start() self.activate_loading() def create_goal_menu_done(self): items = [GoalMenuItem(g, -1) for g in self.next_goals] items.append(BackMenuItem()) self.current_goal = GOAL_MENU self.build_header(None) self.set_menu(items) self.experiment_logger.log_performance( "Goal Menu shows next goals done", True) self.create_goal_menu_thread = None self.deactivate_loading() @pyqtSlot() def action_menu(self): self.next_goals = goals.ExecActionGoal.initial_goals(self.context) items = [GoalMenuItem(g, -1) for g in self.next_goals] items.append(BackMenuItem()) self.current_goal = ACTION_MENU self.build_header(None) self.set_menu(items) @pyqtSlot(int) def select_goal(self, index): # logger2.debug("select goal") # image = self.view.rootObject().findChild(QObject, "compute_image") # image.turnOn() # self.experiment_logger.log_performance("user chose goal #%s" %index) #traceback.print_stack() if self.next_goals: self.display_goal(self.next_goals[index]) #self.experiment_logger.log_performance("goal #%s displayed" %index) # image.turnOff() @pyqtSlot(int) def select_action(self, index): if self.ignore_move_events: logger.debug( "aborting action execution because an action is already in progress" ) return #print self.current_action_index, index if not (self.current_action_index == index or self.current_action_index + 1 == index): logger.debug("Execute previous actions first!!!") return if self.current_plan and index < len(self.current_plan): if self.current_plan[ index].status == plans.ActionStatusEnum.EXECUTED: logger.debug("The action was already executed") return plan_node = self.current_plan[index] plan_node.status = plans.ActionStatusEnum.IN_PROGRESS self.display_status_text("Action is in progress") self.ignore_move_events = True self.ros_handler.execute_on_robot(plan_node.action, plan_node.arguments) items = [ PlanItem(pnode, self.context) for pnode in self.current_plan ] self.set_plan(items) planView = self.view.rootObject().findChild(QObject, "planView") planView.setProperty("currentIndex", index) self.current_action_index = index self.current_action_succeeded = False logger.debug("action selection of %s done, action executed" % index) # self.show_plan_ui() def action_executed(self): success = self.current_action_succeeded planView = self.view.rootObject().findChild(QObject, "planView") index = self.current_action_index logger.debug("current action index %d was executed. success = %s" % (index, success)) if success: plan_node = self.current_plan[index] if not self.planner.execute_action(plan_node.action, plan_node.arguments): plan_node.status = plans.ActionStatusEnum.FAILED logger.fatal( "\033[91mWarning warning warning, Planner found action to be infeasible... aborting\033[0m" ) #assert False self.current_plan[index].status = plans.ActionStatusEnum.EXECUTED #logger.debug("will refresh context now") #self.refresh_context(self.planner.problem) else: self.current_plan[ index].status = plans.ActionStatusEnum.UNSUCCESSFUL self.ignore_move_events = False logger.debug("select next action in plan GUI") planView = self.view.rootObject().findChild(QObject, "planView") items = [PlanItem(pnode, self.context) for pnode in self.current_plan] self.set_plan(items) if success and index + 1 < len(self.current_plan): planView.setProperty("currentIndex", index + 1) # select next plan step if self.AUTOEXECUTE: logger.debug("Auto-executing next") pui = self.view.rootObject().findChild(QObject, "planner_ui") pui.teleop_select() else: logger.debug("autoexecute ist turned off") self.refresh_context(self.planner.problem) else: planView.setProperty("currentIndex", index) # self.show_plan_ui() def handle_world_update(self): world = self.view.rootObject().findChild(QObject, "world_image") world.turn_world() self.init_menu() self.show_goal_ui() self.planner.set_state(self.context.init) # print("World change happened, world turning image displayed. Now I check the plan") # print("goal= ",self.goal) # self.plan(goal) @pyqtSlot() def back(self): if self.ignore_move_events and self.current_plan[ self. current_action_index].status == plans.ActionStatusEnum.IN_PROGRESS: #action is currently running -> abort it self.current_plan[ self. current_action_index].status = plans.ActionStatusEnum.UNSUCCESSFUL planView = self.view.rootObject().findChild(QObject, "planView") items = [ PlanItem(pnode, self.context) for pnode in self.current_plan ] self.set_plan(items) planView.setProperty("currentIndex", self.current_action_index) self.ros_handler.abort_current_action() self.ignore_move_events = False return if self.menu_stack: g = self.menu_stack.pop() self.current_goal = None if g == GOAL_MENU: self.goal_menu() elif g == ACTION_MENU: self.action_menu() else: self.display_goal(g) else: self.init_menu() self.show_goal_ui() @pyqtSlot() def choose(self): logger.debug("choose pressed") # self.menu_stack.pop() goal = self.current_goal if goal.is_unique(): if isinstance(goal, goals.ExecActionGoal): self.execute_action_goal(goal) else: self.plan(goal) return if self.current_goal is not None: self.menu_stack.append(self.current_goal) current_index = goal.arg_index(goal.get_current_arg()) logger.debug("index = %d", current_index) logger.debug( "\033[93m next from current goal----------\n----------\n--------\n-------" ) self.next_goals = [ g for g in self.current_goal.next_all() if not g.is_empty() and self.filter_goal(g) ] #self.next_goals = [g for g in self.current_goal.next() if not g.is_empty() and self.filter_goal(g)] logger.debug("\033[0m next_goals: %s", map(str, self.next_goals)) items = [GoalMenuItem(g, current_index) for g in self.next_goals] if self.menu_stack: items.append(ChooseMenuItem()) items.append(BackMenuItem()) self.build_header(goal) self.set_menu(items) def reload_ui(self): # print "reload_ui clear cache" self.view.engine().clearComponentCache() # print "reload_ui set menu" self.set_menu([]) # print "reload_ui set plan" self.set_plan([]) # print "reload_ui set current" self.set_current(None) if self.mode == MENU_MODE_GOAL: logger.debug("reload_ui show goal") self.show_goal_ui() else: logger.debug("reload_ui show plan") self.show_plan_ui() #print "reload_ui updatself.menu_stack.append(self.current_goal)e" self.repaint() @pyqtSlot() def quit(self): #pass # self.hide() sys.exit(0) # @pyqtSlot('QString') def display_status_text(self, displaytext): # print "about to display in statusbar >%s<" % displaytext bar = self.view.rootObject().findChild(QObject, "statusbar") # QMetaObject.invokeMethod(bar, "display", Qt.DirectConnection, Q_ARG(QVariant, displaytext)) #bar.display("%s" % displaytext) bar.display("") def action_help(self, action): help = "" if action == "go": help = "go [robot] [room], i.e., move the robot into a room" elif action == "approach": help = "approach [robot] [target base], i.e., move the robot to a target (furniture, flowerbed, humans) in the current room" elif action == "drop": help = "drop [robot] [object] [target], i.e., drop an object on a target (furniture, flowerbed, humans)" elif action == "arrange": help = "arrange [robot] [flower] [vase], i.e., arrange a flower in a vase" elif action == "open": help = "open [robot] [bottle], i.e., lets the robot open a bottle" elif action == "drink": help = "drink [human] [vessel] [content], i.e., the robot gives a drink in a vessel with the specified content to the human" elif action == "pour": help = "pour [from vessel] [to vessel] [content], i.e., the robot pours a liquid (3. parameter) from the first vessel into the second one" elif action == "give": help = "give [robot] [object] [human], i.e., the robot brings an object to the human" elif action == "grasp": help = "grasp [robot] [object], i.e., the robot grasps an object" elif action == "pick": help = "pick [robot] [flower] [vase], i.e., the robot picks a flower from a vase" else: help = "Unknown action " + action return help @pyqtSlot(int) def display_status(self, index): text = "Unknown Element with Index " + str(index) # print "Displaying ", text # print "Current goal -> ", self.current_goal # print "Current menustack -> ", self.menu_stack # print "current -> ", self.current # print "Mode -> ", self.mode self.current_menu_index = index if self.mode == MENU_MODE_GOAL: if self.current_goal: # print "ui.py/display_status debug dump of current goal:" # print self.current_goal.__class__ # if type(self.current_goal) is not int: # print "active = %s" % self.current_goal.arg_index # print "goal args= " # for arg in self.current_goal.args: # print str(arg) if (index < len(self.next_goals)): next_goal = self.next_goals[index] text = str(next_goal) if isinstance(next_goal, goals.ActionGoal): action = next_goal.action.name help = self.action_help(action) text = "Current: " + text + "\nHelp: " + help elif (index == len(self.next_goals)): text = "BACK" else: text = rootMenu[index].arg[0].text else: if index < len(self.current_plan): text = str(self.current_plan[index]) else: text = "Cannot display status of step %s in a plan of length %s" % ( index, len(self.current_plan)) # if self.current_goal and isinstance(self.current_goal, goals.ActionGoal): # action = self.current_goal.action.name # help = self.action_help(action) # text = "Current: " + text + "\nHelp: " + help self.display_status_text(text) self.experiment_logger.log_navigation(index, text) def init_menu(self): # logger2.debug("initializing menu") # image = self.view.rootObject().findChild(QObject, "compute_image") # image.turnOn() self.mode = MENU_MODE_GOAL self.menu_stack = [] self.current_goal = None self.build_header(None) ctx = self.view.rootContext() # root = self.view.rootObject().findChild(QObject, "rootMenu") logger.debug("set context property to root menu %s", rootMenu) # image.turnOff() ctx.setContextProperty("selectionsModel", rootMenu) self.set_menu(rootMenu) def show_goal_ui(self): self.mode = MENU_MODE_GOAL gui = self.view.rootObject().findChild(QObject, "goal_ui") pui = self.view.rootObject().findChild(QObject, "planner_ui") pui.setProperty("visible", False) gui.setProperty("visible", True) gui.setProperty("focus", True) def show_plan_ui(self): logger.debug("show plan ui in mode %s", self.mode) self.mode = MENU_MODE_PLAN gui = self.view.rootObject().findChild(QObject, "goal_ui") pui = self.view.rootObject().findChild(QObject, "planner_ui") gui.setProperty("visible", False) pui.setProperty("visible", True) pui.setProperty("focus", True) self.display_status(0) def add_image_provider(self, image_provider): self.image_provider = image_provider self.view.rootContext().engine().addImageProvider( 'ros_image_provider', self.image_provider) image_provider.connect_gui(self) # def change_focuspoint_color_srv(self): # widget = self.view.rootObject().findChild(QObject, 'crosshair') # def switch_to_video_view(self): # self.view.rootObject().switch_to_video_view() # def switch_to_main_view(self): # self.view.rootObject().switch_to_main_view() def build_header(self, goal): if goal is None or goal.__class__ == goals.GoalSpec: self.set_current(None) return self.set_current(CurrentGoalItem(goal)) def display_goal(self, goal): class display_goal_menu(QThread): def __init__(self, instance, goal): QThread.__init__(self) self.instance = instance self.goal = goal def __del__(self): self.wait() def run(self): if self.goal.is_unique(): if isinstance(self.goal, goals.ExecActionGoal): self.instance.execute_action_goal(self.goal) else: self.instance.plan(self.goal, False) self.instance.show_plan_flag = True return self.instance.current_index = self.goal.arg_index( self.goal.get_current_arg()) self.instance.next_goals = [ g for g in self.instance.current_goal.next_flattened() if not g.is_empty() and self.instance.filter_goal(g) ] logger.debug("will display goal %s", str(goal)) self.experiment_logger.log_performance("ui.show_goal_ui display goal") # #CalledGoals.Instance().call_goal(goal) # if goal.is_unique(): # if isinstance(goal, goals.ExecActionGoal): # self.execute_action_goal(goal) # else: # self.plan(goal) # return # # if self.current_goal is not None: # self.menu_stack.append(self.current_goal) # # self.current_goal = goal # self.current_index = goal.arg_index(goal.get_current_arg()) #tmp_goals = [(-CalledGoals.Instance().get_calls(g)*100+i, g) for i, g in enumerate(self.current_goal.next_flattened()) if not g.is_empty() and self.filter_goal(g)] #tmp_goals.sort() #self.next_goals = [g for _, g in tmp_goals] if self.current_goal is not None: self.menu_stack.append(self.current_goal) self.current_goal = goal self.show_plan_flag = False self.display_goal_menu_thread = display_goal_menu(self, goal) self.display_goal_menu_thread.finished.connect( self.display_goal_menu_done) self.display_goal_menu_thread.start() self.activate_loading() # self.next_goals = [g for g in self.current_goal.next_flattened() if not g.is_empty() and self.filter_goal(g)] def display_goal_menu_done(self): if self.show_plan_flag: self.plan_update_gui() if self.experiment_logger.autoperform: self.quit() items = [GoalMenuItem(g, self.current_index) for g in self.next_goals] if self.menu_stack: #items.append(ChooseMenuItem()) items.append(BackMenuItem()) self.build_header(self.current_goal) self.set_menu(items) self.experiment_logger.log_performance("ui.display_goal_menu_done", True) self.display_goal_menu_thread = None self.deactivate_loading() def execute_action_goal(self, action_goal): action = action_goal.action problem = self.context.problem #instantiate an action that matches the selected action and execute it valid_args = action_goal.get_matches() action_args = [] for aarg in action_goal.action.args: if aarg in action_goal.used_arguments: i = action_goal.used_arguments.index(aarg) objects = set(tup[i] for tup in valid_args) # print self.args[i], map(str, objects) else: objects = list(problem.get_all_objects(aarg.type)) action_args.append(objects) inst_function = action.get_inst_func(self.context.init) args = None for mapping in action.smart_instantiate(inst_function, action.args, action_args, problem): args = [mapping[a] for a in action.args] break self.planner.execute_action(action, args) #self.refresh_context(self.planner.problem) self.menu_stack = [] self.action_menu() def refresh_context(self, problem, refs=None): if refs is None: # use old references instead refs = self.context.refs self.context = goals.GoalContext(problem, refs) def plan_update_gui(self): items = [PlanItem(pnode, self.context) for pnode in self.current_plan] self.set_plan(items) self.show_plan_ui() def plan(self, goal, update_gui=True): self.menu_stack = [] self.current_goal = None self.current_action_index = 0 assert self.planner is not None self.planner.find_plan(goal) self.current_plan = self.planner.get_plan() if update_gui: self.plan_update_gui() def filter_goal(self, goal): if goal.is_universal(): return False return True
from _004_3d_loading_model_and_rotating.object import ModelUnderlay import platform if __name__ == '__main__': # Not working in Ubuntu 16.04, result in 1282 error for simple calling like glViewport(...) # TODO if platform.uname().system == 'Darwin': f = QSurfaceFormat() f.setVersion(4, 1) f.setDepthBufferSize(1) # fix depth buffer error f.setStencilBufferSize(1) # fix stencil buffer error # If CoreProfile is used, all the other QML rendering will fail, because they only use 2.1 f.setProfile(QSurfaceFormat.CompatibilityProfile) QSurfaceFormat.setDefaultFormat(f) qmlRegisterType(ModelUnderlay, 'OpenGLUnderQml', 1, 0, 'ModelUnderlay') app = QGuiApplication(sys.argv) view = QQuickView() # view.setFormat(f) view.setPersistentSceneGraph(True) view.setPersistentOpenGLContext(True) view.setResizeMode(QQuickView.SizeRootObjectToView) # Set for the object to resize correctly view.setSource(QUrl('ModelWindow.qml')) view.show() app.exec()
class P2CQMLApplication(QGuiApplication): def __init__(self, list_of_str): super().__init__(list_of_str) self._current_category = None self._current_torrent = None self._current_torrent_info = None self._status_timer = QTimer(self) self._movies_thread = None self._search_thread = None def run_view(self): self._view = QQuickView() self._view.engine().addImportPath("qml") self._rctx = self._view.rootContext() self._view.setResizeMode(QQuickView.SizeRootObjectToView) # set context variables self.categories = [] self._rctx.setContextProperty("categoriesModel", self.categories) self.tiles = [] self.torrents = [] self._rctx.setContextProperty("moviesModel", self.tiles) self._set_loading(False) self._view.setSource(QUrl('qrc:/qml.qml')) self._view.showFullScreen() # self._view.show() def connect_daemon(self, daemon: P2CDaemon): self._daemon = daemon self._set_categories() self._connect_signals() def play(self, movie: Movie): self._set_movie_status("Ready to play!") self._set_media(movie) self._daemon.play(movie) self._set_additional_media_info() def buffer(self, movie: Movie): seconds = self._current_torrent.get_seconds_to_buffer() info = "just started" if seconds: if seconds < 15: info = "just a moment" else: # rount to minutes minutes = int(seconds / 60) + 1 if minutes == 1: info = "1 minute" else: info = "{} minutes".format(minutes) self._set_movie_status("Buffering... ({})".format(info)) self._daemon.buffer(movie) self._set_additional_media_info() def wait_for_metadata(self): self._set_movie_status("Getting metadata...") if self._current_torrent: self._set_additional_media_info(self._current_torrent.name) def select_movie(self, torrent: Torrent) -> Movie: movies = torrent.get_movies() if len(movies) == 0: return # TODO: show dialog with movie selecting instead of doing it automatically return max(movies, key=lambda x: x.size) def update_status(self): torrent = self._current_torrent if torrent: if (torrent.has_torrent_info()): movie = self.select_movie(torrent) if not movie: self._set_movie_status( "No movie in this torrent. Please, select another.") return torrent.download_file(movie.path) self._set_duration(movie) if not self._daemon.is_playing(movie): if (movie.can_play()): # print(movie.get_subtitles()) self.play(movie) else: self.buffer(movie) ### DEBUG INFO text = "s: %s, num p: %s, rate: %s kbs, p_rate: %s kbs" % ( torrent.get_status()['state'], torrent.get_status()['num_peers'], int(torrent.get_status()['download_rate'] / 1024), int(torrent.get_status()['download_payload_rate'] / 1024), ) self._view.rootObject().setProperty("debugText", text) ### END DEBUG INFO else: self.wait_for_metadata() else: self.wait_for_metadata() def on_category_clicked(self, index): # clear list self._set_torrents([], loading=True) category = self._daemon.get_categories()[index] self._current_category = category if self._current_category: self._search_thread = None self._movies_thread = SetMoviesThread(self._current_category) self._movies_thread.start() self._movies_thread.got_movies.connect(self._threaded_set_torrents) def on_movie_clicked(self, index): self._view.rootObject().setProperty("isMovieScene", True) torrent_ui = self.torrents[index] self._current_torrent = self._daemon.get_torrent(torrent_ui) self._current_torrent_info = torrent_ui self.update_status() def on_search(self, query): if len(query) < 3: return # clear list self._set_torrents([], loading=True) self._movies_thread = None self._search_thread = SearchThread(query, self._daemon.search) self._search_thread.start() self._search_thread.got_movies.connect(self._threaded_set_torrents) def on_exit(self): self.quit() def _connect_signals(self): self._view.rootObject().categoryClicked.connect( self.on_category_clicked) self._view.rootObject().movieClicked.connect(self.on_movie_clicked) self._view.rootObject().movieClicked.connect(self.on_movie_clicked) self._view.rootObject().searchQuery.connect(self.on_search) self._view.rootObject().exitAction.connect(self.on_exit) self._status_timer.timeout.connect(self.update_status) self._status_timer.start(500) def _set_movie_status(self, text): self._rctx.setContextProperty("movieStatus", text) def _set_media(self, movie: Movie): file_name = movie.get_target_path() self._rctx.setContextProperty("movieSource", QUrl.fromLocalFile(file_name)) def _set_additional_media_info(self, title=None): self._rctx.setContextProperty( "title", title or self._current_torrent_info.title or self._current_torrent_info.label) self._rctx.setContextProperty( "poster", self._current_torrent_info.poster if self._current_torrent_info and self._current_torrent_info.poster else '') def _set_categories(self): data = [] for category in self._daemon.get_categories(): data.append(Tile(category.label, category.service.name)) self._rctx.setContextProperty("categoriesModel", data) self.categories = data def _threaded_set_torrents(self, data, thread): # if latest action if thread == self._movies_thread or thread == self._search_thread: self._set_torrents(data) def _set_torrents(self, data, loading=False): # only existing tiles for (tile, torrent_info) in zip(self.tiles, data[:len(self.tiles)]): if torrent_info.title: tile.name = torrent_info.title tile.source = torrent_info.label else: tile.name = torrent_info.label tile.source = None tile.poster = torrent_info.poster tile.description = torrent_info.description if len(data) != len(self.tiles): for torrent_info in data[len(self.tiles):]: if torrent_info.title: tile = Tile(torrent_info.title, torrent_info.label, torrent_info.poster, torrent_info.description) else: tile = Tile(torrent_info.label, None, torrent_info.poster, torrent_info.description) self.tiles.append(tile) self._rctx.setContextProperty("moviesModel", self.tiles) self.torrents = data self._set_loading(loading) def _set_loading(self, loading): self._rctx.setContextProperty("loadingMask", loading) def _set_duration(self, movie: Movie): tdelta = movie.get_movie_duration() if tdelta: self._view.rootObject().setProperty("movieDuration", tdelta.seconds * 1000)
painter.setRenderHints(QPainter.Antialiasing, True) rect = QRectF(0, 0, self.width(), self.height()).adjusted(1, 1, -1, -1) painter.drawPie(rect, 90 * 16, 290 * 16) @pyqtSlot() def clearChart(self): self.color = QColor(Qt.transparent) self.update() self.chartCleared.emit() if __name__ == '__main__': import os import sys app = QGuiApplication(sys.argv) qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart") view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) view.setSource( QUrl.fromLocalFile( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app.qml'))) view.show() sys.exit(app.exec_())
# -*- coding: utf-8 -*- import os, sys, re from PyQt5.QtNetwork import * from fboinsgrenderer import * from textureinsgnode_rc import * from PyQt5.QtGui import QSurfaceFormat from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import (QVariant, QUrl, QDir, QSortFilterProxyModel, pyqtProperty, QSize, Q_ENUMS, QObject, QRegExp, QAbstractItemModel, pyqtSignal, Qt, QModelIndex, QByteArray) from PyQt5.QtQml import (QQmlApplicationEngine, QQmlEngine, QQmlFileSelector, qmlRegisterType, QQmlParserStatus, QJSValue) from PyQt5.QtQuick import QQuickView, QQuickItem, QQuickWindow if __name__ == '__main__': app = QApplication(sys.argv) qmlRegisterType(FboInSGRenderer, "SceneGraphRendering", 1, 0, "Renderer") widgetWindow = QQuickView() widgetWindow.setResizeMode(QQuickView.SizeRootObjectToView) widgetWindow.setSource(QUrl("qrc:///main.qml")) widgetWindow.show() sys.exit(app.exec_())
return animal.type() if role == self.SizeRole: return animal.size() return QVariant() def roleNames(self): return self._roles if __name__ == '__main__': import sys app = QGuiApplication(sys.argv) model = AnimalModel() model.addAnimal(Animal("Wolf", "Medium")) model.addAnimal(Animal("Polar bear", "Large")) model.addAnimal(Animal("Quoll", "Small")) view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) ctxt = view.rootContext() ctxt.setContextProperty('myModel', model) view.setSource(QUrl('qrc:view.qml')) view.show() sys.exit(app.exec_())
class PluginsStore(QDialog): def __init__(self, parent=None): super(PluginsStore, self).__init__(parent, Qt.Dialog) # QDialog.__init__(self, parent, Qt.Dialog | Qt.FramelessWindowHint) self.setWindowTitle(self.tr("Plugins Store")) self.setMaximumSize(QSize(0, 0)) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) self.view = QQuickView() self.view.setMinimumWidth(800) self.view.setMinimumHeight(600) self.view.setResizeMode(QQuickView.SizeRootObjectToView) self.view.setSource(ui_tools.get_qml_resource("PluginsStore.qml")) self.root = self.view.rootObject() vbox.addWidget(self.view) self._plugins = {} self._plugins_inflate = [] self._plugins_by_tag = collections.defaultdict(list) self._plugins_by_author = collections.defaultdict(list) self._base_color = QColor("white") self._counter = 0 self._counter_callback = None self._inflating_plugins = [] self._categoryTags = True self._search = [] self.status = None self.connect(self.root, SIGNAL("loadPluginsGrid()"), self._load_by_name) self.connect(self.root, SIGNAL("close()"), self.close) self.connect(self.root, SIGNAL("showPluginDetails(int)"), self.show_plugin_details) self.connect(self.root, SIGNAL("loadTagsGrid()"), self._load_tags_grid) self.connect(self.root, SIGNAL("loadAuthorGrid()"), self._load_author_grid) self.connect(self.root, SIGNAL("search(QString)"), self._load_search_results) self.connect(self.root, SIGNAL("loadPluginsForCategory(QString)"), self._load_plugins_for_category) self.connect(self, SIGNAL("processCompleted(PyQt_PyObject)"), self._process_complete) self.nenv = nenvironment.NenvEggSearcher() self.connect(self.nenv, SIGNAL("searchCompleted(PyQt_PyObject)"), self.callback) self.status = self.nenv.do_search() def _load_by_name(self): if self._plugins: self.root.showGridPlugins() for plugin in list(self._plugins.values()): self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) def _load_plugins_for_category(self, name): self.root.showGridPlugins() if self._categoryTags: for plugin in self._plugins_by_tag[name]: self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) else: for plugin in self._plugins_by_author[name]: self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) def callback(self, values): self.root.showGridPlugins() for i, plugin in enumerate(values): plugin.identifier = i + 1 self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) self._plugins[plugin.identifier] = plugin def show_plugin_details(self, identifier): plugin = self._plugins[identifier] self._counter = 1 self._counter_callback = self._show_details if plugin.shallow: self.connect(plugin, SIGNAL("pluginMetadataInflated(PyQt_PyObject)"), self._update_content) self._plugins_inflate.append(plugin.inflate()) else: self._update_content(plugin) def _load_tags_grid(self): self._categoryTags = True self._counter = len(self._plugins) self.root.updateCategoryCounter(self._counter) self._counter_callback = self._show_tags_grid self._inflating_plugins = list(self._plugins.values()) self._loading_function() def _load_author_grid(self): self._categoryTags = False self._counter = len(self._plugins) self.root.updateCategoryCounter(self._counter) self._counter_callback = self._show_author_grid self._inflating_plugins = list(self._plugins.values()) self._loading_function() def _load_search_results(self, search): self._search = search.lower().split() self._counter = len(self._plugins) self.root.updateCategoryCounter(self._counter) self._counter_callback = self._show_search_grid self._inflating_plugins = list(self._plugins.values()) self._loading_function() def _loading_function(self): plugin = self._inflating_plugins.pop() if plugin.shallow: self.connect(plugin, SIGNAL("pluginMetadataInflated(PyQt_PyObject)"), self._update_content) self._plugins_inflate.append(plugin.inflate()) else: self._process_complete(plugin) def _process_complete(self, plugin=None): self._counter -= 1 self.root.updateCategoryCounter(self._counter) if self._counter == 0: self._counter_callback(plugin) else: self._loading_function() def _show_search_grid(self, plugin=None): self.root.showGridPlugins() for plugin in list(self._plugins.values()): keywords = plugin.keywords.lower().split() + [plugin.name.lower()] for word in self._search: if word in keywords: self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) def _show_details(self, plugin): self.root.displayDetails(plugin.identifier) def _show_tags_grid(self, plugin=None): tags = sorted(self._plugins_by_tag.keys()) for tag in tags: color = self._get_random_color(self._base_color) self.root.addCategory(color.name(), tag) self.root.loadingComplete() def _show_author_grid(self, plugin=None): authors = sorted(self._plugins_by_author.keys()) for author in authors: color = self._get_random_color(self._base_color) self.root.addCategory(color.name(), author) self.root.loadingComplete() def _update_content(self, plugin): self.root.updatePlugin( plugin.identifier, plugin.author, plugin.author_email, plugin.description, plugin.download_url, plugin.home_page, plugin.license) keywords = plugin.keywords.split() for key in keywords: plugins = self._plugins_by_tag[key] if plugin not in plugins: plugins.append(plugin) self._plugins_by_tag[key] = plugins plugins = self._plugins_by_author[plugin.author] if plugin not in plugins: plugins.append(plugin) self._plugins_by_author[plugin.author] = plugins self.emit(SIGNAL("processCompleted(PyQt_PyObject)"), plugin) def _get_random_color(self, mix=None): red = random.randint(0, 256) green = random.randint(0, 256) blue = random.randint(0, 256) # mix the color if mix: red = (red + mix.red()) / 2 green = (green + mix.green()) / 2 blue = (blue + mix.blue()) / 2 color = QColor(red, green, blue) return color