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

时间:2013-06-19 01:55:53

标签: c++ qt user-interface qt-creator

所以,我在主窗口的Qt C ++表单中有以下代码(在按钮点击插槽下):

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

我希望能够访问我放在新表单上的webview控件。经过一些研究,我认为调用nf-> ui是我最好的选择,以获得对所有newform控件的访问权限。所以我进入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

然而,每当我尝试拨打nf-&gt; ui时,都不会出现下拉菜单,我仍然无法访问我的网页视图。当我输入我的代码并尝试运行时,我得到:

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

发生了什么事?难道我做错了什么?任何帮助表示赞赏。提前谢谢。

1 个答案:

答案 0 :(得分:2)

错误是因为你需要访问ui类定义来调用成员函数并访问它包含的小部件,这是一个错误的解决方案,会导致对类内部的这种依赖。

所以,不要试图直接访问 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
}
相关问题