lyqym2012 发表于 2012-2-6 11:05

【武汉华嵌】Qt 自定义窗口部件(控件)的实现

作者:武汉华嵌 嵌入式培训中心技术部

      通过对一个已经存在的Qt窗口部件进行子类化或者直接对QWidget进行子类化,就可以创建自定义窗口部件。以下直接对已有的Qt窗口部件进行子类化:
如下通过对QLineEdit进行子类化来实现自已需要的窗口部件,参考代码如下:
/**********************子类化的头文件*****************************/
#ifndefLINEEDIT_H#defineLINEEDIT_H#include<QLineEdit>#include<QMouseEvent>classLineEdit:publicQLineEdit{    Q_OBJECTpublic:    explicitLineEdit(QObject*parent=0);
protected:    voidmouseDoubleClickEvent(QMouseEvent*);};#endif//LINEEDIT_H


/**********************子类化的源文件*****************************/
#include"lineedit.h"#include<QMessageBox>LineEdit::LineEdit(QObject*parent){}
//重新实现QLineEdit类的mouseDoubleClickEvent(QMouseEvent*event)//事件处理函数,从而达到双击LineEdit的时候会有一个消息框弹出
voidLineEdit::mouseDoubleClickEvent(QMouseEvent*event){    QMessageBox::information(this,tr("提示"),tr("你是对的!"));    event->ignore();}
以上是我自己实现的自己的一个LineEdit类,我双击这个LineEdit控件,就会弹出个消息框出来。
首先建一个工程,把上面的两个文件放到工程目录下面,然后来实现自己的代码:
/**********************主窗口的头文件*****************************/
#ifndefMYWIDGET_H#defineMYWIDGET_H#include<QWidget>#include"lineedit.h"classMyWidget:publicQWidget{    Q_OBJECTpublic:    explicitMyWidget(QWidget*parent=0);private:    LineEdit*lineedit;};#endif//MYWIDGET_H
/**********************主窗口的源文件*****************************/

#include"mywidget.h"#include<QHBoxLayout>MyWidget::MyWidget(QWidget*parent):    QWidget(parent){    lineedit=newLineEdit;    QHBoxLayout*hlayout=newQHBoxLayout;    hlayout->addWidget(lineedit);    setLayout(hlayout);}

/**********************显示主窗口的源文件*****************************/

#include<QApplication>#include<QTextCodec>#include"mywidget.h"intmain(intargc,char*argv[]){    QApplicationapp(argc,argv);    QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));    MyWidget*mywidget=newMyWidget;    mywidget->show();    returnapp.exec();}

以下是运行后的一个效果:
file:///C:/DOCUME~1/jack/LOCALS~1/Temp/msohtml1/01/clip_image001.jpg

说明:以上只是个测试程序,没有实际应用价值,具体的应用还在于实际工作中的需求。
更多技术**请进入华嵌主页,转载请注明来源 http:// www.embedhq.org
页: [1]
查看完整版本: 【武汉华嵌】Qt 自定义窗口部件(控件)的实现