【问题标题】:QUiLoader errơr when loading .ui file加载 .ui 文件时 QUiLoader errơr
【发布时间】:2019-12-10 05:31:23
【问题描述】:

我正在尝试使用 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
为什么这不起作用?

【问题讨论】:

    标签: qt qt-designer


    【解决方案1】:

    您已经阅读了整个文件,在加载之前执行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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 2017-04-14
      相关资源
      最近更新 更多