Qt筆記(8)自定義控件 三 讓使用了自定義控件的工程運行起來

新建一個工程test,在窗體裏放入上兩章自定義的控件HLabel,編譯,會出現以下提示:

  1. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\..\test\mainwindow.cpp:2: In file included from ..\test\mainwindow.cpp:2: 
  2. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:23: error: hlabel.h: No such file or directory 
  3. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\..\test\mainwindow.cpp:2: In file included from ..\test\mainwindow.cpp:2: 
  4. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:31: error: ISO C++ forbids declaration of 'HLabel' with no type 
  5. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:31: error: expected ';' before '*' token 
  6. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:-1: In member function 'void Ui_MainWindow::setupUi(QMainWindow*)'
  7. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:43: error: 'hLabel' was not declared in this scope 
  8. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:43: error: expected type-specifier before 'HLabel' 
  9. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:43: error: expected ';' before 'HLabel' 

很容易看出,是因爲缺少了控件的相關頭文件及源文件,把自定義控件的hlabel.h, hlabel.cpp放入到test工程目錄,再編譯,還是會出錯:

  1. D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\.\ui_mainwindow.h:43: error: undefined reference to `HLabel::HLabel(QWidget*)' 
  2. :-1: error: collect2: ld returned 1 exit status 

關鍵的來了:

把自定義控件的hlabel.pri文件也放到test工程目錄,並在test.pro文件里加入一名:

  1. include(hlabel.pri) 

再編譯,順利運行!

-------------------------------------------------------------------------

爲了更有成就感,可以爲上兩章提到的HLabel控件加入一個clicked()信號:

hlabel.h文件

  1. #ifndef HLABEL_H 
  2. #define HLABEL_H 
  3.  
  4. #include <QtGui/QLabel> 
  5.  
  6. class HLabel : public QLabel 
  7.     Q_OBJECT 
  8. protected
  9.     void mousePressEvent(QMouseEvent * ev);//這是手工加入的 
  10. public
  11.     HLabel(QWidget *parent = 0); 
  12. signals: 
  13.     void clicked();//這是手工加入的 
  14. }; 
  15.  
  16. #endif 

hlabel.cpp文件

  1. #include "hlabel.h" 
  2.  
  3. HLabel::HLabel(QWidget *parent) : 
  4.     QLabel(parent) 
  5. //以下是手工加入的代碼 
  6. void HLabel::mousePressEvent(QMouseEvent * ev) 
  7.     this->setCursor(Qt::PointingHandCursor); 
  8.     emit this->clicked(); 

1、 重新編譯自定義控件,並按照上兩章介紹的方法加入到QtDesigner

2、再按照本文上半部分的方法把相關文件放入到test工程目錄,重新打開test工程,在自定義控件上右鍵 -> go to slots 就會發現多了一個clicked()信號,在信號處理隨便寫點代碼(如下),運行就會看到效果了!

  1. void MainWindow::on_hLabel_clicked() 
  2.     ui->hLabel->setText("ok"); 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章