實踐代碼: git clone https://github.com/dilexliu/learn_qt5.git
Step1: Qt設計器繪制窗口

保存會得到一個文件: mainwindow.ui
另外還需要把mainwindow.ui 的代碼保存出來,操作:在Qt設計器中的菜單欄【窗體】->【查看代碼】,把其中的代碼保存為 ui_mainwindow.h

Step2: 手動添加代碼
mainwindow.h
#pragma once
#include "ui_mainwindow.h"
class CMainWindow : public QMainWindow, public Ui_MainWindow
{
Q_OBJECT
public:
CMainWindow(QWidget* = 0);
};
mainwindow.cpp
#include <QtGui>
#include "mainwindow.h"
CMainWindow::CMainWindow(QWidget* parent) : QMainWindow(parent)
{
this->setupUi(this);
this->show();
}
main.cpp
#include <QtGui>
#include "mainwindow.h"
CMainWindow::CMainWindow(QWidget* parent) : QMainWindow(parent)
{
this->setupUi(this);
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(MainWindow)
# Find the QtWidgets library
find_package(Qt5Widgets)
link_libraries(Qt5::Widgets)
FILE(GLOB SC_FILES "*.cpp" "*.h")
add_executable(${PROJECT_NAME} WIN32 ${SC_FILES})
Step3:CMake創建VS工程后編譯
會出現一些錯誤:
1>mainwindow.obj : error LNK2001: 無法解析的外部符號 "public: virtual struct QMetaObject const * __thiscall CMainWindow::metaObject(void)const " (?metaObject@CMainWindow@@UBEPBUQMetaObject@@XZ) 1>mainwindow.obj : error LNK2001: 無法解析的外部符號 "public: virtual void * __thiscall CMainWindow::qt_metacast(char const *)" (?qt_metacast@CMainWindow@@UAEPAXPBD@Z) 1>mainwindow.obj : error LNK2001: 無法解析的外部符號 "public: virtual int __thiscall CMainWindow::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@CMainWindow@@UAEHW4Call@QMetaObject@@HPAPAX@Z) 1>E:\vc\qt\build\MainWindow\Debug\MainWindow.exe : fatal error LNK1120: 3 個無法解析的外部命令
Step4:解決問題 Qt下bin的moc生成moc_mainwindow.cpp
為了解決上面的錯誤,需要用到Qt\bin目錄下的一個程序moc,通過它生成moc_mainwindow.cpp
如:

Step5:再編譯
再通過cmake一下, 在VS加載工程配置后, 再編譯, 就可以了

