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

拈花ヽ惹草 提交于 2019-12-10 16:12:42

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4787275/how-to-add-a-widget-qpushbutton-for-example-dynamically-to-a-layout-built-in-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!