13

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?

Learner
  • 499
  • 2
  • 8
  • 20
  • 1
    For the beggining it is better (from my point of view) to create application with QWidget as base class. QMainWindow provide a lot of extra functionality and you may learn it only when you will have some experience it Qt. – Dmitry Sazonov Aug 01 '13 at 08:59

1 Answers1

27

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);
Collin Price
  • 5,620
  • 3
  • 33
  • 35
s4eed
  • 7,173
  • 9
  • 67
  • 104
  • What if I want to add more buttons? Should I use the same widget or create a new widget for each buttons? – Learner Aug 01 '13 at 09:02
  • @user2595561 ~> No ! You just have one central widget! You should use Layouts. I'll update my answer very soon. – s4eed Aug 01 '13 at 09:03