Clion中创建QT UI类为QMainWindow时, QDesiger无法拖控件解决方法

一直用QWidget类型的窗口,今天在Clion中创建Qt UI类,父类选择QMainWindow时,发现用QDesiger打开后,无法拖控件进去。baidu/google一番:
stackoverflow

这个问题回答中提到这是由于Clion生成的UI文件没有"central widget"这个东西,但是没好的解决方法,只能手动加。然后我用QCreator创建了一个,确实内容差异比较大,QCreator创建的还有QMenuBar、QToolBar、QStatusBar这些东西。

其实Clion生成Qt的UI类是通过文件和代码模板实现的,Settings>>Editor>>File and Code Templates找到Qt Designer Form将里面的内容改为如下:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
  <author/>
  <comment/>
  <exportmacro/>
  <class>${NAMESPACE_SPECIFIER}${NAME}</class>
  <widget class="${PARENT_CLASS}" name="${NAMESPACE_SPECIFIER}${NAME}">
    <property name="geometry">
      <rect>
        <x>0</x>
        <y>0</y>
        <width>400</width>
        <height>300</height>
      </rect>
    </property>
    <property name="windowTitle">
      <string>${NAME}</string>
    </property>
#if( ${PARENT_CLASS} == "QMainWindow" )
  <widget class="QWidget" name="centralWidget"/>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>25</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
    </widget>
    <widget class="QStatusBar" name="statusBar"/>
#end
  </widget>
#if( ${PARENT_CLASS} == "QMainWindow" )
  <layoutdefault spacing="6" margin="11"/>
#end
  <pixmapfunction/>
  <connections/>
</ui>

其实就是通过:

#if( ${PARENT_CLASS} == "QMainWindow" )
  xxxxx
  xxxxx
#end

这个Clion的模板的宏来实现。

posted @ 2022-06-11 23:48  thammer  阅读(380)  评论(0编辑  收藏  举报