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

标签 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->ui 时,下拉菜单不会出现,我仍然无法访问我的 webview。当我输入代码并尝试运行时,我得到:

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

这是怎么回事?难道我做错了什么?任何帮助表示赞赏。提前致谢。

最佳答案

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

因此,不要尝试直接访问 ui(或其他成员),它们是私有(private)的,建议它们保持这种状态,而是将您需要的功能编码到 newform 类并使该类完成您需要从主窗口类触发的工作,例如:

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
}

关于c++ - 为什么我不能在 Qt 中访问其他表单的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181746/

相关文章:

c++ - 具有 unicode 属性支持的 Qt/C++ 正则表达式库

xcode - 如何像 XCode 一样向 Mac 应用程序添加左/下/右 Pane ?

c++ - get_input_port 方法位于 drake 的什么位置?

c++ - 接受者拒绝只为 -O0 构建打开套接字

qt - 如何流畅地显示QProgressBar?

c++ - 如何使用 QString 引用 objectName?

c++ - 如何在 Linux 中链接 QT 和 OpenCV

c++ - PHP7 和 IIS8 HTTP 错误 500.0 - FastCGI 进程意外退出

java - 在 java 中创建一个独立的 gui 控制台,扩展基于提示的应用程序

java - 如何让GUI java变得漂亮?