Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add buttons to a main window in Qt?

I'm new to qt programming so please don't mind if you find it a noob question. I've added a button to my main window but when I run the code the button is not displayed. Here's my code:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>

MainWindow::MainWindow(QWidget *parent)
{
QPushButton *train_button = new QPushButton(this);
train_button->setText(tr("something"));
train_button->move(600, 600);
train_button->show();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow  
{  
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H


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

What should I do?

like image 335
Learner Avatar asked Aug 01 '13 08:08

Learner


People also ask

How do I add widgets to the main window in Qt?

For QHBoxLayout or QVBoxLayout you can call addWidget() to put it on the end, or insertWidget() to put it in the middle somewhere. This is pretty much the same thing that happens when you call setupUi() in your main window constructor, where Qt reads the compiled ui description and instantiates the widgets to build it.

How do I create a window in Qt?

Create a new main window by opening the File menu and selecting the New Form... option, or by pressing Ctrl+N. Then, select the Main Window template. This template provides a main application window containing a menu bar and a toolbar by default -- these can be removed if they are not required.

What is main window in Qt?

Qt Main Window Framework A main window provides a framework for building an application's user interface. Qt has QMainWindow and its related classes for main window management. QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar.


1 Answers

In main window you should use central widget . You have two choices :

Set the button for central widget ( Not so good choice ) :

QPushButton *train_button = new QPushButton(this);
train_button->setText(tr("something"));
setCentralWidget(train_button);

Add a widget and add the button to that widget and set the widget for centralWidget :

QWidget * wdg = new QWidget(this);
QPushButton *train_button = new QPushButton(wdg);
train_button->setText(tr("something"));
setCentralWidget(wdg);

And surely you can use Layouts for your centralWidget:

QWidget * wdg = new QWidget(this);
QVBoxLayout *vlay = new QVBoxLayout(wdg);
QPushButton *btn1 = new QPushButton("btn1");
vlay->addWidget(btn1);
QPushButton *btn2 = new QPushButton("btn2");
vlay->addWidget(btn2);
QPushButton *btn3 = new QPushButton("btn3");
vlay->addWidget(btn3);
wdg->setLayout(vlay);
setCentralWidget(wdg);
like image 81
s4eed Avatar answered Oct 07 '22 11:10

s4eed