Here is my code:

#include <QApplication> #include <QtWidgets> #include <QMenu> #include <QMenuBar> #include <main/MainMenu> int main(int argc, char *argv[]) { QApplication a(argc, argv); QMainWindow w; w.show(); MainMenu m(a); w.setMenuBar(&m); return a.exec(); } 

MainMenu is my class:

 class MainMenu{ public: MainMenu(QApplication app,QWidget *parent = Q_NULLPTR):QMenuBar(parent){ QMenu *pm_file = new QMenu("&Меню"); pm_file->addAction("&Выйти", &app, SLOT(quit()),Qt::ALT + Qt::Key_F4); this->addMenu(pm_file); } }; 

But when I try to compile, I get the error C2248: QApplication::QApplication: невозможно обратиться к private член, объявленному в классе "QApplication" in the MainMenu m(a); . That is, as I understand it, I cannot access the QApplication constructor, although I don’t need it here ... What could be the error? In general, I want to establish a connection in my class with the quit() slot, maybe there is another way for this?

  • 3
    You pass QApplication by value and want it to be copied (this is clearly not what you need). Follow the link - KoVadim

2 answers 2

QApplication can not be transmitted at all. It can be accessed from anywhere in your program using the qApp macro. It is defined in qcoreapplication.h :

 #define qApp QCoreApplication::instance() 

Then your code can be simplified as follows:

 #include <QCoreApplication> class MainMenu : public QMenuBar { Q_OBJECT public: explicit MainMenu(QWidget *parent = Q_NULLPTR) : QMenuBar(parent) { QMenu *pm_file = new QMenu("&Меню"); pm_file->addAction("&Выйти", qApp, SLOT(quit()), Qt::ALT + Qt::Key_F4); this->addMenu(pm_file); } }; 
  • thanks, it's really better. And why are you using explicit? Googled, but did not understand the specific benefits. - Nik
  • @Nik, the use of explicit most often is a matter of preference of each individual. Personally, I always use it, except in those cases where I know for sure that a constructor call with one argument will be absolutely transparent, convenient and visible without using the class name. - aleks.andr
  • Well, what is the general use of explicit? - Nik
  • one
    Here you have two classes: class A { public: A(int); }; class A { public: A(int); }; and class B { public: explicit B(int); }; class B { public: explicit B(int); }; . The compiler will skip these lines: A a1 = A(0); A a2 = 0; A a1 = A(0); A a2 = 0; , two equivalent objects will be constructed, and here: B b1 = B(0); B b2 = 0; B b1 = B(0); B b2 = 0; the compiler will say that when constructing a b2 object, implicitly calling the constructor fails. This is the effect of the explicit keyword. - aleks.andr
  • Oh, I see. Thank. - Nik

Your class MainMenu - probably should inherit from QMenuBar ?

 class MainMenu : public QMenuBar { Q_OBJECT // добавьте чтоб использовать слоты и сигналы public: // ... }; 

Well, as said in the comments, QApplication should be passed by reference.

  • Thank you, it works! - Nik