Qt - 加载.ui文件时出现QUiLoader错误

时间:2013-09-06 09:00:12

标签: qt

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

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 为什么这不起作用?

1 个答案:

答案 0 :(得分: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();