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"); 

 

本文出自 “自由自我” 博客,请务必保留此出处http://hhuayuan.blog.51cto.com/1630327/969840

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值