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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With