Please nominate your Qt Champions for 2021!

Newbie question about widgets

  • Hi all,
    Using the designer in Qt creator, I have created a widget with a QPushButton object on it called "pushButton", but I have two problems:

    1. How to access the objects pushButton
    2. How to add another object to the widget from the source code

    My code is the following

    #include <QApplication>
    #include "widget.h"

    int main(int argc, char *argv[])
    QApplication a(argc, argv);
    Widget w;;

    return a.exec&#40;&#41;;


    #ifndef WIDGET_H
    #define WIDGET_H

    #include <QWidget>
    #include <QLabel>

    namespace Ui {
    class Widget;

    class Widget : public QLabel

    explicit Widget(QWidget *parent = 0);
    QLabel * label;

    Ui::Widget *ui;

    #endif // WIDGET_H

    There is another file widget.ui that is the form with the QPushButton, and the file

    #include "widget.h"
    #include "ui_widget.h"

    Widget::Widget(QWidget *parent) : QLabel (parent), ui(new Ui::Widget){
    // label =new QLabel("aaaaaaaaaa");

    delete ui;

    where I have the two problems.

    1)In the first comment, I try to add a new label

    2)In the second comment, I try to change the text on the pushButton

    Neither of them seem to be the right approach.
    Any help would be much appreciated!

  • bq. In the first comment, I try to add a new label

    Label will be created by qmake generated code. Don't worry about it.

    bq. In the second comment, I try to change the text on the pushButton

    Do it after setupUI call.

  • thanks for the prompt reply. I

    I changed it to this; now I'm able to change the pushButton, but I still don't know how to add/display the label in the widget.

    Widget::Widget(QWidget *parent) : QLabel (parent), ui(new Ui::Widget){
    label =new QLabel("aaaaaaaaaa");


  • Open the ui file in qtcreator, drop a qlabel in the ui file.
    In the cpp file, @ui->label->setText("aaaaa");@
    You can add QLabel from code too, but I feel you might want to play around with adding items in widget.ui file at the moment. Also after compilation and linking, open the generated file ui_widget.h and see what all code is being generated for you.

  • I got the idea of adding items with widget.ui, and I also have been able to create create dialogues from code.
    However, I'd like to know how to add widgets from code into a form created using graphic tools.

Log in to reply