Qt使用教程之使用Qt Quick UI表单(三)

来源:互联网 发布:淘宝网店改名字 编辑:程序博客网 时间:2024/05/19 00:08

<Qt Enterprise最新版下载>

实现主视图的应用逻辑

新项目向导将模板代码添加到main.qml文件中来创建菜单项和按钮。通过删除旧的代码和添加新的代码修改模板代码。您可以从UI表单中删除按钮,同时还需要从main.qml中删除相应的代码(或应用程序不能被创建)。

指定主视图的大小

该向导将创建一个ApplicationWindow类型和一个MainForm类型来指定应用程序主视图。输入应用程序的名称作为标题属性的值。当按钮被点击时,通过删除旧的行所调用函数来清理MainForm代码:

1
2
3
4
5
MainForm {
anchors.fill: parent
button1.onClicked: messageDialog.show(qsTr("Button 1 pressed"))
button2.onClicked: messageDialog.show(qsTr("Button 2 pressed"))
}

从ApplicationWindow类型中删除width和height属性,并在MainForm类型中使用一个布局类型来设置主视图的最小值和首选大小。想要使用布局,可导入QtQuick Layouts:

1
import QtQuick.Layouts 1.1

然后指定MainForm的以下属性:

1
2
3
4
5
6
MainForm {
anchors.fill: parent
Layout.minimumWidth: 800
Layout.minimumHeight: 480
Layout.preferredWidth: 768
Layout.preferredHeight: 480
创建表视图模型

在表视图中使用列表模式显示客户数据。因为列表模式是从几个不同的.qml文件中读取的,通过在CustomerModelSingleton.qml中定义一个singleton类型并在main.cpp注册来访问它。这样,就不必依赖QML context作用域规则来访问列表模型。

1.在Projects视图中,右键单击qml.qrc并选择Add New > Qt > QML File (Qt Quick 2)来创建CustomerModelSingleton.qml文件并将其添加到项目中。

2.从CustomerModelSingleton.qml中复制实现。

3.在main.qml中添加以下代码到MainForm来访问列表模型:

1
2
3
tableView1.model: CustomerModel
 
Component.onCompleted: CustomerModel.selection = tableView1.selection

4.在main.cpp文件中注册singleton类型,包含Qt QML模块并在初始化函数中调用qmlRegisterSingletonType()函数:

1
2
3
4
5
6
7
8
9
...
#include <qtqml>
 
intmain(intargc, char*argv[])
{
QApplication app(argc, argv);
 
QUrl resourceUrl(QStringLiteral("qrc:/CustomerModelSingleton.qml"));
qmlRegisterSingletonType(resourceUrl, "my.customermodel.singleton", 1, 0, "CustomerModel");</qtqml>

5.在main.qml中想要使用已经注册的singleton类型,您必须导入singleton类型:

1
import my.customermodel.singleton 1.0
有兴趣的朋友可以点击查看更多有关Qt的文章>>
0 0
原创粉丝点击