简体   繁体   中英

Why can't I access my other form's widgets in Qt?

So, I have the following code in my main window's Qt C++ form (under a button click slot):

    newform *nf = new newform(this);
    nf->show();

I want to be able to access a webview control I placed on the new form. After some research, I figured that calling nf->ui would be my best bet in order to gain access to all of newform's controls. So I went into newform.h and changed the *ui variable to public:

#ifndef NEWFORM_H
#define NEWFORM_H

#include <QMainWindow>

namespace Ui {
class newform;
}

class newform : public QMainWindow
{
    Q_OBJECT

public:
    explicit newform(QWidget *parent = 0);
    ~newform();

    Ui::newform *ui;

};

#endif // NEWFORM_H

Yet, whenever I try calling nf->ui, a dropdown menu doesn't appear and I still can't get access to my webview. When I type my code anyway and try to run, I get:

error: invalid use of incomplete type 'class Ui::newform'
error: forward declaration of 'class Ui::newform'

What's going on? Am I doing something wrong? Any help is appreciated. Thanks in advance.

The errors are because you will need access to the ui class definition to call member functions and access the widgets it contains and that is a bad solution to cause such a dependency on that class internals.

So, don't try to access the ui (or the other members) directly, those are private and it's recommended that they stay that way, instead code the functionality you need into the newform class and make that class do the work that you need to be triggered from mainwindow class, something like:

class newform : public QMainWindow
{
    Q_OBJECT
public:
    explicit newform(QWidget *parent = 0);
    ~newform();

//code a member function (or a slot if you need a signal to trigger it) 
//example:    
    void loadUrlInWebView(QUrl url);
private:
    Ui::newform *ui; //leave this private - it's not a good solution to make it public
};

//and in the .cpp file
void newform::loadUrlInWebView(Qurl url)
{
//you can access the internal widgets here
    ui->WEBVIEWNAME->load(url);
//do whatever you need here and you call this public function from other form
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM