-1

I just created a Qt default project with a Qt designer form.

The class MainWindow is declared in a mainwindow.h and then included in mainwindows.cpp.

Why is it done this way ? Why not a declaration of this form directly in mainwindows.cpp ?:

class MainWindow
{
    ...
}

What is the proper way to add my code ? For example, a button that trigger a method.

bokan
  • 3,601
  • 2
  • 23
  • 38
  • 3
    I think you should learn a bit more about C++ first. Than try Qt and other libraries. – denys Sep 05 '12 at 16:49
  • @denys The fact that it is a beginner question is not a reason for down-voting it. The question is clear, the answer given by codingthewheel is clear too. Using of separate header is a good practice, it's not mandatory for the language. If you look at books, examples declare methods and the source using one file. With the help of codingthewheel I can now make my sample application work. – bokan Sep 05 '12 at 16:57
  • Sorry @bokan I've not explained enough my action. Your question is about basic C++ principles. Not About Qt. That is good question with proper answer on it: http://stackoverflow.com/q/1106149/658346 – denys Sep 05 '12 at 18:43
  • "Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post...". Just look for .h files in a search engine and you'd encounter pages and pages on the subject as the first result. – Luca Carlon Sep 05 '12 at 18:44

2 Answers2

2

In C++ you typically put class definitions into header files (.h), and method implementations in source files (.cpp). That allows clients of the class to use the class without having to see the implementation of each function. That also means that when adding a method, you'll typically have to make two changes: add the method to the class definition (in the header) and then add the method's implementation to the .CPP file.

In header file:

class MainWindow
{
    void SomeMethod();
};

In source file:

void MainWindow::SomeMethod()
{
    // Your code here.
}
0

The definition of MainWindow class is needed in another file, where an instance of it is constructed in the main function and then shown. That's why the class needs to be defined in a header file.

There are a number of ways to add your own code: for the button you described you could create in entirely in the QtCreator UI, or you could create it "programmatically" in the MainWindow constructor.

eq-
  • 9,986
  • 36
  • 38