Files
scuc-qt-course/docs/teaching/examples/model_view/qt_model_view_basics.cpp
T
张宗平 1f66098277 Qt 示例窗口默认不再自动退出,仅离屏验证时自动退出
p03/ 生成产物与 docs/teaching/examples/ 手工示例里的 QTimer::singleShot
自动退出逻辑,从"始终 200ms 后退出"改为"仅当 QT_QPA_PLATFORM=offscreen
时才退出"。正常运行(有显示环境)窗口保持打开,需手动关闭;离屏自动化
验证(tools/run_qt.sh + QT_QPA_PLATFORM=offscreen)行为不变。

p03/ 改动来自重新生成 tools/gen_part3.py(AUTO_QUIT 常量加 qgetenv 判断),
未手改生成产物。QCoreApplication 控制台风格示例(qfile_basic 等)本就
执行完即退出,不受影响。
2026-07-02 16:14:49 +08:00

65 lines
2.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ============================================================================
// qt_model_view_basics —— 教学补充示例(非 wiki 生成,手工维护)
// 用途:方案书「C++方向 Day3」要求的 Model/View 模型视图架构,仓库 p03/ 原有
// wiki 抓取内容未覆盖这一点,故补一个最小示例。
// 配套文档:docs/teaching/examples/model_view/README.md
// 离屏验证:QT_QPA_PLATFORM=offscreen tools/run_qt.sh qt_model_view_basics(自动退出)
// ============================================================================
#include <QApplication>
#include <QWidget>
#include <QListView>
#include <QLabel>
#include <QVBoxLayout>
#include <QStandardItemModel>
#include <QTimer>
#include <QItemSelectionModel>
class ModelViewDemo : public QWidget {
Q_OBJECT
public:
explicit ModelViewDemo(QWidget* parent = nullptr) : QWidget(parent) {
// 模型:数据本身,与展示方式无关
auto* model = new QStandardItemModel(this);
model->appendRow(new QStandardItem(QStringLiteral("需求分析")));
model->appendRow(new QStandardItem(QStringLiteral("项目设计")));
model->appendRow(new QStandardItem(QStringLiteral("编码实现")));
model->appendRow(new QStandardItem(QStringLiteral("测试及回归")));
// 视图:只负责展示,不持有数据
auto* view = new QListView(this);
view->setModel(model);
auto* selectedLabel = new QLabel(QStringLiteral("当前选中:(无)"), this);
// 选中项变化 → 视图层通知 → 界面同步更新,模型和视图之间没有直接耦合
connect(view->selectionModel(), &QItemSelectionModel::currentChanged,
this, [selectedLabel](const QModelIndex& current, const QModelIndex&) {
if (current.isValid())
selectedLabel->setText(QStringLiteral("当前选中:%1").arg(current.data().toString()));
});
auto* layout = new QVBoxLayout(this);
layout->addWidget(view);
layout->addWidget(selectedLabel);
// 离屏自动化验证:选中第一行,触发一次 currentChanged
view->setCurrentIndex(model->index(0, 0));
}
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
ModelViewDemo w;
w.resize(280, 220);
w.show();
// 仅在离屏自动化验证时(QT_QPA_PLATFORM=offscreen200ms 后自动退出;
// 正常运行(有显示环境)窗口保持打开,不自动退出。
if (qgetenv("QT_QPA_PLATFORM") == "offscreen") {
QTimer::singleShot(200, &app, &QApplication::quit);
}
return app.exec();
}
#include "qt_model_view_basics.moc"