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

I have a game with Qt that is basically looking to rewrite an old java application for symbian, and I have a bit confused.

First of all, I must explain that C ++ is not my kung fu, and this may be the cause of the problem.

What I'm trying to do is add a simple QPushButton to the vertical layout in the main window, which was built into the qt constructor at runtime.

My sample code looks 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 get are the following:

/home/graham/myFirstApp/mainwindow.cpp:22: error: conversion from "QPushButton" to the non-scalar type "QPushButton" requested

/home/graham/myFirstApp/mainwindow.cpp:27: Error: there is no corresponding function to call in "QVBoxLayout :: addWidget (QPushButton &)

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

Now I know that the first error has something to do with pointers, but I don’t know that if someone can clear my confusion and provide sample code that will be great.

Hello

Graham.

+4
source share
2 answers

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

 QPushButton* button = new QPushButton(); button->setText(text); ui->myLayout->addWidget(button); 
+6
source

QPushButton button = new QPushButton();

A pointer to a QPushButton is not a QPushButton. This is what your compiler pops up and what your problem is.

+2
source

Source: https://habr.com/ru/post/1336867/


All Articles