Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. QGuiApplication app(argc, argv);
  2. QQmlEngine* engine = new QQmlEngine;
  3. QQmlComponent component(engine, QUrl(QStringLiteral("qrc:/main.qml")));
  4.  
  5. // ignoring error checking (make sure component is ready, compiles w/o errors, etc)
  6.  
  7. QObject* object = component.create();
  8. app.exec();
  9.  
  10. QByteArray SimpleQml()
  11. {
  12. return QByteArray("import QtQuick 2.7; Text {") +
  13. "text: "Hello, World!"}";
  14. }
  15.  
  16. QByteArray TextExampleQml()
  17. {
  18. return QByteArray("import QtQuick 2.7; Simple{") +
  19. "color: "Red"}";
  20. }
  21.  
  22. QObject* createObjectFromMemory(QByteArray qmlData, QQmlEngine* engine, QQmlComponent* componentOut)
  23. {
  24. componentOut = new QQmlComponent(engine);
  25.  
  26. // note this line: load data from memory (no URL specified)
  27. componentOut->setData(qmlData, QUrl());
  28.  
  29. if (componentOut->status() != QQmlComponent::Status::Ready)
  30. {
  31. qDebug() << "Component status is not ready";
  32.  
  33. foreach(QQmlError err, componentOut->errors())
  34. {
  35. qDebug() << "Description: " << err.description();
  36. qDebug() << err.toString();
  37. }
  38.  
  39. qDebug() << componentOut->errorString();
  40.  
  41. return nullptr;
  42. }
  43. else
  44. {
  45. return component.create();
  46. }
  47. }
  48.  
  49. int main(int argc, char* argv[])
  50. {
  51. QGuiApplication app(argc, argv);
  52.  
  53. QQuickView view;
  54. QQmlComponent* component = nullptr;
  55.  
  56. // works great: shows a small window with the text "Hello, World!"
  57. QObject* object = createObjectFromMemory(SimpleQml(), view.engine(), component);
  58.  
  59. // problem: Simple is not a type
  60. // QObject* object = createObjectFromMemory(TextExampleQml(), view.engine(), component);
  61.  
  62. // setContent() is marked as an internal Qt method (but it's public)
  63. // see source for qmlscene for why I'm using it here
  64. view.setContent(QUrl(), component, object);
  65.  
  66. view.show();
  67.  
  68. app.exec();
  69.  
  70. // don't forget to clean up (if you're not doing a demo snippet of code)
  71. //delete object;
  72. //delete component;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement