找回密码
 注册
搜索
查看: 1279|回复: 2

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

[复制链接]
发表于 2012-2-19 11:46:49 | 显示全部楼层 |阅读模式
作者:武汉华嵌[/COLOR]嵌入式培训学院 技术部



        通过对一个已经存在的Qt窗口部件进行子类化或者直接对QWidget进行子类化,就可以创建自定义窗口部件。以下直接对已有的Qt窗口部件进行子类化:

如下通过对QLineEdit进行子类化来实现自已需要的窗口部件,参考代码如下:

/**********************子类化的头文件*****************************/

#ifndefLINEEDIT_H

#defineLINEEDIT_H

#include<QLineEdit>

#include<QMouseEvent>

classLineEdit:publicQLineEdit

{

    Q_OBJECT

public:

    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_OBJECT

public:

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

}





以下是运行后的一个效果:









说明:以上只是个测试程序,没有实际应用价值,具体的应用还在于实际工作中的需求。



更多技术文章请进入华嵌[/COLOR]主页,转载请注明来源

------分隔线---------------------------- 上一篇:GUN C attribute的一些常用方法
下一篇:结构体的sizeof问题

华嵌网址: http://www.embedhq.org
 楼主| 发表于 2013-5-15 13:45:55 | 显示全部楼层
Linux设备驱动入门视频--武汉华嵌 冯勇老师
http://www.embedhq.org/plus/view.php?aid=1050
点评回复

使用道具 举报

 楼主| 发表于 2013-8-14 14:28:48 | 显示全部楼层
2013”清凉一夏“课程套餐大优惠!
http://www.embedhq.org/html/dongtai/2013/0609/3537.html
点评回复

使用道具 举报

高级模式
B Color Image Link Quote Code Smilies

本版积分规则

Archiver|手机版|小黑屋|52RD我爱研发网 ( 沪ICP备2022007804号-2 )

GMT+8, 2024-4-20 06:15 , Processed in 0.047381 second(s), 16 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表