ISTB
ISTB

Reputation: 1817

Organization of the QT Code

I am writing an application of middle size. I will have many gui components and many classes. However, it is difficult for me to organize the code, to separate the logic, ... For example, let say that I press one button that creates an object of a class and perform a computation on that object. After exiting the slot function of the button, this local object is destroyed. What if I need it in another function later? Defining everything as a global variable in the header file is not a good thing for me. So I was thinking of a static class that contains somehow pointers to all the objects I will need later. Does anybody has a better idea?

Upvotes: 1

Views: 1096

Answers (1)

pmr
pmr

Reputation: 59811

How to manage objects inside an application is always a tricky question. Qt goes down a very object-oriented route and uses reference semantics implemented through pointer for nearly everything. To prevent tedious manual memory management Qt organizes everything into Object Trees. This is augmented by Qt own object model that adds some dynamic capabilities.

If you want to go down that route, stick to everything Qt provides. It is much more similar to Java than the usual C++ approach and might be more comforting for beginners and maybe suits your application domain. It tightly ties your code to Qt and will make it hard to separate from it.

One other approach means to simply forgo all Qt stuff and work out the core logic of your application. Develop it in pure C++ and than have a thin layer that ties this logic into your Qt application through signals and slots. In such an approach you would opt to use more value-semantics.

For your concrete example of creating an algorithm and keeping it around. The Qt approach:

class MyAlgo : public QObject {
  Q_OBJECT
public:
    MyAlgo(QObject* o) : QObject(o) { }

    virtual compute();
};

// use it in a mainwindow slot

void MainWindow::executeAlgorithm(const QString& name) {
   MyAlgo* algo = this->findChild<MyAlgo*>(name);
   if(!algo) {
     // not found, create
     algo = new MyAlgo(this); // make mainwindow the parent of this algo
     algo->setName(name); // QObject name property
   }

   algo->compute();
}

Upvotes: 2

Related Questions