新闻  |   论坛  |   博客  |   在线研讨会
Qt 自定义窗口部件(控件)的实现
华嵌 | 2013-08-09 14:33:47    阅读:854   发布文章

作者:武汉华嵌技术部

 

        通过对一个已经存在的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();

}

 

 

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

 

 

 

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

 

更多技术文章请进入华嵌主页,转载请注明来源 http:// www.embedhq.org

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

参与讨论
登录后参与讨论
推荐文章
最近访客