Qt 5.10 Book Examples
PluginsWindow.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // PluginsWindow.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 "PluginsWindow.h"
13 
14 // ----------------------------------------------------------------------
15 PluginsWindow::PluginsWindow(QWidget* pwgt/*=0*/) : QMainWindow(pwgt)
16 {
17  m_plbl = new QLabel("this is an example text");
18  m_pmnuPlugins = new QMenu("&PluginOperations");
19 
20  loadPlugins();
21  setCentralWidget(m_plbl);
22  menuBar()->addMenu(m_pmnuPlugins);
23 }
24 
25 // ----------------------------------------------------------------------
27 {
28  QDir dir(QCoreApplication::applicationDirPath());
29 #ifdef Q_OS_OSX
30  dir.cdUp();
31 #endif
32  if (!dir.cd("plugins")) {
33  QMessageBox::critical(0, "", "plugins directory does not exist");
34  return;
35  }
36 
37  foreach (QString strFileName, dir.entryList(QDir::Files)) {
38  QPluginLoader loader(dir.absoluteFilePath(strFileName));
39  addToMenu(qobject_cast<QObject*>(loader.instance()));
40  }
41 }
42 
43 // ----------------------------------------------------------------------
44 void PluginsWindow::addToMenu(QObject* pobj)
45 {
46  if (!pobj) {
47  return;
48  }
49 
50  StringInterface* pI = qobject_cast<StringInterface*>(pobj);
51  if (pI) {
52  QStringList lstOperations = pI->operations();
53  foreach (QString str, lstOperations) {
54  QAction* pact = new QAction(str, pobj);
55  connect(pact, SIGNAL(triggered()),
56  this, SLOT(slotStringOperation())
57  );
58  m_pmnuPlugins->addAction(pact);
59  }
60  }
61 }
62 
63 // ----------------------------------------------------------------------
65 {
66  QAction* pact = qobject_cast<QAction*>(sender());
67 
68  StringInterface* pI = qobject_cast<StringInterface*>(pact->parent());
69 
70  m_plbl->setText(pI->operation(m_plbl->text(), pact->text()));
71 }
virtual QStringList operations() const =0
PluginsWindow(QWidget *pwgt=0)
void addToMenu(QObject *pobj)
void slotStringOperation()