新建一個工程test,在窗體裏放入上兩章自定義的控件HLabel,編譯,會出現以下提示:
- 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:
- 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
- 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:
- 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
- D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:31: error: expected ';' before '*' token
- 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*)':
- 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
- D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\ui_mainwindow.h:43: error: expected type-specifier before 'HLabel'
- 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工程目錄,再編譯,還是會出錯:
- D:\Test\test-build-desktop-Qt_4_8_2__4_8_2__Debug\.\ui_mainwindow.h:43: error: undefined reference to `HLabel::HLabel(QWidget*)'
- :-1: error: collect2: ld returned 1 exit status
關鍵的來了:
把自定義控件的hlabel.pri文件也放到test工程目錄,並在test.pro文件里加入一名:
- include(hlabel.pri)
再編譯,順利運行!
-------------------------------------------------------------------------
爲了更有成就感,可以爲上兩章提到的HLabel控件加入一個clicked()信號:
hlabel.h文件
- #ifndef HLABEL_H
- #define HLABEL_H
- #include <QtGui/QLabel>
- class HLabel : public QLabel
- {
- Q_OBJECT
- protected:
- void mousePressEvent(QMouseEvent * ev);//這是手工加入的
- public:
- HLabel(QWidget *parent = 0);
- signals:
- void clicked();//這是手工加入的
- };
- #endif
hlabel.cpp文件
- #include "hlabel.h"
- HLabel::HLabel(QWidget *parent) :
- QLabel(parent)
- {
- }
- //以下是手工加入的代碼
- void HLabel::mousePressEvent(QMouseEvent * ev)
- {
- this->setCursor(Qt::PointingHandCursor);
- emit this->clicked();
- }
1、 重新編譯自定義控件,並按照上兩章介紹的方法加入到QtDesigner
2、再按照本文上半部分的方法把相關文件放入到test工程目錄,重新打開test工程,在自定義控件上右鍵 -> go to slots 就會發現多了一個clicked()信號,在信號處理隨便寫點代碼(如下),運行就會看到效果了!
- void MainWindow::on_hLabel_clicked()
- {
- ui->hLabel->setText("ok");
- }