Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c++ - 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?

question from:https://stackoverflow.com/questions/65939450/accessing-a-widget-created-in-a-ui-file-from-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...