Qt C ++ 5.11 custom procedure to customize the Linux ---- Example Label

The machine environment linux mint Qt5.11

  • Demand: a custom label, so that the label can display the coordinate values ​​of the mouse while clicking
  • Step one, create a new project QWidget

  • Convenience, are set as follows

  • Step two, a new class Label
Custom controls, is nothing more than added on the basis of official controls on new Qt slot (popular point is the response function of the event), so be sure to inherit a base class, then what is the specific name of the base class? How do I find? We might as well drag an official control to view its associated properties

 

 

 Made the right attribute information

 

 

  •  Add a new project C ++ class I for the time being defined as mylabel, so that the label inheriting the base class QLabel, according to the needs, click on the tab will display the mouse, x, y-axis coordinate information, which is bound to the appropriate relationship to select which widgets ( widget, it means a new era of elegance controls) in response to an event, which would be, put the mouse control name, such as at QLabel, press F1

 

 

 

查看Reimplemented protected functions

 

 

MousePressEvent feel very much Zhen Xin, and thus, in the header file plus the relevant function declaration (protected part)

#ifndef MYLABEL_H
#define MYLABEL_H

#include <QWidget>
#include<QLabel>
class mylabel : public QLabel
{
    Q_OBJECT
public:
    explicit mylabel(QWidget *parent = nullptr);
protected:
    void mousePressEvent(QMouseEvent *ev);
    void mouseReleaseEvent(QMouseEvent *ev);
    void mouseMoveEvent(QMouseEvent *ev);
signals:

public slots:
};

#endif // MYLABEL_H
  • 接下来,要写下详尽的功能,切换到类的实现文件mylabel.cpp
#include "mylabel.h"
#include<QLabel>
#include<QMouseEvent>//必须添加控件头文件,否则程序会让你好看
#include<QString>//必须添加控件头文件,否则程序会让你好看
mylabel::mylabel(QWidget *parent) : QLabel(parent)
{

}
void mylabel::mousePressEvent(QMouseEvent *ev)
{
    int x=ev->x();//把鼠标放在QMouseEvent处,按下F1可以发现该类的公共函数x(),y()是用来获取x,y轴坐标的
    int y=ev->y();
    QString str=QString("x轴坐标:%1, y轴坐标:%2").arg(x).arg(y);
    this->setText(str);
}
void mylabel::mouseReleaseEvent(QMouseEvent *ev)
{

}
void mylabel::mouseMoveEvent(QMouseEvent *ev)
{

}

以为这样就万事大吉了?......I‘m deeply sorry,点击ui文件

选中label微件,鼠标右键 点击promote to......

 

在promoted class name处添加你写好的 类名----mylabel,添加成功后,下次打开,如上图所示

接下来就是选中label组件,然后右键选择promoted to 选择拟定义好的类mylabel,最后运行结果如下,你的label控件最好拖的跟窗体一样大,这样才由更好的测试体验

 

Guess you like

Origin www.cnblogs.com/saintdingspage/p/12155489.html