Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a widget (QPushButton for example) dynamically to a layout built in designer

Tags:

c++

qt

qt-creator

I'm having a play around with Qt mainly looking to rewrite an old java app for symbian and I have got my self a bit confused.

I should first of all explain that C++ is not my kung-fu, and that may be the cause of the problem.

What I am trying to do is add a simple QPushButton to a Vertical Layout in a main window which has been built in qt designer at run time.

My example code is something like this...

QPushButton button = new QPushButton();

QString text("Testing Buttons");

button.setText(text);

//How do we add children to this widget??

ui->myLayout->addWidget(button);

The errors I am getting are as follows...

/home/graham/myFirstApp/mainwindow.cpp:22: error: conversion from ‘QPushButton*’ to non-scalar type ‘QPushButton’ requested

/home/graham/myFirstApp/mainwindow.cpp:27: error: no matching function for call to ‘QVBoxLayout::addWidget(QPushButton&)’

/home/graham/myFirstApp/../qtsdk-2010.05/qt/include/QtGui/qboxlayout.h:85: candidates are: void QBoxLayout::addWidget(QWidget*, int, Qt::Alignment)

Now I know the first error has something to do with pointers but I don't know what, if anyone is able to clear up my confusion and provide example code that would be great.

Regards

Graham.

like image 633
Graham Avatar asked Feb 26 '23 07:02

Graham


1 Answers

This is a merely C++ problem, you need to use asterisk to declare the button as pointer when you use new-operator.

QPushButton* button = new QPushButton();
button->setText(text);
ui->myLayout->addWidget(button);
like image 171
Tonttu Avatar answered Apr 25 '23 08:04

Tonttu