1. 程式人生 > >Qt Creator4.6.2&Visual Studio 2017新建Qt專案並編譯顯示Hello World

Qt Creator4.6.2&Visual Studio 2017新建Qt專案並編譯顯示Hello World

關於Qt CReator & Visual Studio 2017的安裝不在本文介紹之中

文章目錄

Qt Creator4.6.2新建專案工程

1、建立工程

  1. 左上角 檔案->新建檔案或專案,如下圖所示,選擇Qt Widgets Application(Widget用於可視視窗顯示,Console用於在命令列視窗顯示,Qt Quick於後續介紹)
    選擇Qt Widgets Application
  2. 單擊choose下一步,Qt會在指定的路徑(F:\QTFile\PersonProgramFiles)建立untitled1這個檔案,這個也是專案工程目錄
    指定專案存放路徑
  3. 點選下一步,預設選擇Desktop Qt 5.11.1 MinGW 32bit選擇Kit Selection
  4. 點選下一步,選擇要建立專案的基本類資訊,預設選擇QMainWindow,關於基類三個(QMainWindow、QWidget和QDialog)詳細具體區別可以參考網上資料
    專案基於MainWindow類建立
  5. 點選完成,開啟左邊欄目mainwindow.cpp檔案,如下圖所示
    Qt專案介面
  6. 直接編譯執行如下圖所示,生成介面中有三個部分,依次是選單欄–主介面–狀態列,(工具欄沒有直觀表現出來)
    在這裡插入圖片描述

2、編寫Hello World

  1. 在主Widget中顯示 Hello World!,程式碼如下
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //在主Widget中(centralWidget)新建一個Label標籤用於顯示字串
QLabel *label = new QLabel(ui->centralWidget); //為這個新建的Label標籤定義一個名字,“labelShow” label->setObjectName(QStringLiteral("labelShow")); //label裡面顯示Hello World! label->setText(QStringLiteral("Hello World!")); } MainWindow::~MainWindow() { delete ui; }
  1. 編譯執行如下,Hello World!顯示在介面的左上角,接下來將其顯示在居中位置
    顯示Hello World!
  2. 參考如下程式碼,新增標頭檔案#include <QHBoxLayout>,此程式碼將Label居中顯示
#include <QLabel>
#include <QHBoxLayout>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QLabel *label = new QLabel(ui->centralWidget);//在主Widget中(centralWidget)新建一個Label標籤用於顯示字串
    label->setObjectName(QStringLiteral("labelShow"));//為這個新建的Label標籤定義一個名字,“labelShow”
    label->setText(QStringLiteral("Hello World!"));//label裡面顯示Hello World!

    QHBoxLayout *horizontalLayout = new QHBoxLayout();//新增一個水平佈局
    horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));//為這個水平佈局定義一個名字,"horizontalLayout"
    horizontalLayout->addStretch();//在label左邊新增伸縮佈局
    horizontalLayout->addWidget(label);//佈局中新增label
    horizontalLayout->addStretch();//在label右邊新增伸縮佈局
    horizontalLayout->setContentsMargins(10, 10, 10, 10);

    ui->centralWidget->setLayout(horizontalLayout);//將佈局新增到主Widget中
}
  1. 編譯執行如下圖所示,改變視窗大小可以發現Hello World!依舊在介面中間顯示
    居中顯示Hello World!

Visual Studio 2017新建專案工程

1、建立工程

2、編寫Hello World