简体   繁体   English

为什么我不能在Qt中访问其他表单的小部件?

[英]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): 因此,我在主窗口的Qt C ++表单中(在按钮单击槽下方)具有以下代码:

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

I want to be able to access a webview control I placed on the new form. 我希望能够访问放置在新表单上的Webview控件。 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. 经过一番研究,我发现最好使用nf-> ui来访问所有newform控件。 So I went into newform.h and changed the *ui variable to public: 所以我进入了newform.h并将* ui变量更改为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. 但是,每当我尝试调用nf-> ui时,都不会出现下拉菜单,并且仍然无法访问我的Web视图。 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. 出现这些错误是因为您将需要访问ui类定义以调用成员函数并访问其包含的小部件,而这是对类内部造成依赖的一个不好的解决方案。

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: 因此,请勿尝试直接访问ui (或其他成员),它们是私有的,建议保持这种状态,而应将所需的功能编码到newform类中,并使该类完成所需的工作从mainwindow类触发,例如:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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