0

i am trying to use QShortcut, and declare in in widget constructor like:

   QShortcut  *keyCtrlL;
    keyCtrlL = new QShortcut(this);
    keyCtrlL->setKey(Qt::CTRL + Qt::Key_L);
    connect(keyCtrlL, &QShortcut::activated, this, &MyPage::loadB);

I am not sure it will work, even it compile fine, as variable is local in the constructor. So i am trying to declare it as a private variable for the whole class MyPage,

and getting compilation errors:

error: cannot initialize a parameter of type 'QWidget *' with an rvalue of type 'MyPage *'
    ui->setupUi(this);
                ^~~~
./qt/forms/ui_mypage.h:69:27: note: passing argument to parameter 'MyPage' here
    void setupUi(QWidget *MyPage)
                          ^
qt/mypage.cpp:153:20: error: no matching constructor for initialization of 'QShortcut'
    keyCtrlL = new QShortcut(this);

Even MyPage is inherited from QWidget. Why this error happens, how can i fix it?

user453575457
  • 464
  • 6
  • 21

1 Answers1

0

You may be missing #include of MyPage header... Without it, it cannot upcast MyPage* to QWidget*. Check if it is not missing.

  • To be presice I forgot #include in MyPage.h header file, after adding this it worked fine, thanks – user453575457 Apr 16 '22 at 09:34
  • Well, if you keep `QShortcut` by pointer in the `MyPage` class definition (which I bet you do), then you should only forward declare `QShortcut` in `MyPage.h` and `#include` it in `MyPage.cpp`. This is actually the correct way. Including it in the header is not a good practice. – HiFile.app - best file manager Apr 16 '22 at 09:39
  • MyPage.h - what i called header file, sorry is i messed a terminology. – user453575457 Apr 16 '22 at 09:41
  • Not sure if I understand the clarification. `MyPage.h` is a header file. But you should only use `class QShortcut;` (i.e. forward declaration) in that header. And you should only use`#include ` in `MyPage.cpp`. – HiFile.app - best file manager Apr 16 '22 at 09:44
  • I am also not so good in c++ and may be misunderstanding how it works, ^_^ , Initially i added in `MyPage.h` only one string - `QShortcut *keyCtrlL;` and it did not compile as described in a question. After adding `#include ` in `MyPage.h` all compiled successfully. – user453575457 Apr 16 '22 at 09:49
  • That is what I am talking about. This works but it is not good solution (for multiple reasons). `#include ` should not be in the header and it should go to `MyPage.cpp`. And to make it compile, you should add `class QShortcut;` (this is so called forward declaration of a class) to the header instead of the include. Read about forward declarations here https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c – HiFile.app - best file manager Apr 16 '22 at 09:55