所以,我在主窗口的 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/