[Qt5] 使用Qt设计器绘制主窗口

实践代码: 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:vcqtuildMainWindowDebugMainWindow.exe : fatal error LNK1120: 3 个无法解析的外部命令

Step4:解决问题  Qt下bin的moc生成moc_mainwindow.cpp

为了解决上面的错误,需要用到Qtin目录下的一个程序moc,通过它生成moc_mainwindow.cpp

如:

Step5:再编译

再通过cmake一下, 在VS加载工程配置后, 再编译, 就可以了

原文地址:https://www.cnblogs.com/dilex/p/10952394.html