15

I would like to have a UI class in its own namespace, like ProjectName::MainWindow. Is there some convenient way how to achieve this in Qt Creator, please?

I can open the mainwindow.ui file and change the from "MainWindow" to "ProjectName::MainWindow", which compiles and works. But when I change something in the UI designer, the ui file gets generated again ... with the wrong class name.

eMko
  • 1,147
  • 9
  • 22
  • Are you talking about your own form class (it's by default in the default namespace, and its source is in the project) or about Qt-generated UI class (it's by default in `Ui` namespace and its declaration is stored in Qt-generated `ui_ClassName.h` file)? – Pavel Strakhov Jun 18 '13 at 08:29
  • My own. But the generated class should be also in propper namespace. Id est: ProjectName::MainWindow for my own and ProjectName::Ui for the generated one. – eMko Jun 18 '13 at 08:48

1 Answers1

23

When you create new Designer Form Class, specify class name with namespace, e.g. ProjectName::MainWindow. Qt Creator will automatically generate the following code.

MainWindow.h:

namespace ProjectName {
  namespace Ui {
    class MainWindow;
  }
  class MainWindow : public QWidget {
    Q_OBJECT    
  public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();    
  private:
    Ui::MainWindow *ui;
  };
} // namespace ProjectName

MainWindow.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>ProjectName::MainWindow</class>
 <widget class="QWidget" name="ProjectName::MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
 </widget>
 <resources/>
 <connections/>
</ui>

As you see, both MainWindow and Ui::MainWindow are now in ProjectName namespace.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • 1
    In addidtion, you don't even need to edit the XML document. You can simply edit the name property inside QtDesigner – RobbieE Jun 18 '13 at 09:51
  • 1
    The trick in the answer (Qt creator 2.7.0) does work only when adding a class, not when creating project - the wizard complains about non valid characters in class name. That mystified me... Editing the property in QtDesigner works too. Thank you very much! – eMko Jun 18 '13 at 10:02