Qt C++初始化列表混乱
我正在开始使用 Qt(以及 C++,在较小程度上),并且我想确保在继续之前我完全理解基本代码。据我所知,初始化列表中的第一个元素用于选择非默认继承的构造函数。
但是 ui(new Ui::TestAppMain) 的目的是什么?在我看来,这将是一个无限循环,因为 ui 在构造函数中被设置为 TestAppMain 的新实例,但事实并非如此。
namespace Ui {
class TestAppMain;
}
class TestAppMain : public QMainWindow{
public:
explicit TestAppMain(QWidget *parent = 0);
private:
Ui::TestAppMain *ui;
};
TestAppMain::TestAppMain(QWidget *parent): QMainWindow(parent), ui(new Ui::TestAppMain){
ui->setupUi(this);
}
I'm getting started with Qt (and C++, to a lesser extent), and I wanted to be sure I fully understood the base code before continuing on. I understand that the first element in the initialization list is being used to select a non-default inherited constructor.
What is the purpose of ui(new Ui::TestAppMain), though? It seems to me like it would be an infinite loop, since ui is being set to a new instance of TestAppMain in the constructor, but that's not the case.
namespace Ui {
class TestAppMain;
}
class TestAppMain : public QMainWindow{
public:
explicit TestAppMain(QWidget *parent = 0);
private:
Ui::TestAppMain *ui;
};
TestAppMain::TestAppMain(QWidget *parent): QMainWindow(parent), ui(new Ui::TestAppMain){
ui->setupUi(this);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ui::TestAppMain
与您的TestAppMain
类不同。它是 Qt 从您在 Qt Creator 中创建的 .ui 文件生成的另一个 C++ 类。为了避免混淆和命名冲突,Qt 将所有此类生成的类放在Ui
命名空间中。在您自己的类
MyWidget
中包含Ui::MyWidget
实例是标准的 Qt 实践。在您的情况下,实例化Ui::TestAppMain
后,您可以根据您指定的布局使用该对象初始化主窗口(由TestAppMain
类表示)在 TestAppMain.ui 中。这是通过调用 ui->setupUi(this) 来完成的。Ui::TestAppMain
is not the same as yourTestAppMain
class. It's another C++ class that is generated by Qt from the .ui file you've created in Qt Creator. To avoid confusion and naming conflicts, Qt puts all such generated classes in theUi
namespace.It is a standard Qt practice to include an instance of
Ui::MyWidget
in your own classMyWidget
. In your case, after you instantiateUi::TestAppMain
, you use that object to initialize your main window (represented by yourTestAppMain
class) according to the layout you've specified in TestAppMain.ui. That is done by callingui->setupUi(this)
.