在Qt中启动程序时如何创建列表或对象?

How to create a list or an object when starting a program in Qt?

我刚开始使用 Qt,在阅读了一些示例并自己尝试了一些东西后,我有这个疑问。 我想在我的程序启动后立即创建一个列表。它将是空的,等待用户将项目(或对象)添加到此列表。 我做这个列表的主要例子是 this example.

现在,当启动 Qt 时,我在 "Forms" 文件夹中得到一个 .ui 文件,作为我的 mainwindow.cpp 我得到这个:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

检查示例,它没有关联的 .ui 文件。 更重要的是,让我想知道的是,这就是 Main Window:

的开始
MainWindow::MainWindow()
    : textEdit(new QTextEdit)
{
    setCentralWidget(textEdit);

    createActions();
    createStatusBar();
    createDockWindows();

    setWindowTitle(tr("Dock Widgets"));

    newLetter();
    setUnifiedTitleAndToolBarOnMac(true);
}

"createDockWindows()" 在此示例中完成了创建列表和内容的技巧。 我只想简单点:

QList <QString> GroceryShoppingList

现在,我应该把它放在哪里?像这样(在创建 UI 的方法内部):

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<QString> GroceryShoppingList;
}

MainWindow::~MainWindow()
{
    delete ui;
}

如果是的话,我用程序初始化的所有东西也应该放在里面吗?还是仅在这个特定示例中? 我的问题也基于 this question。我想知道这个函数的作用,因为它似乎是启动 MainWindow 的函数。 提前致谢。

奖金: 我如何 link 使用 QListView 程序创建的列表,该列表将显示在 ui 中?

您的对象列表是应用程序状态的一部分,因此不能仅在 MainWindow 构造函数的局部变量中定义此数据。

在您的简单示例中,它可以是您 MainWindow class 的成员:

在mainwindow.h中:

class MainWindow :.....
{
    ....
private:
    QList<QString> items;
    ....
}

但是,由于您想在 UI 中的视图中显示它,最常见的情况是数据保存在 model查看。请参阅 documentation of how Qt's model and view classes work. Short version is that responsibilities are split between the visual presentation (view) and the data (model). You can start with a simple QStringListModel 了解您的数据。

所以 QList<QString> items 你会

在mainwindow.h中:

class MainWindow :....
{
    ....
private:
    QStringListModel model;
    ....
}

在Designer或Qt Creator的Design模式中的UI文件中添加一个ListView(即打开mainwindow.ui文件),然后在mainwindow.cpp中:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // "ui" contains members for each UI element that you added in
    // design mode. Look what the name of the list view is that you
    // added there, and adapt accordingly
    ui->listView->setModel(&model);

    // if you want, you can initialize your model with some items:
    model.setStringList({"Bananas", "DVD Player"});
}