0
QPushButton* m_button = new QPushButton();

Whenever i try to create a QPushButton like this, it appears to be created in a new separate window. However, I want the Button to be created within the Mainwindow but I don't know how to do this (without using the Qt Designer).

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
Schulp
  • 73
  • 6
  • 2
    It depends on what do you actually want to achieve. The simplest way is just adding a button to the main window like: `setCentralWidget(m_button);`, assuming that you call that function from main window class. – vahancho Feb 25 '20 at 12:28
  • 3
    QPushButton* m_button = new QPushButton(this); – Konstantin T. Feb 25 '20 at 12:41
  • The setCentralWidget Method worked out fine. Thanks a lot, vahancho! – Schulp Feb 26 '20 at 10:22

1 Answers1

0

You need to set the MainWindow as a parent

try this:

QPushButton* m_button = new QPushButton(this)
Louis Kröger
  • 344
  • 3
  • 10
  • When I try your Code, I receive the error: "no matching constructor for initialization of 'QPushButton' – Schulp Feb 26 '20 at 10:19
  • `this` must refer to a QWidget. Since QMainWindow is derived by QWidget, it should work – Louis Kröger Feb 26 '20 at 11:58
  • My code looks like this: MainwindowInstance{ public: MainwindowInstance(); MainWindow w; } When I try to create a QPushButton in my MainWindow from another class by the following code, the Button is always opened in another window. MainwindowInstance* instance = new MainwindowInstance(); QPushButton *m_button = new QPushButton(&instance->w); Any further advice? – Schulp Feb 27 '20 at 11:18