Search code examples
c++qtsignals-slotsqt-designer

Accessing a widget created in a .ui file from code


I'm using Qt5.12.10 inside Visual Studio using Qt VS Tools.

I added a QTextEdit widget inside Qt Designer as shown in the image below. Text

I also connected a button to a custom slot named "slot2()" and I want to edit the text inside text box based on what the user typed inside textBox at the time of pressing the "submit" button. The code I used for this task is as below:

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication1.h"

class QtWidgetsApplication1 : public QMainWindow
{
    Q_OBJECT

public:
    QtWidgetsApplication1(QWidget *parent = Q_NULLPTR);

public slots:
    void slot1() {
        exit(1);
    };

    void slot2() {
        if (ui.textEdit.toPlainText() == "hello")
            ui.textEdit.setText("hello there!");
        else
            ui->centralWidget->textEdit.setText("sorry, I don't understand :(");
    }

private:
    Ui::QtWidgetsApplication1Class ui;
};

This code gives me a compilation error saying that "textEdit" is not a member of Ui::QtWidgetsApplication1Class. I have also tried changing the code for slot2() as such:

    void slot2() {
        if (ui.centralWidget->textEdit.toPlainText() == "hello")
            ui.centralWidget->textEdit.setText("hello there!");
        else
            ui.centralWidget->textEdit.setText("sorry, I don't understand :(");
    }

but that did not solve the issue as well, saying that "textEdit is not a member of 'QWidget'". What should I do?


Solution

  • In Qt UI, layout are not use in "compoment code path", you don't have to write centralWidget

    If you try to use QtCreator, you will have a ton of auto-completion that will help you a lot (at least for the begining)

    try to write

    ui.textEdit->setText("HelloWorld");