如果ui设计中有提升过小部件,则无法直接使用QUiLoader加载。完成加载需要重新实现UiLoader::createWidget()函数。
virtual?QWidget * QUiLoader::createWidget(const QString & className, QWidget * parent = Q_NULLPTR, const QString & name = QString())
下面是类的实现,其中“MyTextEdit?”作为自定义的提升小部件类
//自定义小部件
class MyTextEdit : public QTextEdit
{
Q_OBJECT
public:
MyTextEdit(QWidget * parent = nullptr) : MyTextEdit(parent){}
};
//自定义QUiLoader派生类
#include "QUiLoader"
class CustomClassUiLoader : public QUiLoader
{
Q_OBJECT
public:
CustomClassUiLoader(QObject * parent = Q_NULLPTR);
//重写createWidget()类
QWidget * createWidget(const QString & className, QWidget * parent = Q_NULLPTR,
const QString & name = QString())
{
if(className == "MyTextEdit"){
MyTextEdit* widget = new MyTextEdit(parent);
widget->setObjectName(name);
widget->setEdit(info.textEdit );
return widget;
}
return QUiLoader::createWidget(className, parent, name);
}
};
加载ui,
QUiLoader uiL;
QFile file("C:\\Users\\Administrator\\Desktop\\untitled2\\form.ui");
file.open(QFile::ReadOnly);
QWidget * widget = uiL.load(&file, ui->textEdit);
QVBoxLayout * layout = new QVBoxLayout;
layout->addWidget(widget);
layout->setContentsMargins(0, 0, 0, 0);
file.close();
ui->frame->setLayout(layout);