本文整理汇总了Python中PyQt5.QtQml.QQmlApplicationEngine.rootContext方法的典型用法代码示例。如果您正苦于以下问题:Python QQmlApplicationEngine.rootContext方法的具体用法?Python QQmlApplicationEngine.rootContext怎么用?Python QQmlApplicationEngine.rootContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtQml.QQmlApplicationEngine
的用法示例。
在下文中一共展示了QQmlApplicationEngine.rootContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MainWindow
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
class MainWindow(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self.model = MainWindowViewModel(self)
self.loginModel = LoginViewModel(self)
self.engine = QQmlApplicationEngine(self)
self.engine.rootContext().setContextProperty('model', self.model)
self.engine.rootContext().setContextProperty('loginModel', self.loginModel)
self.engine.quit.connect(parent.quit)
self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml'))
self.window = self.engine.rootObjects()[0]
# wire up logging console
self.log = self.window.findChild(QQuickItem, 'log')
parent.log_changed.connect(self._log)
def show(self):
self.window.show()
def _log(self, msg):
# replace with collections.deque binding(ish)?
if self.log.property('lineCount') == LOG_BUFFER_SIZE:
line_end = self.log.property('text').find('\n') + 1
self.log.remove(0, line_end)
self.log.append(msg)
示例2: main
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
def main():
app = QGuiApplication(sys.argv)
qmlRegisterType(MainController, 'MainController', 1, 0, 'MainController')
qmlRegisterType(ProfileViewModel, 'ProfileViewModel', 1, 0, 'ProfileViewModel')
engine = QQmlApplicationEngine()
main_controller = MainController()
main_controller.profile_selection_changed(0)
engine.rootContext().setContextProperty('mainController', main_controller)
engine.load(QUrl.fromLocalFile(pkg_resources.resource_filename('yarg.resource', 'main.qml')))
sys.exit(app.exec_())
示例3: PixelWall
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
class PixelWall(QApplication):
def __init__(self, *args, **kwargs):
super(PixelWall, self).__init__(*args, **kwargs)
self.engine = QQmlApplicationEngine(self)
self.servers = ServerModel(self.engine)
self.settings = QSettings('OpenServices', 'PixelWall')
url = self.settings.value('server/url')
self.engine.setNetworkAccessManagerFactory(NetworkAccessManagerFactory('hetzner.fladi.at', 3128))
ctxt = self.engine.rootContext()
ctxt.setContextProperty('app', self)
ctxt.setContextProperty('url', 'about:blank')
self.engine.load(QUrl('states.qml'))
discoverer = Avahi(self.engine, '_pixelwall._tcp')
discoverer.initialized.connect(self.serverState)
discoverer.added.connect(self.servers.addService)
ctxt.setContextProperty('serverModel', self.servers)
discoverer.run()
if url:
self.setUrl(url)
self.setState('Web')
def setState(self, state):
for root in self.engine.rootObjects():
node = root.findChild(QObject, 'main')
if node:
logger.info('Setting state: {}'.format(state))
node.setProperty('state', state)
def setUrl(self, url):
logger.info('Connecting WebView to {}'.format(url))
ctxt = self.engine.rootContext()
ctxt.setContextProperty('url', 'https://www.heise.de/')
@pyqtSlot()
def reset(self):
self.settings.remove('server/url')
self.setState('Servers')
@pyqtSlot(int)
def serverSelected(self, index):
server = self.servers.getIndex(index)
logger.info('Server selected {}'.format(server))
url = 'https://{server.host}:{server.port}/'.format(server=server)
self.settings.setValue('server/url', url)
self.setUrl(url)
self.setState('Web')
@pyqtSlot()
def serverState(self):
self.setState('Servers')
示例4: __init__
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
class Application:
organization = 'pisak'
name = 'pisak'
def __init__(self, gui):
self._app = QApplication(sys.argv)
self._app.setOrganizationName(self.organization)
self._app.setApplicationName(self.name)
self._context = _ApplicationContext()
self._engine = QQmlApplicationEngine()
self._engine.rootContext().setContextProperty('pisak', self._context)
self._engine.load(gui)
def run(self):
sys.exit(self._app.exec_())
示例5: Application
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
class Application(QApplication):
def __init__(self, argv):
super(Application, self).__init__(argv)
stderrHandler = logging.StreamHandler(stream=sys.stderr)
stderrHandler.setLevel(logging.WARN)
stdoutHandler = logging.StreamHandler(stream=sys.stdout)
stdoutHandler.setLevel(logging.INFO)
stdoutHandler.filter = lambda rec: rec.levelno <= stdoutHandler.level
logging.basicConfig(
format='%(name)-15s %(message)s',
level=logging.INFO,
handlers=[stderrHandler, stdoutHandler]
)
logger.info("__init__")
self._qml_engine = QQmlApplicationEngine()
self._root_context = self._qml_engine.rootContext()
self.char = Character(self)
def setContext(self, name, value):
self._root_context.setContextProperty(name, value)
def start(self):
logger.info("start")
self.setContext('character', self.char)
self.readModels()
self._qml_engine.load(QUrl("qrc:/ui/main.qml"))
def readModels(self):
logger.info("readModels")
modelTypes = [
MODEL.Perk,
MODEL.Quirk,
MODEL.Species
]
allDelayedInits = {}
for modelType in modelTypes:
delayedInits = []
logger.info("parsing model %s", modelType.__name__)
g = modelParsers.parse(modelType, delayedInits=delayedInits)
allDelayedInits[modelType] = delayedInits
model = list(g)
# TODO
name = "%sModel" % modelType.__name__
assert model is not None, "failed to parse {0}".format(modelType.__name__)
self.setContext(name, model)
for modelType, delayedInits in allDelayedInits.items():
logger.info("delayed init model %s (%s)", modelType.__name__, len(delayedInits))
for delayedInit in delayedInits:
delayedInit()
def exec(self):
logger.info("exec")
super().exec()
示例6: MainWindow
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
class MainWindow(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self.log = logging.getLogger(__name__)
self._read_settings()
self.client = Client(self)
if self.remember:
self._autologin()
self.model = MainWindowViewModel(self)
self.loginModel = LoginViewModel(self.client, self.user, self.password, self.remember, self)
self.loginModel.panel_visible = not self.remember
self.gamesModel = GamesViewModel(self)
self.engine = QQmlApplicationEngine(self)
self.engine.rootContext().setContextProperty('windowModel', self.model)
self.engine.rootContext().setContextProperty('loginModel', self.loginModel)
self.engine.rootContext().setContextProperty('contentModel', self.gamesModel)
self.engine.quit.connect(parent.quit)
self.engine.load(QUrl.fromLocalFile('ui/Chrome.qml'))
self.window = self.engine.rootObjects()[0]
# wire up logging console
self.console = self.window.findChild(QQuickItem, 'console')
parent.log_changed.connect(self._log)
def show(self):
self.window.show()
def _read_settings(self):
stored = settings.get()
stored.beginGroup('login')
self.user = stored.value('user')
self.password = stored.value('password')
self.remember = stored.value('remember') == 'true'
stored.endGroup()
@async_slot
def _autologin(self):
try:
self.log.info('logging in (auto)...')
self.loginModel.logged_in = yield from self.client.login(self.user, self.password)
self.log.debug('autologin result: {}'.format(self.loginModel.logged_in))
except Exception as e:
self.log.error('autologin failed. {}'.format(e))
@pyqtSlot(str)
def _log(self, msg):
# replace with collections.deque binding(ish)?
if self.console.property('lineCount') == LOG_BUFFER_SIZE:
line_end = self.console.property('text').find('\n') + 1
self.console.remove(0, line_end)
self.console.append(msg)
示例7: MyApp
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
class MyApp(QObject):
def __init__(self, qml, set_context=None):
super().__init__()
self.app = QApplication(sys.argv)
self.engine = QQmlApplicationEngine(self)
self.root_context = self.engine.rootContext()
if set_context:
set_context(self.root_context)
self.engine.load(QUrl(qml))
self.root_view = self.engine.rootObjects()[0]
@staticmethod
def run(my_app):
my_app.root_view.show()
return my_app.app.exec_()
示例8: main
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
def main(argv):
signal.signal(signal.SIGINT, signal.SIG_DFL)
qapp = QGuiApplication([])
engine = QQmlApplicationEngine()
data_list = []
for entry in os.scandir(argv[1]):
url = "file://" + urllib.parse.quote(os.path.abspath(entry.path))
digest = hashlib.md5(os.fsencode(url)).hexdigest()
result = os.path.join(xdg.BaseDirectory.xdg_cache_home, "thumbnails", "normal", digest + ".png")
data_list.append(Foo(entry.name, result, "2018-01-11T19:20"))
engine.load(QUrl('main.qml'))
ctxt = engine.rootContext()
ctxt.setContextProperty("menu2", QVariant(data_list))
win = engine.rootObjects()[0]
win.show()
sys.exit(qapp.exec())
示例9: QtApplication
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
#.........这里部分代码省略.........
pass
def run(self):
pass
def hideMessage(self, message):
with self._message_lock:
if message in self._visible_messages:
self._visible_messages.remove(message)
self.visibleMessageRemoved.emit(message)
def showMessage(self, message):
with self._message_lock:
if message not in self._visible_messages:
self._visible_messages.append(message)
message.setTimer(QTimer())
self.visibleMessageAdded.emit(message)
def setMainQml(self, path):
self._main_qml = path
def initializeEngine(self):
# TODO: Document native/qml import trickery
Bindings.register()
self._engine = QQmlApplicationEngine()
for path in self._qml_import_paths:
self._engine.addImportPath(path)
if not hasattr(sys, "frozen"):
self._engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml"))
self._engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR)
self.registerObjects(self._engine)
self._engine.load(self._main_qml)
self.engineCreatedSignal.emit()
engineCreatedSignal = Signal()
def isShuttingDown(self):
return self._shutting_down
def registerObjects(self, engine):
pass
def getRenderer(self):
if not self._renderer:
self._renderer = QtRenderer()
return self._renderer
def addCommandLineOptions(self, parser):
parser.add_argument("--disable-textures",
dest="disable-textures",
action="store_true", default=False,
help="Disable Qt texture loading as a workaround for certain crashes.")
# Overridden from QApplication::setApplicationName to call our internal setApplicationName
def setApplicationName(self, name):
Application.setApplicationName(self, name)
mainWindowChanged = Signal()
示例10: QtApplication
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
#.........这里部分代码省略.........
if last_run_version < current_version:
self._just_updated_from_old_version = True
self._preferences.setValue("general/last_run_version", str(current_version))
self._preferences.writeToFile(self._preferences_filename)
# Preferences: recent files
self._preferences.addPreference("%s/recent_files" % self._app_name, "")
file_names = self._preferences.getValue("%s/recent_files" % self._app_name).split(";")
for file_name in file_names:
if not os.path.isfile(file_name):
continue
self._recent_files.append(QUrl.fromLocalFile(file_name))
if not self.getIsHeadLess():
# Initialize System tray icon and make it invisible because it is used only to show pop up messages
self._tray_icon = None
if self._tray_icon_name:
self._tray_icon = QIcon(Resources.getPath(Resources.Images, self._tray_icon_name))
self._tray_icon_widget = QSystemTrayIcon(self._tray_icon)
self._tray_icon_widget.setVisible(False)
def initializeEngine(self) -> None:
# TODO: Document native/qml import trickery
self._qml_engine = QQmlApplicationEngine(self)
self._qml_engine.setOutputWarningsToStandardError(False)
self._qml_engine.warnings.connect(self.__onQmlWarning)
for path in self._qml_import_paths:
self._qml_engine.addImportPath(path)
if not hasattr(sys, "frozen"):
self._qml_engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml"))
self._qml_engine.rootContext().setContextProperty("QT_VERSION_STR", QT_VERSION_STR)
self._qml_engine.rootContext().setContextProperty("screenScaleFactor", self._screenScaleFactor())
self.registerObjects(self._qml_engine)
Bindings.register()
self._qml_engine.load(self._main_qml)
self.engineCreatedSignal.emit()
recentFilesChanged = pyqtSignal()
@pyqtProperty("QVariantList", notify=recentFilesChanged)
def recentFiles(self) -> List[QUrl]:
return self._recent_files
def _onJobFinished(self, job: Job) -> None:
if isinstance(job, WriteFileJob):
if not job.getResult() or not job.getAddToRecentFiles():
# For a write file job, if it failed or it doesn't need to be added to the recent files list, we do not
# add it.
return
elif (not isinstance(job, ReadMeshJob) and not isinstance(job, ReadFileJob)) or not job.getResult():
return
if isinstance(job, (ReadMeshJob, ReadFileJob, WriteFileJob)):
self.addFileToRecentFiles(job.getFileName())
def addFileToRecentFiles(self, file_name: str) -> None:
file_path = QUrl.fromLocalFile(file_name)
if file_path in self._recent_files:
self._recent_files.remove(file_path)
示例11: QImage
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
fig.canvas.draw()
img = QImage(fig.canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
plot_area = (left*width, top*height, (1-left-right)*width, (1-top-bottom)*height)
return img, plot_area
if __name__ == '__main__':
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtWidgets import QApplication
import sys
app = QApplication(sys.argv)
qmlRegisterType(MeasurementData, "org.dynalyzer", 1, 0, "MeasurementData");
qmlRegisterType(DifferenceAnalyzer, "org.dynalyzer", 1, 0, "DifferenceAnalyzer");
qmlRegisterType(SnapshotView, "org.dynalyzer", 1, 0, "SnapshotView");
qmlRegisterType(DifferenceOverlayImage, "org.dynalyzer", 1, 0, "DifferenceOverlayImage");
qmlRegisterType(AnalogSignalPlot, "org.dynalyzer", 1, 0, "AnalogSignalPlot");
qmlRegisterType(Exporter, "org.dynalyzer", 1, 0, "Exporter");
engine = QQmlApplicationEngine()
if len(sys.argv) > 1:
path = QUrl(sys.argv[1])
engine.rootContext().setContextProperty("loadpath", path)
dir_path = os.path.dirname(__file__)
engine.load(os.path.join(dir_path, 'dynalyzer.qml'))
app.exec_()
示例12: QApplication
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
import sys
import os
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
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())
示例13: Test
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
window = engine.rootObjects()[0]
myObject = window.findChild(QObject, "myObject")
#loop.call_soon(myObject.funcRetClicked())
#myObject.funcRetClicked()
loop.run_in_executor(exec, myObject.funcRetClicked)
'''
with loop:
try:
test = Test()
service = Service(loop)
#loop.run_forever()
print('1')
# rootObjects 실행전 context를 선언/추가해줍니다.
ctx = engine.rootContext()
ctx.setContextProperty('Service', service)
#engine.load("main.qml")
engine.load("qml/tytrader.qml")
window = engine.rootObjects()[0]
#window.setContextProperty('Service', service)
loop.run_until_complete(test.printInterval())
loop.run_forever()
except:
pass
示例14: QApplication
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QUrl
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtWidgets import QApplication
from mvc_control.controller import Controller
import sys, signal
from mvc_view.FFDScene import FFDScene
from util.util import filter_for_speed
__author__ = 'ac'
# logging.basicConfig(level=logging.DEBUG)
app = QApplication(sys.argv)
signal.signal(signal.SIGINT, signal.SIG_DFL)
qmlRegisterType(FFDScene, 'FFD', 1, 0, "FFDScene")
# controller = Controller()
engine = QQmlApplicationEngine()
engine.load(QUrl(filter_for_speed(file_name='res/ui/main.qml')))
scene = engine.rootObjects()[0].findChild(FFDScene, 'scene')
controller = scene.controller # type: Controller
engine.rootContext().setContextProperty('controller', controller)
# print('main thread:', threading.current_thread().ident)
# app.exec()
sys.exit(app.exec())
示例15: PandasModel
# 需要导入模块: from PyQt5.QtQml import QQmlApplicationEngine [as 别名]
# 或者: from PyQt5.QtQml.QQmlApplicationEngine import rootContext [as 别名]
# pandas model test
import pandas as pd
df = pd.DataFrame(columns=('code', 'name'))
model = PandasModel(df)
print(model.headerData(0, QtCore.Qt.Horizontal, QtCore.Qt.DisplayRole))
print("%s %s" % (id(df), id(model._dataFrame())))
print("before append model length %s" %(len(model)))
df.loc[len(df)] = ['1', '1111']
df.loc[len(df)] = ['2', '2222']
df.loc[len(df)] = ['3', '3333']
df.loc[len(df)] = ['4', '4444']
index = model.index(0, 0)
# print("0 row 0 col data is %s" % (model.data(index)))
model.refresh()
print("after append model length %s" %(len(model)))
print("model list is \n %s " % model)
print("model roleNames %s" % model.roleNames())
# pandas model and qml operation test
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
myApp = QApplication(sys.argv)
qmlEngine = QQmlApplicationEngine()
rootContext = qmlEngine.rootContext()
rootContext.setContextProperty("cppModelCondition", model)
qmlEngine.load(QUrl('main.qml'))
sys.exit(myApp.exec_())
# input()