Home > Net >  PushButton is opened in different window
PushButton is opened in different window

Time:06-18

i am new at QT

i created a window and i want to add a button on this window but the button is opened in different window.

How to add this button to default window

Here is my code;

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QPushButton"
#include "QDesktopWidget"
#include <iostream>

using namespace std;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QPushButton* buton1 = new QPushButton("Hello");
    buton1 -> setGeometry(QRect(QPoint(100,100),QSize(200,50)));
    connect(buton1, &QPushButton::released, this, &MainWindow::buton_fonk);
    buton1 -> show();
    ui->setupUi(this);
}

void MainWindow::buton_fonk()
{
    cout << "here" << endl;
}

MainWindow::~MainWindow()
{
    delete ui;
}

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setWindowState(Qt::WindowMaximized);

    w.showFullScreen();

    return a.exec();
}

CodePudding user response:

You need to make QPushButton a child of the main window for it to be rendered inside the main window, otherwise QPushButton will be an independent widget.

Usually all Qt Widgets accept a pointer to parent widget, QPushButton also accept a pointer to parent widtet.

QPushButton(const QString &text, QWidget *parent = nullptr)

To make QPushButton child of MainWindow, add this as second parameter to QPushButotn constructor.

QPushButton* buton1 = new QPushButton("Hello", this); // Make MainWindow as parent of QPushButton

Ideally you should create a layout and add all your widgets to this layout and then set the central widget of MainWindow to this layout.

QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(button1);
// Add anyother widget to your layout
this->setCentralWidget(mainLayout);

Hope this helps.

  •  Tags:  
  • c qt
  • Related