简体   繁体   中英

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

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.

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);

QPushButton button = new QPushButton();

A pointer to QPushButton is not a QPushButton. That's what your compiler's bitching about and that's your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM