# Qt Lesson 2 一些基礎元件的教學 --- ## Qt resource 將你的檔案改成相對路徑! ![](https://i.imgur.com/ldPEMqQ.jpg =60%x) ---- 當我們要匯入檔案,可能會這麼做(先別管QPixmap,之後會有教學影片) ![](https://i.imgur.com/QOG7qmn.png) ---- ![](https://memes.tw/user-template/b81fa7d87499a972b9cd55cbdd3cf716.png =60%x) 修但幾勒,並不是所有人的電腦都是這個路徑! ---- ### 使用相對路徑 1. 新增Qt Resource File 2. Add prefix 3. 在專案資料夾下新增一個放圖片的資料夾 4. Add file --- ## QLabel 標籤可以放文字、圖片,甚至也可以當按鈕來用? ---- ### 如何使用 ```cpp= /*宣告標頭檔*/ #include<QLabel> /*用指標new一個新的QLabel*/ QLabel *label = new QLabel(this); /*設定位置、大小*/ label->setGeometry(50, 50, 50, 50); ``` 這樣應該就會出現在mainWindow上了 ---- ### 一些常用method https://doc.qt.io/qt-5/qlabel.html ---- #### 設定文字 ```cpp= label->setText("你好啊"); ``` #### 取得文字 ```cpp= qDebug() << label->Text(); ``` ---- #### 設定圖片 ```cpp= QPixmap pix(":/剛剛用的相對路徑"); label->setPixmap(pix.scaled( label->width(), label->height() , Qt::KeepAspectRatio)); ``` :::info 這裡取得label的長寬後,將圖片pix進行縮放 ::: --- ## QPushButton 最基礎的按鈕,發揮你最大的創意 ![](https://imgflip.com/s/meme/Blank-Nut-Button.jpg) ---- ### 如何使用 與QLabel類似,用上面的方法應該就可以了 ---- ### 點擊事件 還記得上一個教學教的Signals & Slots嗎? ![](https://i.imgur.com/uUoC9rS.png) ---- 大概會需要做這些事 * connect你要的signal跟slot * 宣告並完成這個slot function ---- 在你要讓它產生作用的時候寫這一行 ```cpp= connect(button, SIGNAL(clicked(bool)), this, SLOT(buttonClick())); ``` 在class裡面宣告 ```cpp= private slots: void buttonClick(); ``` 完成它的內容 ```cpp= void MainWindow::buttonClick() { // 看你要幹嘛 } ``` --- ## 練習 —— suck meme generator ![](https://i.imgur.com/vyb6Z7O.png =40%x) 右上方輸入文字,按下按鈕後,更改下方標籤文字 (後面有提示以及詳解) ---- #### 提示一 一共有四個元件 1. QPushButton 2. QLabel(放圖片的) 3. QLabel(更改文字的) 4. QLineEdit(功能能沒有講到,試著網路上查資料) ---- #### 提示二 設定圖片以及文字後,讓按鈕Connect Signal與Slot 要注意的點有: 1. setFont可以改字形跟字體大小 2. 物件需要宣告在mainwindow.h,之後才能再拿出來用 3. 需要在mainwindow.h宣告一個slot,並在mainwindow.cpp完成它的內容 ---- #### 提示三 利用text() method取得QLineEdit的文字輸入 ---- ### 解答 https://github.com/erickuo5124/suck-meme-generator ###### tags: `醒獅團`
{"breaks":true,"metaMigratedAt":"2023-06-15T06:04:47.941Z","metaMigratedFrom":"Content","title":"Qt Lesson 2","contributors":"[{\"id\":\"35cea605-1599-4b9b-a7f8-610e7a3b3107\",\"add\":2274,\"del\":314}]"}
    472 views