在Visual Studio中将自定义代码添加到Qt UIC生成的文件中

Adding custom code to Qt UIC generated file in Visual Studio

本文关键字:UIC Qt 文件 添加 Studio Visual 自定义 代码      更新时间:2023-10-16

我使用的是带有Qt插件的Microsoft Visual Studio。为了设计我的UI,我使用Qt Designer工具直接获取.UI文件,Qt UIC从该文件生成.h文件。

现在Qt设计器有一些缺点,因此我现在想添加我的自定义代码,以便进一步完善UI。可以将其直接添加到Qt UIC生成的.h文件中,但每次重新编译时,更改都会丢失。

我应该如何将自己的代码添加到Qt UIC生成的.h文件中?

正如您所观察到的,编辑生成的.h文件是个坏主意,该文件在重新编译时会被覆盖。添加抛光代码的一个地方是在组成生成的UI对象的类的构造函数中。例如:

// MainWindow.cpp
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
  ui.setupUi(this);
  // Additional polish      
  ui.textEdit->setText("Hello !");
}
// MainWindow.h
#include "ui_MainWindow.h" // the generated UI header
class MainWindow : public QMainWindow
{
  Q_OBJECT
public:
  MainWindow(QWidget *parent = 0);
private:  
  Ui::MainWindowClass ui;
};