PDA

View Full Version : Adding QPushButton to *.ui file by hand



s410i
23rd June 2009, 01:37
Hello!

I've made a new QMainWindow project by QtCreator.
Constructor looks like that:


MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{

ui->setupUi(this);
}


Is it possible to add for example QPushButton to the window generated form *.ui file just by writing it in constructor?

I've tried to write:

QPushButton button("button",ui->centralWidget);
button.move(10,10);
button.show();


QPushButton button("button",this);
button.move(10,10);
button.show();

but the button don't want to show.

Please help
s410i

vieraci
23rd June 2009, 02:10
You have to add the widget, assuming your centralWidget has a layout, this will add it to the last row:


QPushButton button = new QPushButton;
int rows = ui->centralWidget->rowCount();
ui->centralWidget->addWidget(button rows, 0, rows, 0, 0);


edit: centralWidget HAS to have a layout assigned to it first, then:

ui->centralWidget->layout->addWidget(button rows, 0, rows, 0, 0);

s410i
23rd June 2009, 14:01
I've tried just as you sad:

I've added QGridLayout to *.ui file and:

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);

QPushButton button("Click");

int rows = ui->gridLayout->rowCount();
int cols = ui->gridLayout->columnCount();

ui->gridLayout->addWidget(&button,rows,cols,0);
}

but when I compile the program there in no button.

Lykurg
23rd June 2009, 14:08
of course, because your button is deleted after the ctor! create it on the heap, not on the stack!