温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

QT自定义控件消息实现

发布时间:2020-08-19 12:18:02 来源:网络 阅读:621 作者:WZM3558862 栏目:开发技术
通过对一个已经存在的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();

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI