def main(): app = QGuiApplication([]) try: path = QUrl(sys.argv[1]) except IndexError: print("Usage: pyqmlscene <filename>") sys.exit(1) engine = QQmlApplicationEngine() # Procedure similar to # https://github.com/qt/qtdeclarative/blob/0e9ab20b6a41bfd40aff63c9d3e686606e51e798/tools/qmlscene/main.cpp component = QQmlComponent(engine) component.loadUrl(path) root_object = component.create() if isinstance(root_object, QQuickWindow): # Display window object root_object.show() elif isinstance(root_object, QQuickItem): # Display arbitrary QQuickItems by reloading the source since # reparenting the existing root object to the view did not have any # effect. Neither does the QQuickView class have a setContent() method view = QQuickView(path) view.show() else: raise SystemExit("Error displaying {}".format(root_object)) sys.exit(app.exec_())
def init_country_names_from_code(locale): '''Init the country description as found in GCompris geography/resource/board/board*.qml''' '''in the global descriptions hash''' po = None try: po = polib.pofile( gcompris_qt + '/po/gcompris_' + locale + '.po') except: print "**ERROR: Failed to load po file %s**" %(gcompris_qt + '/po/gcompris_' + locale + '.po') print '' app = QCoreApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'): component.loadUrl(QUrl(qml)) board = component.create() levels = board.property('levels') for level in levels.toVariant(): if level.has_key('soundFile') and level.has_key('toolTipText'): sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg') tooltip = level['toolTipText'] if po: tooltip = po.find(tooltip).msgstr if po.find(tooltip) else tooltip descriptions[sound] = tooltip
def run(): directory = os.path.dirname(os.path.abspath(__file__)) appIcon = QIcon() appIcon.addFile(os.path.join(directory, "python.png"), QSize(64, 64)) app.setWindowIcon(appIcon) from . import registerQmlTypes registerQmlTypes() engine = QQmlApplicationEngine() context = QQmlContext(engine) mainQml = QUrl.fromLocalFile(os.path.join(directory, "Main.qml")) component = QQmlComponent(engine) component.loadUrl(mainQml) if component.isError(): for error in component.errors(): print("Error: ", error.toString()) dialog = component.create(context) return app.exec_()
def reloadProject(self, filename): engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl(filename)) self.site = component.create() if self.site is not None: self.site.setFilename(filename) self.site.setWindow(self) else: for error in component.errors(): print(error.toString()) return False self.site.loadMenus() self.site.loadPages() self.site.loadPosts() self.theme_settings_button.setVisible(False) Plugins.setActualThemeEditorPlugin("") for key in Plugins.themePluginNames(): tei = Plugins.getThemePlugin(key) if tei: if tei.theme_name == self.site.theme: Plugins.setActualThemeEditorPlugin(tei.class_name) self.theme_settings_button.setVisible(True) break #if not self.site.publisher: # if len(Plugins.publishPluginNames()) > 0: # self.site.publisher = Plugins.publishPluginNames[0] Plugins.setActualPublishPlugin(self.site.publisher) self.siteLoaded.emit(self.site) return True
def init_country_names_from_code(locale): '''Init the country description as found in GCompris geography/resource/board/board*.qml''' '''in the global descriptions hash''' po = None try: po = polib.pofile(gcompris_qt + '/po/gcompris_' + locale + '.po') except: print("**ERROR: Failed to load po file %s**" % ('/po/gcompris_' + locale + '.po')) print('') app = QCoreApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'): component.loadUrl(QUrl(qml)) board = component.create() levels = board.property('levels') for level in levels.toVariant(): if 'soundFile' in level and 'toolTipText' in level: sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg') tooltip = level['toolTipText'] if po: tooltip = po.find(tooltip).msgstr if po.find( tooltip) else tooltip descriptions[sound] = tooltip
def loadMenus(self): engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl(os.path.join(self.source_path, "Menus.qml"))) self.menus = component.create() if self.menus is not None: self.win.statusBar().showMessage("Menus have been loaded") else: for error in component.errors(): print(error.toString()) del engine
def loadProject(self, filename): self.last_project = filename self.filename = "" engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl(filename)) self.project = component.create() if self.project is not None: self.project.setFilename(filename) self.project.setWindow(self) else: for error in component.errors(): print(error.toString()) return
def main(argv, app): engine = QQmlEngine(app) engine.quit.connect(app.quit) component = QQmlComponent(engine) component.loadUrl(QUrl('Wizard/Wizard.qml')) if component.isReady(): mainWindow = component.create() file = FileInfo() context = engine.rootContext() context.setContextProperty('FileInfo', file) else: print(component.errorString()) sys.exit(app.exec_())
def get_geography_on_letter_from_code(): '''Return all the countries in geography/resource/board/board-x.json''' words = set() app = QCoreApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'): component.loadUrl(QUrl(qml)) board = component.create() levels = board.property('levels') for level in levels.toVariant(): if level.has_key('soundFile') and (not level.has_key('type') or level['type'] != "SHAPE_BACKGROUND"): sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg') words.add(sound) return words
def loadContent(self, source, type): if type == ContentType.PAGE: sub = "pages" else: sub = "posts" engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl(os.path.join(self.source_path, sub, source))) content = component.create() if content is not None: content.source = source content.content_type = type else: for error in component.errors(): print(error.toString()) return content
def main(): # Set up correct Ctrl-C behavior. signal.signal(signal.SIGINT, signal.SIG_DFL) app = QGuiApplication( sys.argv ) engine = QQmlEngine() engine.addImportPath( path.join( path.dirname( __file__ ), 'ui', 'qml' ) ) core.register_types() component = QQmlComponent( engine ) component.loadUrl( QUrl( '/home/feoh3/.config/nube/hud.qml' ) ) if component.isError(): print( "\n".join( error.toString() for error in component.errors() ) ) else: window = component.create() app.exec_()
def get_geography_on_letter_from_code(): '''Return all the countries in geography/resource/board/board-x.json''' words = set() app = QCoreApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'): component.loadUrl(QUrl(qml)) board = component.create() levels = board.property('levels') for level in levels.toVariant(): if 'soundFile' in level and (not 'type' in level or level['type'] != "SHAPE_BACKGROUND"): sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg') words.add(sound) return words
def loadMenus(self): engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl.fromLocalFile(os.path.join(self.source_path, "Menus.qml"))) self.menus = component.create() if self.menus is not None: self.win.statusBar().showMessage(QCoreApplication.translate("Site", "Menus have been loaded")) else: for error in component.errors(): print(error.toString()) del engine # we have to loop through the menu items to set the parent for subitems for i in range(0, len(self.menus._menus)): menu = self.menus._menus[i] for j in range(0, len(menu._items)): item = menu._items[j] for k in range(len(item._items)): subItem = item._items[k] subItem.setParentItem(item)
def main(arguments): 'Main logic' app = QCoreApplication([__file__] + arguments) # Register the Python type. Its URI is 'People', it's v1.0, and the type # will be called 'Person' in QML. qmlRegisterType(Person, 'People', 1, 0, 'Person') # Now we can load Person.qml, since it uses our registered python class engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl('Person.qml')) person = component.create() if person is not None: print("The person's name is {0}.".format(person.name)) print('They wear a size {0} shoe.'.format(person.shoe_size)) else: for error in component.errors(): print(error.toString())
def runQML(): app =QApplication(sys.argv) engine = QQmlApplicationEngine() #app.setWindowIcon(QIcon("icon.png")) # Register the Python type. Its URI is 'People', it's v1.0 and the type # will be called 'Person' in QML. qmlRegisterType(Model, 'Model', 1, 0, 'Model_QML') # Create a component factory and load the QML script. component = QQmlComponent(engine) component.loadUrl(QUrl('res/Model.qml')) engine.load('res/main.qml') # Create an instance of the component. model = component.create() ##test screen_resolution = app.desktop().screenGeometry() width, height = screen_resolution.width(), screen_resolution.height() #print("width: %d" % width) #print("height: %d" % height) if model is not None: # Print the value of the properties. print("The AG name is %s." % model.nameAG) print("The Ulysses PID is %s." % model.ulyssesPID) print("The Excel PID is %s." % model.excelPID) else: # Print all errors that occurred. for error in component.errors(): print(error.toString()) #example class #ex = Example() if not engine.rootObjects(): return -1 return app.exec_()
def ros_qml_main(): try: rospy.init_node('ros_qml', sys.argv) my_argv = rospy.myargv(sys.argv) signal.signal(signal.SIGINT, sigint_handler) app = QApplication(my_argv) engine = QQmlEngine() engine.quit.connect(app.quit) plugins_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath) # ## Add QML extension modules and plugins to the path, including ourselves plugins_paths = rospack.get_manifest(THIS_PACKAGE).get_export(THIS_PACKAGE, 'plugins') for idx, p in enumerate(plugins_paths): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): plugins_paths[idx] = plugins_dir + '/' + p qml_paths = rospack.get_manifest(THIS_PACKAGE).get_export(THIS_PACKAGE, 'imports') deps = rospack.get_depends_on(THIS_PACKAGE) for d in deps: pp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'plugins') for idx, p in enumerate(pp): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): pp[idx] = plugins_dir + '/' + p plugins_paths += pp qp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'imports') qml_paths += qp for p in plugins_paths: engine.addPluginPath(p) for p in qml_paths: engine.addImportPath(p) qml_sys_path = QLibraryInfo.location(QLibraryInfo.ImportsPath) engine.addImportPath(qml_sys_path) # Somehow we need to set the path both with QQmlEngine and with environment, # commenting any of the two will lead to 'module not installed' error os.environ['QML2_IMPORT_PATH'] = ':'.join(qml_paths) + ':' + qml_sys_path comp = QQmlComponent(engine) if len(my_argv) > 1 and my_argv[1]: qml_url = my_argv[1] comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_url'): qml_url = rospy.get_param('qml_url') comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_description'): # experimental qml_description = rospy.get_param('qml_description') # FIXME that hangs for unknown reason comp.setData(QByteArray(qml_description), QUrl()) else: rospy.logfatal('Neither /qml_url nor /qml_description (experimental) parameter is present') sys.exit(1) if not comp.isReady(): sys.stderr.write(comp.errorString()) sys.exit(1) win = comp.create() if not win: rospy.logfatal('Your root item has to be a Window') sys.exit(1) engine.setIncubationController(win.incubationController()) if win: win.show() # Poll Python interpreter every 500ms timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) sys.exit(app.exec_()) except KeyboardInterrupt: pass except rospy.ROSInterruptException: pass
#engine = QQmlApplicationEngine() # doesn't quite work because we aren't actually using the component associated # with this engine engine.quit.connect(app.quit) # from http://pyqt.sourceforge.net/Docs/PyQt5/qml.html # Register the Python type. Its URI is 'People', it's v1.0 and the type # will be called 'Person' in QML. qmlRegisterType(Weather, 'WeatherCategory', 1, 0, 'Weather') qmlRegisterType(DataPoint, 'WeatherCategory', 1, 0, 'DataPoint') qmlRegisterType(DataBlock, 'WeatherCategory', 1, 0, 'DataBlock') qmlRegisterType(Geocoder, 'WeatherCategory', 1, 0, 'Geocoder') component = QQmlComponent(engine) component.loadUrl(QUrl('WeatherDash.qml')) # Create the QML user interface. Auto creates its own engine view = QQuickView() engine2 = view.engine # Does not run #engine2.quit.connect(app.quit) #view.setSource(QUrl('PyTest.qml')) # To Satisfy cool-retro-term needs view.rootContext().setContextProperty('devicePixelRatio', app.devicePixelRatio()) view.setSource(QUrl('WeatherDash.qml')) #view.setResizeMode(QDeclarativeView.SizeRootObjectToView) view.setGeometry(100, 100, 750, 480)
class ApplicationHandler(QObject): end_find_handling = pyqtSignal() messages_recieved = pyqtSignal() end_chat = pyqtSignal() MAX_MESSAGE_WIDTH = 160 FIND_CHAT_SLEEP_TIME = 2 GET_MESSAGES_SLEEP_TIME = 0.1 def __init__(self): QObject.__init__(self) self.connectengine = QQmlApplicationEngine("connectform.qml") self.root = self.connectengine.rootObjects()[0] button = self.get_obj('connect_button') button.clicked.connect(self.connect) self.root.show() self.drawn = [] self.end_find_handling.connect(self.create_chat) self.messages_recieved.connect(self.message_drawer) self.end_chat.connect(self.end_chat_locally) def address(self): return 'http://' + self.host + ':' + self.port def connect(self): self.host = self.get_obj('host_input_text').property('text') self.port = self.get_obj('port_input_text').property('text') answer = requests.get(self.address() + '/') if answer.status_code == 200: args = answer.json() self.id = args['id'] self.key = args['key'] self.root.close() self.engine = QQmlApplicationEngine('form.qml') self.root = self.engine.rootObjects()[0] self.root.show() self.get_obj('return_button').clicked.connect(self.stop_find_chat) self.get_obj('find_chat_button').clicked.connect(self.find_chat) self.get_obj('disconnect_button').clicked.connect(self.disconnect) self.get_obj('text_input').message_ready.connect(self.send_message) self.get_obj('leave_chat_button').clicked.connect(self.leave_chat) self.message0_component = QQmlComponent(self.engine) self.message0_component.loadUrl(QUrl('message0.qml')) self.message1_component = QQmlComponent(self.engine) self.message1_component.loadUrl(QUrl('message1.qml')) self.draw_main() def find_chat(self): self.draw_waiting() handler = threading.Thread(target=self.find_chat_handler) self.looking_for_chat = True handler.start() def find_chat_handler(self): while self.looking_for_chat: answer = requests.post(self.address() + '/user', params=dict(cmd='find_chat', id=self.id, key=self.key)) args = answer.json() if args['status'] == 'ok': self.end_find_handling.emit() return time.sleep(self.FIND_CHAT_SLEEP_TIME) def create_chat(self): self.draw_chat() handler = threading.Thread(target=self.get_messages_handler) self.chatting = True handler.start() self.items = [] self.item_id = 0 self.column_height = 0 self.get_obj('text_input').setProperty('text', '') def get_messages_handler(self): while self.chatting: answer = requests.post(self.address() + '/chat', params=dict(cmd='get_messages', id=self.id, key=self.key)) args = answer.json() if args['status'] == 'chat ended': self.end_chat.emit() return if args['msg']: self.message_buffer = args['msg'] self.messages_recieved.emit() time.sleep(self.GET_MESSAGES_SLEEP_TIME) def message_drawer(self): current = self.message_buffer self.message_buffer = [] for msg_response in current: id = msg_response['id'] text = msg_response['msg'] if id == int(self.id): item = self.message0_component.create() else: item = self.message1_component.create() item.setProperty('text', text) if int(item.property('width')) > self.MAX_MESSAGE_WIDTH: item.setProperty('width', str(self.MAX_MESSAGE_WIDTH)) height = item.property('height') self.column_height += height + 8 self.get_obj('message_column_layout').setProperty( 'height', self.column_height) item.setParentItem(self.get_obj('message_column_layout')) self.items.append(item) self.get_obj('message_frame').update() def send_message(self): text = self.get_obj('text_input').property('text') self.get_obj('text_input').setProperty('text', '') requests.post(self.address() + '/chat', params=dict(cmd='send_message', msg=text, id=self.id, key=self.key)) def leave_chat(self): self.chatting = False requests.post(self.address() + '/chat', params=dict(cmd='stop', id=self.id, key=self.key)) self.draw_main() def end_chat_locally(self): self.chatting = False self.draw_main() def stop_find_chat(self): requests.post(self.address() + '/user', params=dict(cmd='stop_find_chat', id=self.id, key=self.key)) self.looking_for_chat = False self.draw_main() def disconnect(self): self.looking_for_chat = False requests.post(self.address() + '/user', params=dict(cmd='disconnect', id=self.id, key=self.key)) self.root.close() self.root = self.connectengine.rootObjects()[0] button = self.get_obj('connect_button') button.clicked.connect(self.connect) self.root.show() def get_obj(self, name): return self.root.findChild(QObject, name) def show_obj(self, name): obj = self.get_obj(name) obj.setVisible(True) def hide_obj(self, name): obj = self.get_obj(name) obj.setVisible(False) def draw_main(self): self.draw_clear() self.draw_obj('find_chat_button') self.draw_obj('disconnect_button') def draw_waiting(self): self.draw_clear() self.draw_obj('looking_for_chat_text') self.draw_obj('return_button') def draw_chat(self): self.draw_clear() self.draw_obj('message_frame') self.draw_obj('text_input_rectangle') self.draw_obj('leave_chat_button') def draw_obj(self, name): self.show_obj(name) self.drawn.append(name) def draw_clear(self): for item in self.drawn: self.hide_obj(item) self.drawn = []
#!/usr/bin/env python3 import sys from PyQt5.QtCore import pyqtProperty, QObject, QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import qmlRegisterType, QQmlComponent, QQmlEngine # Create the application instance. app = QApplication(sys.argv) # Create a QML engine. engine = QQmlEngine() # Create a component factory and load the QML script. component = QQmlComponent(engine) component.loadUrl(QUrl('main.qml')) # get window window = component.create() window.show() app.exec_()
# -*- coding : utf-8 -*- from PyQt5.QtCore import QUrl,QCoreApplication from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlEngine,QQmlComponent import os import sys app = QGuiApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl("main.qml")) top = component.create() if top : top.show() sys.exit(app.exec_())
class PhotoBoothGUI(QObject): def run(self): # Create main app self.myApp = QApplication(sys.argv) # Create a label and set its properties self.appLabel = QQuickView() #self.appLabel.setSource(QUrl('loading.qml')) # Show the Label self.appLabel.show() # Initialize PhotoBoothEngine. self.pbengine = PhotoBoothEngine() self.pbengine.on_change_url.connect(self.update_url_signal) self.pbengine.on_connect_signal.connect(self.connect_signal) self.pbengine.change_qml(0) self.pbengine.connect_state(0) print("UPDATE") #self.pbengine.on_status.connect(self.appLabel.rootObject().status) #self.pbengine.on_update_filter_preview.connect(self.appLabel.rootObject().updateImageFilterPreview) self.appLabel.rootContext().setContextProperty('pbengine', self.pbengine) self.setup_text_status_fly_component() self.pbengine.start_state_thread(0) # Execute the Application and Exit self.myApp.exec_() sys.exit() def setup_text_status_fly_component(self): # Create a component factory and load the QML script. print("Hello") self.component = QQmlComponent(self.appLabel.engine()) self.component.loadUrl(QUrl('qml/TextStatusFly.qml')) print("Hello2") self.statuswidget = self.component.create(self.appLabel.rootContext()) print("Hello3") self.statuswidget.setParentItem(self.appLabel.rootObject()) self.statuswidget.setParent(self.appLabel.rootObject()) print("Hello4") #statuswidget.setProperty("targetX", 100) self.statuswidget.setProperty("objectName", "textStatusBar") print("Hello5") self.appLabel.rootContext().setContextProperty('textStatusBar', self.statuswidget) self.statuswidget.setProperty("parentSet", True) def update_url_signal(self, url): print(" ** Updating URL: %s" % url) #self.pbengine.on_change_url.disconnect() #self.pbengine.on_connect_signal.disconnect() self.appLabel.rootContext().setContextProperty('textStatusBar', None) self.appLabel.setSource(QUrl()) self.appLabel.engine().clearComponentCache() self.appLabel.setSource(QUrl(url)) self.setup_text_status_fly_component() self.appLabel.show() # Reconnect #self.pbengine.on_change_url.connect(self.update_url_signal) #self.pbengine.on_connect_signal.connect(self.connect_signal) def connect_signal(self, signal, target): print(" ** Binding signal %s to target %s!" % (str(signal), target)) print(" ** (getattr(self.appLabel, target) = %s)" % (str(getattr(self.appLabel.rootObject(), target)))) signal.connect(getattr(self.appLabel.rootObject(), target))
qmlRegisterType(HomeView.Seq_List, 'IGT_GUI', 1, 0, 'Seq_List') qmlRegisterType(HomeView.Message,'IGT_GUI', 1, 0, 'Message') qmlRegisterType(HomeView.Message_List,'IGT_GUI', 1, 0, 'Message_List') # Activate the actual QML Application sys_argv = sys.argv sys_argv += ['--style', 'universal'] app = QGuiApplication(sys_argv) engine=QQmlApplicationEngine() # Initialize Variables to Communicate with QML Layer engine.rootContext().setContextProperty('all_msgs', all_msgs) # Initialize the Main View component = QQmlComponent(engine) component.loadUrl(QUrl("MainWindow.qml")) mainWindow = component.create() stackView = mainWindow.findChild(QObject, "stack") # Generate the Views home_view = HomeView.HomeView(engine,mainWindow,all_msgs,gen,stackView) load_seq_view = LoadSeqView.LoadSeqView(engine, mainWindow, all_msgs,gen,motor) motor_view = MotorView.MotorView(engine,mainWindow,all_msgs,motor) home_view.load_views(load_seq_view,motor_view) # Load the home view home_view.load()
def ros_qml_main(): try: rospy.init_node('ros_qml', sys.argv) my_argv = rospy.myargv(sys.argv) signal.signal(signal.SIGINT, sigint_handler) app = QApplication(my_argv) engine = QQmlEngine() engine.quit.connect(app.quit) plugins_dir = QLibraryInfo.location(QLibraryInfo.PluginsPath) # ## Add QML extension modules and plugins to the path, including ourselves plugins_paths = rospack.get_manifest(THIS_PACKAGE).get_export( THIS_PACKAGE, 'plugins') for idx, p in enumerate(plugins_paths): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): plugins_paths[idx] = plugins_dir + '/' + p qml_paths = rospack.get_manifest(THIS_PACKAGE).get_export( THIS_PACKAGE, 'imports') deps = rospack.get_depends_on(THIS_PACKAGE) for d in deps: pp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'plugins') for idx, p in enumerate(pp): # If a relative path provided, treat it as relative to Qt plugins dir if not os.path.isabs(p): pp[idx] = plugins_dir + '/' + p plugins_paths += pp qp = rospack.get_manifest(d).get_export(THIS_PACKAGE, 'imports') qml_paths += qp for p in plugins_paths: engine.addPluginPath(p) for p in qml_paths: engine.addImportPath(p) qml_sys_path = QLibraryInfo.location(QLibraryInfo.ImportsPath) engine.addImportPath(qml_sys_path) # Somehow we need to set the path both with QQmlEngine and with environment, # commenting any of the two will lead to 'module not installed' error os.environ['QML2_IMPORT_PATH'] = ':'.join( qml_paths) + ':' + qml_sys_path comp = QQmlComponent(engine) if len(my_argv) > 1 and my_argv[1]: qml_url = my_argv[1] comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_url'): qml_url = rospy.get_param('qml_url') comp.loadUrl(QUrl(qml_url)) elif rospy.has_param('qml_description'): # experimental qml_description = rospy.get_param('qml_description') # FIXME that hangs for unknown reason comp.setData(QByteArray(qml_description), QUrl()) else: rospy.logfatal( 'Neither /qml_url nor /qml_description (experimental) parameter is present' ) sys.exit(1) if not comp.isReady(): sys.stderr.write(comp.errorString()) sys.exit(1) win = comp.create() if not win: rospy.logfatal('Your root item has to be a Window') sys.exit(1) engine.setIncubationController(win.incubationController()) if win: win.show() # Poll Python interpreter every 500ms timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) sys.exit(app.exec_()) except KeyboardInterrupt: pass except rospy.ROSInterruptException: pass
import sys from PyQt5.QtCore import pyqtProperty, QCoreApplication, QObject, QUrl from PyQt5.QtQml import qmlRegisterType, QQmlComponent, QQmlEngine class EEGApp(QObject): def __init__(self, parent=None): eegdata = None sens = 7.0 speed = 30.0 app = QCoreApplication(sys.argv) # Register the Python type. Its URI is 'People', it's v1.0 and the type # will be called 'Person' in QML. qmlRegisterType(Person, 'People', 1, 0, 'Person') # Create a QML engine. engine = QQmlEngine() # Create a component factory and load the QML script. component = QQmlComponent(engine) component.loadUrl(QUrl('example.qml')) # Create an instance of the component. #person = component.create()
# Create main app myApp = QApplication(sys.argv) # Create a label and set its properties appLabel = QQuickView() appLabel.setSource(QUrl('main.qml')) #appLabel.load(QUrl('main2.qml')) # Show the Label appLabel.show() # Create a QML engine. engine = QQmlEngine() # Create a component factory and load the QML script. component = QQmlComponent(engine) component.loadUrl(QUrl('TextStatusFly.qml')) # Create an instance of the component. #person = component.create() asdf = component.create() asdf.setParentItem(appLabel.rootObject()) asdf.setParent(appLabel.rootObject()) asdf.setProperty("targetX", 100) #asdf.setProperty("y", 100) print(appLabel) print(appLabel.rootObject()) print(asdf)
toolbar = self.addToolBar('Exit') # toolbar.setObjectName('ToolBar') # toolbar.addAction(exitAction) # toolbar.addAction(processUrlAction) self.restoreState() self.show() if __name__ == '__main__': app = QApplication(sys.argv) qmlRegisterType(JiraMain, 'JiraTree', 1, 0, 'MainWindow') engine = QQmlEngine() # Create a component factory and load the QML script. component = QQmlComponent(engine) component.loadUrl(QUrl.fromLocalFile('main.qml')) jm = component.create() [print(e.toString()) for e in component.errors()] engine.rootContext().setContextProperty("mainWindow", jm) if jm is None: print("JM is none") print({e.toString() for e in component.errors()}) # ex = JiraMain(None) print("Run") app.exec() print("Exit") sys.exit()
import sys from PyQt5.QtCore import QObject, QUrl, pyqtSlot from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine, QQmlComponent, QQmlContext from SignalHandler import SignalHandler if __name__ == "__main__": app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() configurator = SignalHandler() engine.load("qml/SimpleMainWindow.qml") engine.quit.connect(app.quit) rootWindow = engine.rootObjects()[0] content_item = rootWindow.property("contentItem") context = QQmlContext(engine) component = QQmlComponent(engine) component.loadUrl(QUrl("qml/TestViewButton.qml")) itm = component.create(context) context.setContextProperty("configurator", configurator) itm.setProperty("parent", content_item) sys.exit(app.exec_())
@name.setter def name(self, name): self._name = name @shoeSize.setter def shoeSize(self, shoeSize): self._shoeSize = shoeSize app = QCoreApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) qmlRegisterType(Person, 'People', 1, 0, 'Person') engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl('person.qml')) person = component.create() if person is not None: print("The person's name is {}".format(person.name)) print("They wear a size {} shoe".format(person.shoeSize)) else: for error in component.errors(): print(error.toString()) loop.run_forever()
return self._name @name.setter def name(self, name): self._name = name @pyqtProperty(int) def shoeSize(self): return self._shoeSize @shoeSize.setter def shoeSize(self, shoeSize): self._shoeSize = shoeSize app = QCoreApplication(sys.argv) qmlRegisterType(Person, 'People', 1, 0, 'Person') engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl('example.qml')) person = component.create() if person is not None: print "The person's name is %s." % person.name print "They wear a size %d shoe." % person.shoeSize else: for error in component.errors(): print error.toString()
self._name = name @shoeSize.setter def shoeSize(self, shoeSize): self._shoeSize = shoeSize app = QCoreApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) qmlRegisterType(Person, 'People', 1, 0, 'Person') engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl('person.qml')) person = component.create() if person is not None: print("The person's name is {}".format(person.name)) print("They wear a size {} shoe".format(person.shoeSize)) else: for error in component.errors(): print(error.toString()) loop.run_forever()
def getID(self, val): global PORT global producerID producerID = val print("Received: " + val) if val == "Producer1": PORT = 33000 elif val == "Producer2": PORT = 33001 else: PORT = 33003 startConnections() @pyqtSlot(str) def send_extracted_message(self, msg): send_msg(msg) # Initialize the software window. app = QApplication(sys.argv) # Create the QtQuick engine and load the software's root component. engine = QQmlApplicationEngine() irc = IRC() engine.rootContext().setContextProperty("irc", irc) component = QQmlComponent(engine) component.loadUrl(QUrl('main.qml')) window = component.create() app.exec_()
from PyQt5.QtQml import QQmlComponent, QQmlApplicationEngine from PyQt5.QtQuick import QQuickWindow from view_model import ViewModel if __name__ == '__main__': myApp = QApplication(sys.argv) engine = QQmlApplicationEngine() context = engine.rootContext() engine.addImportPath("/home/bob/Qt/5.11.2/Automotive/sources/qtapplicationmanager/dummyimports/") # create a view model view_model = ViewModel() # bind the view model to the context context.setContextProperty('view_model', view_model) component = QQmlComponent(engine) component.loadUrl(QUrl('mainwindow.qml')) # some boilerplate to make sure the component is ready before showing if component.status() != QQmlComponent.Ready: if component.status() == QQmlComponent.Error: sys.exit(component.errorString()) root_window: QQuickWindow = component.create() myApp.exec_() sys.exit()
qmlRegisterType(StraightLine, "CustomGeometry", 1, 0, "StraightLine") # Create QML engine engine = QQmlApplicationEngine() # Load the qml file into the engine engine.addImportPath(str(resolved_path)) engine.load("main/main.qml") if not engine.rootObjects(): sys.exit(-1) # load the components component = QQmlComponent(engine) component.loadUrl(QUrl("components/Class.qml")) line_component = QQmlComponent(engine) line_component.loadUrl(QUrl("components/Edge.qml")) # check for component creation errors for error in component.errors(): print(error.toString()) # check for component creation errors for error in line_component.errors(): print(error.toString()) classes = [] for index, class_name in enumerate(["Person", "Home"]): # create a new instance of the component cclass = component.create() # set the class name property of the component cclass.setProperty("className", class_name)
appLabel.show() # Create a QML engine. engine = QQmlEngine() # Initialize PhotoBoothEngine. pbengine = PhotoBoothEngine() pbengine.on_status.connect(appLabel.rootObject().status) pbengine.on_update_filter_preview.connect(appLabel.rootObject().updateImageFilterPreview) appLabel.rootContext().setContextProperty('pbengine', pbengine) # Create a component factory and load the QML script. print("Hello") component = QQmlComponent(appLabel.engine()) component.loadUrl(QUrl('TextStatusFly.qml')) print("Hello2") asdf = component.create(appLabel.rootContext()) print("Hello3") asdf.setParentItem(appLabel.rootObject()) asdf.setParent(appLabel.rootObject()) print("Hello4") #asdf.setProperty("targetX", 100) asdf.setProperty("objectName", "textStatusBar") print("Hello5") appLabel.rootContext().setContextProperty('textStatusBar', asdf)
class MainWindow(QMainWindow): htmlReady = pyqtSignal(str) def __init__(self, app): QMainWindow.__init__(self) self.install_directory = os.getcwd() self.app = app self.book = None self.last_book = "" self.filename = "" self._part_is_new = False self.tread_running = False self.initTheme() self.createUi() self.loadPlugins() self.createMenus() self.createStatusBar() self.readSettings() self.text_edit.textChanged.connect(self.textChanged) def initTheme(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) self.theme = settings.value("theme", "DarkFusion") hilite_color = settings.value( "hiliteColor", self.palette().highlight().color().name()) self.changeStyle(self.theme, hilite_color) def showEvent(self, event): if self.last_book: self.loadBook(self.last_book) def changeStyle(self, theme, hilite_color): self.theme = theme if theme == "DarkFusion": QApplication.setStyle(DarkFusion(hilite_color)) else: QApplication.setStyle(QStyleFactory.create(theme)) pal = self.app.palette() pal.setColor(QPalette.Highlight, QColor(hilite_color)) self.app.setPalette(pal) def createUi(self): self.content = Expander("Content", ":/images/parts.svg") self.images = Expander("Images", ":/images/images.svg") self.settings = Expander("Settings", ":/images/settings.svg") self.setWindowTitle(QCoreApplication.applicationName() + " " + QCoreApplication.applicationVersion()) vbox = QVBoxLayout() vbox.addWidget(self.content) vbox.addWidget(self.images) vbox.addWidget(self.settings) vbox.addStretch() self.content_list = QListWidget() self.content_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) content_box = QVBoxLayout() content_box.addWidget(self.content_list) self.item_edit = QLineEdit() self.item_edit.setMaximumHeight(0) self.item_edit.editingFinished.connect(self.editItemFinished) self.item_anim = QPropertyAnimation(self.item_edit, "maximumHeight".encode("utf-8")) content_box.addWidget(self.item_edit) button_layout = QHBoxLayout() plus_button = FlatButton(":/images/plus.svg") self.edit_button = FlatButton(":/images/edit.svg") self.trash_button = FlatButton(":/images/trash.svg") self.up_button = FlatButton(":/images/up.svg") self.down_button = FlatButton(":/images/down.svg") self.trash_button.enabled = False self.up_button.enabled = False self.down_button.enabled = False button_layout.addWidget(plus_button) button_layout.addWidget(self.up_button) button_layout.addWidget(self.down_button) button_layout.addWidget(self.edit_button) button_layout.addWidget(self.trash_button) content_box.addLayout(button_layout) self.content.addLayout(content_box) plus_button.clicked.connect(self.addPart) self.trash_button.clicked.connect(self.dropPart) self.up_button.clicked.connect(self.partUp) self.down_button.clicked.connect(self.partDown) self.edit_button.clicked.connect(self.editPart) self.image_list = QListWidget() self.image_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) image_box = QVBoxLayout() image_box.addWidget(self.image_list) image_button_layout = QHBoxLayout() image_plus_button = FlatButton(":/images/plus.svg") self.image_trash_button = FlatButton(":/images/trash.svg") self.image_trash_button.enabled = False image_button_layout.addWidget(image_plus_button) image_button_layout.addWidget(self.image_trash_button) image_box.addLayout(image_button_layout) self.images.addLayout(image_box) image_plus_button.clicked.connect(self.addImage) self.image_trash_button.clicked.connect(self.dropImage) scroll_content = QWidget() scroll_content.setLayout(vbox) scroll = QScrollArea() scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setWidget(scroll_content) scroll.setWidgetResizable(True) scroll.setMaximumWidth(200) scroll.setMinimumWidth(200) self.navigationdock = QDockWidget("Navigation", self) self.navigationdock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.navigationdock.setWidget(scroll) self.navigationdock.setObjectName("Navigation") self.addDockWidget(Qt.LeftDockWidgetArea, self.navigationdock) self.splitter = QSplitter() self.text_edit = MarkdownEdit() self.text_edit.setFont(QFont("Courier", 15)) # 11 on Linux self.preview = QWebEngineView() self.preview.setMinimumWidth(300) self.setWindowTitle(QCoreApplication.applicationName()) self.splitter.addWidget(self.text_edit) self.splitter.addWidget(self.preview) self.setCentralWidget(self.splitter) self.content.expanded.connect(self.contentExpanded) self.images.expanded.connect(self.imagesExpanded) self.settings.expanded.connect(self.settingsExpanded) self.settings.clicked.connect(self.openSettings) self.content_list.currentItemChanged.connect(self.partSelectionChanged) self.image_list.currentItemChanged.connect(self.imageSelectionChanged) self.image_list.itemDoubleClicked.connect(self.insertImage) self.text_edit.undoAvailable.connect(self.undoAvailable) self.text_edit.redoAvailable.connect(self.redoAvailable) self.text_edit.copyAvailable.connect(self.copyAvailable) QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged) def undoAvailable(self, value): self.undo_act.setEnabled(value) def redoAvailable(self, value): self.redo_act.setEnabled(value) def copyAvailable(self, value): self.copy_act.setEnabled(value) self.cut_act.setEnabled(value) def clipboardDataChanged(self): md = QApplication.clipboard().mimeData() self.paste_act.setEnabled(md.hasText()) def openSettings(self): dlg = Settings(self.book, self.install_directory) dlg.exec() if dlg.saved: self.setWindowTitle(QCoreApplication.applicationName() + " - " + self.book.name) def addPart(self): self.item_edit.setText("") self.item_edit.setFocus() self.item_anim.setStartValue(0) self.item_anim.setEndValue(23) self.item_anim.start() self._part_is_new = True def addItem(self): text = self.item_edit.text() if text: if not self.book.getPart(text): self.book.addPart(text) self.loadBook(self.last_book) def updateItem(self): text = self.item_edit.text() if text: if not self.book.getPart(text): self.book.updatePart( self.content_list.currentItem().data(1).name, text) self.loadBook(self.last_book) def editItemFinished(self): if self._part_is_new: self.addItem() else: self.updateItem() self.item_anim.setStartValue(23) self.item_anim.setEndValue(0) self.item_anim.start() def editPart(self): item = self.content_list.currentItem().data(1).name self.item_edit.setText(item) self.item_edit.setFocus() self.item_anim.setStartValue(0) self.item_anim.setEndValue(23) self.item_anim.start() self._part_is_new = False def dropPart(self): item = self.content_list.currentItem().data(1).name msgBox = QMessageBox() msgBox.setText("You are about to delete the part <i>" + item + "</i>") msgBox.setInformativeText("Do you really want to delete the item?") msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Cancel) ret = msgBox.exec() if ret == QMessageBox.Yes: self.book.dropPart(item) self.loadBook(self.last_book) def addImage(self): fileName = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("Image Files(*.png *.jpg *.bmp *.gif);;All (*)") dialog.setWindowTitle("Load Image") dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptOpen) if dialog.exec_(): fileName = dialog.selectedFiles()[0] del dialog if not fileName: return base = os.path.basename(fileName) if not os.path.exists( os.path.join(self.book.source_path, "images", base)): copy(fileName, os.path.join(self.book.source_path, "images")) item = QListWidgetItem() item.setText(Path(fileName).name) item.setData( 1, os.path.join(self.book.source_path, "images", Path(fileName).name)) self.image_list.addItem(item) def dropImage(self): item = self.image_list.currentItem() image = item.data(1) filename = os.path.join(self.book.source_path, "parts", image) os.remove(filename) self.loadImages() def loadImages(self): self.image_list.clear() for root, dir, files in os.walk( os.path.join(self.book.source_path, "images")): for file in files: filename = os.path.join(self.book.source_path, "images", Path(file).name) item = QListWidgetItem() item.setToolTip("Doubleclick image to insert into text") item.setText(Path(file).name) item.setData(1, filename) self.image_list.addItem(item) def partUp(self): pos = self.content_list.currentRow() item = self.content_list.takeItem(pos) self.content_list.insertItem(pos - 1, item) self.content_list.setCurrentRow(pos - 1) self.book.partUp(item.data(1).name) def partDown(self): pos = self.content_list.currentRow() item = self.content_list.takeItem(pos) self.content_list.insertItem(pos + 1, item) self.content_list.setCurrentRow(pos + 1) self.book.partDown(item.data(1).name) def partSelectionChanged(self, item): if item: part = item.data(1) self.filename = os.path.join(self.book.source_path, "parts", part.src) with open(self.filename, "r") as f: t = f.read() self.text_edit.setPlainText(t) self.trash_button.enabled = True self.up_button.enabled = self.content_list.currentRow() > 0 self.down_button.enabled = self.content_list.currentRow( ) < self.content_list.count() - 1 self.edit_button.enabled = True else: self.text_edit.setText("") self.trash_button.enabled = False self.up_button.enabled = False self.down_button.enabled = False self.edit_button.enabled = False def imageSelectionChanged(self, item): if item: self.image_trash_button.enabled = True else: self.image_trash_button.enabled = False def contentExpanded(self, value): if value: self.images.setExpanded(False) self.settings.setExpanded(False) def imagesExpanded(self, value): if value: self.content.setExpanded(False) self.settings.setExpanded(False) def appearanceExpanded(self, value): if value: self.content.setExpanded(False) self.images.setExpanded(False) self.settings.setExpanded(False) def settingsExpanded(self, value): if value: self.content.setExpanded(False) self.images.setExpanded(False) def closeEvent(self, event): self.writeSettings() event.accept() def createMenus(self): new_icon = QIcon(QPixmap(":/images/new.svg")) open_icon = QIcon(QPixmap(":/images/open.svg")) book_icon = QIcon(QPixmap(":/images/book.svg")) bold_icon = QIcon(QPixmap(":/images/bold.svg")) italic_icon = QIcon(QPixmap(":/images/italic.svg")) image_icon = QIcon(QPixmap(":/images/image.svg")) table_icon = QIcon(QPixmap(":/images/table.svg")) á_icon = QIcon(QPixmap(":/images/á.svg")) ã_icon = QIcon(QPixmap(":/images/ã.svg")) é_icon = QIcon(QPixmap(":/images/é.svg")) ê_icon = QIcon(QPixmap(":/images/ê.svg")) ó_icon = QIcon(QPixmap(":/images/ó.svg")) new_act = QAction(new_icon, "&New", self) new_act.setShortcuts(QKeySequence.New) new_act.setStatusTip("Create a new ebook project") new_act.triggered.connect(self.newFile) new_act.setToolTip("Create new ebook project") open_act = QAction(open_icon, "&Open", self) open_act.setShortcuts(QKeySequence.Open) open_act.setStatusTip("Open an existing ebook project") open_act.triggered.connect(self.open) open_act.setToolTip("Open an existing ebook project") book_act = QAction(book_icon, "&Create Book", self) book_act.setShortcuts(QKeySequence.SaveAs) book_act.setStatusTip("Create an ebook") book_act.triggered.connect(self.create) book_act.setToolTip("Create an ebook") pdf_act = QAction("Create &PDF", self) pdf_act.setStatusTip("Create PDF") pdf_act.setToolTip("Create PDF") pdf_act.triggered.connect(self.pdfExport) settings_act = QAction("&Settings", self) settings_act.setStatusTip("Open settings dialog") settings_act.triggered.connect(self.settingsDialog) settings_act.setToolTip("Open settings dialog") exit_act = QAction("E&xit", self) exit_act.setShortcuts(QKeySequence.Quit) exit_act.setStatusTip("Exit the application") exit_act.triggered.connect(self.close) self.undo_act = QAction("Undo", self) self.undo_act.setShortcut(QKeySequence.Undo) self.undo_act.setEnabled(False) self.undo_act.triggered.connect(self.doUndo) self.redo_act = QAction("Redo", self) self.redo_act.setShortcut(QKeySequence.Redo) self.redo_act.setEnabled(False) self.undo_act.triggered.connect(self.doRedo) self.cut_act = QAction("Cu&t", self) self.cut_act.setShortcut(QKeySequence.Cut) self.cut_act.triggered.connect(self.doCut) self.cut_act.setEnabled(False) self.copy_act = QAction("&Copy", self) self.copy_act.setShortcut(QKeySequence.Copy) self.copy_act.triggered.connect(self.doCopy) self.copy_act.setEnabled(False) self.paste_act = QAction("&Paste", self) self.paste_act.setShortcut(QKeySequence.Paste) self.paste_act.triggered.connect(self.doPaste) self.paste_act.setEnabled(False) bold_act = QAction(bold_icon, "Bold", self) bold_act.setShortcut(Qt.CTRL + Qt.Key_B) bold_act.triggered.connect(self.bold) italic_act = QAction(italic_icon, "Italic", self) italic_act.setShortcut(Qt.CTRL + Qt.Key_I) italic_act.triggered.connect(self.italic) image_act = QAction(image_icon, "Image", self) image_act.setShortcut(Qt.CTRL + Qt.Key_G) image_act.triggered.connect(self.insertImage) image_act.setToolTip("Insert an image") table_act = QAction(table_icon, "Table", self) table_act.setShortcut(Qt.CTRL + Qt.Key_T) table_act.triggered.connect(self.insertTable) table_act.setToolTip("Insert a table") á_act = QAction(á_icon, "á", self) á_act.triggered.connect(self.insertLetterA1) á_act.setToolTip("Insert letter á") ã_act = QAction(ã_icon, "ã", self) ã_act.triggered.connect(self.insertLetterA2) ã_act.setToolTip("Insert letter ã") é_act = QAction(é_icon, "é", self) é_act.triggered.connect(self.insertLetterE1) é_act.setToolTip("Insert letter é") ê_act = QAction(ê_icon, "ê", self) ê_act.triggered.connect(self.insertLetterE2) ê_act.setToolTip("Insert letter ê") ó_act = QAction(ó_icon, "ó", self) ó_act.triggered.connect(self.insertLetterO1) ó_act.setToolTip("Insert letter ó") about_act = QAction("&About", self) about_act.triggered.connect(self.about) about_act.setStatusTip("Show the application's About box") spell_act = QAction("&Spellcheck", self) spell_act.setShortcut(Qt.CTRL + Qt.Key_P) spell_act.triggered.connect(self.spellCheck) spell_act.setStatusTip("Spellcheck") file_menu = self.menuBar().addMenu("&File") file_menu.addAction(new_act) file_menu.addAction(open_act) file_menu.addAction(book_act) file_menu.addAction(pdf_act) file_menu.addSeparator() file_menu.addAction(settings_act) file_menu.addSeparator() file_menu.addAction(exit_act) edit_menu = self.menuBar().addMenu("&Edit") edit_menu.addAction(self.undo_act) edit_menu.addAction(self.redo_act) edit_menu.addSeparator() edit_menu.addAction(self.cut_act) edit_menu.addAction(self.copy_act) edit_menu.addAction(self.paste_act) format_menu = self.menuBar().addMenu("&Format") format_menu.addAction(bold_act) format_menu.addAction(italic_act) insert_menu = self.menuBar().addMenu("&Insert") insert_menu.addAction(image_act) insert_menu.addAction(table_act) for key in Plugins.generatorPluginNames(): gen = Plugins.getGeneratorPlugin(key) if gen: act = QAction(gen.display_name, self) #act.triggered.connect(self.insertTable) #act.setToolTip("Insert a table") insert_menu.addAction(act) act.triggered.connect(gen.menu_action) help_menu = self.menuBar().addMenu("&Help") help_menu.addAction(about_act) help_menu.addAction(spell_act) file_tool_bar = self.addToolBar("File") file_tool_bar.addAction(new_act) file_tool_bar.addAction(open_act) file_tool_bar.addAction(book_act) format_tool_bar = self.addToolBar("Format") format_tool_bar.addAction(bold_act) format_tool_bar.addAction(italic_act) insert_toolbar = self.addToolBar("Insert") insert_toolbar.addAction(image_act) insert_toolbar.addAction(table_act) insert_toolbar.addAction(á_act) insert_toolbar.addAction(ã_act) insert_toolbar.addAction(é_act) insert_toolbar.addAction(ê_act) insert_toolbar.addAction(ó_act) def doUndo(self): self.text_edit.undo() def doRedo(self): self.text_edit.redo() def doCut(self): self.text_edit.cut() def doCopy(self): self.text_edit.copy() def doPaste(self): self.text_edit.paste() def insertImage(self): if not self.book: QMessageBox.warning(self, QCoreApplication.applicationName(), "You have to load or create a book first!") return if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return if self.image_list.count() == 0: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to add an image to the image list first!") return if not self.image_list.currentItem(): QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select an image from the image list first!") return item = self.image_list.currentItem() filename = item.text() cursor = self.text_edit.textCursor() pos = cursor.position() base = filename.split(".")[0].replace("_", "-") cursor.insertText("![" + base + "](../images/" + filename + " \"" + base + "\")") cursor.setPosition(pos) self.text_edit.setTextCursor(cursor) def insertTable(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText( "| alignLeft | alignCenter | unAligned | alignRight |\n" "| :--- | :---: | --- | ---: |\n" "| cell a | cell b | cell c | cell d |\n" "| cell e | cell f | cell g | cell h |\n") cursor.setPosition(pos) self.text_edit.setTextCursor(cursor) def insertLetterA1(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("á") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterA2(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("ã") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterE1(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("é") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterE2(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("ê") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def insertLetterO1(self): cursor = self.text_edit.textCursor() pos = cursor.position() cursor.insertText("ó") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def createStatusBar(self): self.statusBar().showMessage("Ready") def about(self): QMessageBox.about( self, "About " + QCoreApplication.applicationName(), "EbookCreator\nVersion: " + QCoreApplication.applicationVersion() + "\n(C) Copyright 2020 CrowdWare. All rights reserved.\n\nThis program is provided AS IS with NO\nWARRANTY OF ANY KIND, INCLUDING THE\nWARRANTY OF DESIGN, MERCHANTABILITY AND\nFITNESS FOR A PATICULAR PURPOSE." ) def newFile(self): dlg = ProjectWizard(self.install_directory, parent=self) dlg.loadBook.connect(self.loadBook) dlg.show() def open(self): fileName = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("EbookCreator (book.qml);;All (*)") dialog.setWindowTitle("Load Ebook") dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setDirectory(os.path.join(self.install_directory, "sources")) if dialog.exec_(): fileName = dialog.selectedFiles()[0] del dialog if not fileName: return self.loadBook(fileName) def writeSettings(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) settings.setValue("geometry", self.saveGeometry()) settings.setValue("lastBook", self.last_book) def readSettings(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) geometry = settings.value("geometry", QByteArray()) self.last_book = settings.value("lastBook") if not geometry: availableGeometry = QApplication.desktop().availableGeometry(self) self.resize(availableGeometry.width() / 3, availableGeometry.height() / 2) self.move((availableGeometry.width() - self.width()) / 2, (availableGeometry.height() - self.height()) / 2) else: self.restoreGeometry(geometry) def bold(self): if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return cursor = self.text_edit.textCursor() pos = cursor.position() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.insertText("**" + cursor.selectedText() + "**") cursor.setPosition(pos + 2) self.text_edit.setTextCursor(cursor) def italic(self): if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return cursor = self.text_edit.textCursor() pos = cursor.position() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.insertText("*" + cursor.selectedText() + "*") cursor.setPosition(pos + 1) self.text_edit.setTextCursor(cursor) def create(self): filename = "" dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("ePub3 (*.epub);;All (*)") dialog.setWindowTitle("Create Ebook") dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDirectory(self.book.source_path) dialog.setDefaultSuffix("epub") if dialog.exec_(): filename = dialog.selectedFiles()[0] del dialog if not filename: return QApplication.setOverrideCursor(Qt.WaitCursor) createEpub(filename, self.book, self) QApplication.restoreOverrideCursor() def loadStatusChanged(self, status): if status == 1: self.book = self.component.create() if self.book is not None: self.book.setFilename(self.last_book) self.book.setWindow(self) else: for error in self.component.errors(): print(error.toString()) return self.content_list.clear() for part in self.book.parts: item = QListWidgetItem() item.setText(part.name) item.setData(1, part) self.content_list.addItem(item) self.loadImages() self.setWindowTitle(QCoreApplication.applicationName() + " - " + self.book.name) self.content.setExpanded(True) self.content_list.setCurrentRow(0) elif status == 3: for error in self.component.errors(): print(error.toString()) return def loadBook(self, filename): self.last_book = filename self.filename = "" engine = QQmlEngine() self.component = QQmlComponent(engine) self.component.statusChanged.connect(self.loadStatusChanged) self.component.loadUrl(QUrl.fromLocalFile(filename)) def settingsDialog(self): dlg = SettingsDialog(self.theme, self.palette().highlight().color().name(), parent=self) dlg.exec() if dlg.theme != self.theme or dlg.hilite_color != self.palette( ).highlight().color().name(): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, QCoreApplication.organizationName(), QCoreApplication.applicationName()) settings.setValue("theme", dlg.theme) settings.setValue("hiliteColor", dlg.hilite_color) msgBox = QMessageBox() msgBox.setText("Please restart the app to change the theme!") msgBox.exec() def textChanged(self): text = self.text_edit.toPlainText() if self.filename: with open(self.filename, "w") as f: f.write(text) self.lock = Lock() with self.lock: if not self.tread_running: self.tread_running = True self.htmlReady.connect(self.previewReady) thread = Thread(target=self.createHtml, args=(text, )) thread.daemon = True thread.start() def previewReady(self, html): self.preview.setHtml( html, baseUrl=QUrl( Path(os.path.join(self.book.source_path, "parts", "index.html")).as_uri())) self.htmlReady.disconnect() with self.lock: self.tread_running = False def createHtml(self, text): html = '<html>\n<head>\n' html += '<link href="../css/pastie.css" rel="stylesheet" type="text/css"/>\n' html += '<link href="../css/stylesheet.css" rel="stylesheet" type="text/css"/>\n' html += '</head>\n<body>\n' html += markdown(text, html4tags=False, extras=[ "fenced-code-blocks", "wiki-tables", "tables", "header-ids" ]) html += '\n</body>\n</html>' html = addLineNumbers(html) self.htmlReady.emit(html) def pdfExport(self): p = PdfExport(self.book, self.statusBar()) def spellCheck(self): if not self.filename: QMessageBox.warning( self, QCoreApplication.applicationName(), "You have to select part from the book content first!") return cursor = self.text_edit.textCursor() pos = cursor.position() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) spell = Speller(lang='en') changed = spell(cursor.selectedText()) if changed != cursor.selectedText(): cursor.insertText(changed) self.text_edit.setTextCursor(cursor) def loadPlugins(self): # check if we are running in a frozen environment (pyinstaller --onefile) if getattr(sys, "frozen", False): bundle_dir = sys._MEIPASS # if we are running in a onefile environment, then copy all plugin to /tmp/... if bundle_dir != os.getcwd(): os.mkdir(os.path.join(bundle_dir, "plugins")) for root, dirs, files in os.walk( os.path.join(os.getcwd(), "plugins")): for file in files: shutil.copy(os.path.join(root, file), os.path.join(bundle_dir, "plugins")) print("copy", file) break # do not copy __pycache__ else: bundle_dir = os.getcwd() plugins_dir = os.path.join(bundle_dir, "plugins") for root, dirs, files in os.walk(plugins_dir): for file in files: modulename, ext = os.path.splitext(file) if ext == ".py": module = import_module("plugins." + modulename) for name, klass in inspect.getmembers( module, inspect.isclass): if klass.__module__ == "plugins." + modulename: instance = klass() if isinstance(instance, GeneratorInterface): Plugins.addGeneratorPlugin(name, instance) instance.setTextEdit(self.text_edit) #instance.registerContenType() break # not to list __pycache__