1

我正在尝试使用加载一个简单的 .ui 文件QUiLoader,但出现以下错误:

Designer: An error has occurred while reading the UI file at line 1, column 0: Premature end of document. 

我检查了 .ui 文件是否存在并打印了它的内容。
代码:

QApplication a(argc, argv);
MainWindow w;
w.show();

QUiLoader loader;
qDebug()<< QDir::currentPath();
QFile file("customwidget.ui");
qDebug() <<"File open: "<< file.open(QIODevice::ReadOnly| QIODevice::Text );
QWidget *formWidget;
qDebug() << file.readAll();
qDebug() <<"Loader: "<<(formWidget=loader.load(&file,&w));
file.close();
formWidget->show();

return a.exec();

输出:

"/home" 
File open:  true 
"<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>customWidget</class>
 <widget class="QWidget" name="customWidget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>200</width>
    <height>200</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>50</x>
     <y>60</y>
     <width>87</width>
     <height>27</height>
    </rect>
   </property>
   <property name="text">
    <string>PushButton</string>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>
" 
Designer: An error has occurred while reading the UI file at line 1, column 0: Premature end of document.
Loader:  QObject(0x0)

customwidget.ui 文件是使用 QTDesigner 生成的,位于/home.
为什么这不起作用?

4

1 回答 1

3

您已经阅读了整个文件,file.reset()在加载之前执行或只是不先阅读它:

QUiLoader loader;
qDebug()<< QDir::currentPath();
QFile file("customwidget.ui");
qDebug() <<"File open: "<< file.open(QIODevice::ReadOnly| QIODevice::Text );
QWidget *formWidget;
qDebug() << file.readAll();
file.reset();//or file.seek(0);
qDebug() <<"Loader: "<<(formWidget=loader.load(&file,&w));
file.close();
formWidget->show();
于 2013-09-06T09:19:37.917 回答