QUiLoader 动态加载.ui

Dynamic dialogs are dialogs that are created from Qt Designer .ui files at run-time. Instead of converting the .ui file to C++ code using uic, we can load the file at run-time using the QUiLoader class:

QUiLoader uiLoader;
QFile file("sortdialog.ui");
QWidget *sortDialog = uiLoader.load(&file);
if (sortDialog) {
    ...
}

We can access the form's child widgets using QObject::findChild<T>():

QComboBox *primaryColumnCombo =
        sortDialog->findChild<QComboBox *>("primaryColumnCombo");
if (primaryColumnCombo) {
    ...
}

The findChild<T>() function is a template member function that returns the child object that matches the given name and type. Because of a compiler limitation, it is not available for MSVC 6. If you need to use the MSVC 6 compiler, call the qFindChild<T>() global function instead, which works in essentially the same way.

The QUiLoader class is located in a separate library. To use QUiLoader from a Qt application, we must add this line to the application's .pro file:

CONFIG += uitools

Dynamic dialogs make it possible to change the layout of a form without recompiling the application. They can also be used to create thin-client applications, where the executable merely has a front-end form built-in and all other forms are created as required.

总结:

准备工作:

1.适用情况:
动态加载UI文件是指,用 Qt Designer 通过拖拽的方式生产.ui 文件。不用 uic工具把.ui 文件变成等价的 c++代码,而是在程序运行过程中需要用到UI文件时,用 QUiLoader 加载.ui文件,达到相同目的。
 
2.适用环境:
1.UI文件是程序运行中途创建生成的,在同程序的其他地方调用,没法进行uic。
2.前端设计和功能实现相分离,前端设计人员和功能实现人员只要事前沟通好相关组件的名称等,就可以进行独立开发,能提高效率。
 
3.配置信息:
3.1若使用的.pro文件生成,需要在.pro文件中需要加上

  

TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
CONFIG += uitools//这个是要添加的代码行,以及需要添加的位置,关键是该行代码要在正确地方添加

# Input
HEADERS += DialogInstance.h
FORMS += gotocelldialog.ui
SOURCES += DialogInstance.cpp main.cpp



3.2如使用的是VS开发工具,需要添加QtUiToolsd.lib/QtUiTools.lib 库

PS:

1:添加类库

2:修改.pro文件,添加一行代码

3:添加头文件

4:添加对应的功能代码

5:编译、运行

THE END!

2012年12月28日

原文地址:https://www.cnblogs.com/xingchen/p/2836986.html