Qt 5.10 Book Examples
main.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // main.cpp
3 // ======================================================================
4 // This file is a part of the book
5 // "Qt 5.10 Professional programming with C++"
6 // http://qt-book.com
7 // ======================================================================
8 // Copyright (c) 2017 by Max Schlee
9 // ======================================================================
10 
11 #include <QtWidgets>
12 #include <QJSEngine>
13 
14 // ----------------------------------------------------------------------
15 int main(int argc, char** argv)
16 {
17  QApplication app(argc, argv);
18  QWidget* pwgt = new QWidget;
19 
20  QLineEdit* ptxt = new QLineEdit;
21  ptxt->setObjectName("lineedit");
22 
23  QLabel* plbl1 = new QLabel("1");
24  plbl1->setObjectName("label1");
25 
26  QLabel* plbl2 = new QLabel("2");
27  plbl2->setObjectName("label2");
28 
29  QLabel* plbl3 = new QLabel("3");
30  plbl3->setObjectName("label3");
31 
32  QLabel* plbl4 = new QLabel("4");
33  plbl4->setObjectName("label4");
34 
35  //Layout Setup
36  QVBoxLayout* pvbxLayout = new QVBoxLayout;
37  pvbxLayout->addWidget(ptxt);
38  pvbxLayout->addWidget(plbl1);
39  pvbxLayout->addWidget(plbl2);
40  pvbxLayout->addWidget(plbl3);
41  pvbxLayout->addWidget(plbl4);
42  pwgt->setLayout(pvbxLayout);
43 
44  pwgt->show();
45 
46  //Script part
47  QJSEngine se;
48  QFile file(":/script.js");
49  if (file.open(QFile::ReadOnly)) {
50  QJSValue sw = se.newQObject(pwgt);
51 
52  se.globalObject().setProperty("wgt", sw);
53 
54  QList<QObject*> lst = pwgt->findChildren<QObject*>();
55  foreach(QObject* pobj, lst) {
56  sw = se.newQObject(pobj);
57  se.globalObject().setProperty(pobj->objectName(), sw);
58  }
59 
60  QJSValue result =
61  se.evaluate(QLatin1String(file.readAll()));
62  if (result.isError()) {
63  QMessageBox::critical(0,
64  "Evaluating error",
65  result.toString(),
66  QMessageBox::Yes
67  );
68  }
69  }
70  else {
71  QMessageBox::critical(0,
72  "File open error",
73  "Can not open the script file",
74  QMessageBox::Yes
75  );
76  }
77 
78  return app.exec();
79 }
int main(int argc, char **argv)
Definition: main.cpp:15