学习自《Foundations of Qt Development》
针对一个widget设置多个不同的
tooltips
,当鼠标移动到不同的区域能得到不同的提示。
自定义
tooltip
事件: 因为没有现成的
tooltipEvent
,所以需要自己来处理鼠标在不同位置的情况,使用
QWidget::event()
调用
QWidget::paintEvent()
来绘画四个矩形。
细节如下:
#ifndef TIPZONE_H
#define
#include <QWidget>
#include <QPainter>
#include <QRect>
#include <QEvent>
class tipZone : public QWidget
{
Q_OBJECT
QRect redRec, blueRec, blackRec, whiteRec;
int width, height;
public:
explicit tipZone(QWidget *parent = 0);
signals:
public slots:
protected:
bool event(QEvent * e);
void paintEvent(QPaintEvent * event);
};
#endif
#include "tipzone.h"
#include <QHelpEvent>
tipZone::tipZone(QWidget *parent) :
QWidget(parent)
{
QRect geo = this->geometry();
width = geo.width(); // don't use this->width
height = geo.height(); // don't use this->height
redRec = QRect(0,0,width/2,height/2);
blueRec = QRect(width/2,0,width/2,height/2);
blackRec = QRect(0,height/2,width/2,height/2);
whiteRec = QRect(width/2,height/2,width/2,height/2);
}
bool tipZone::event(QEvent *e)
{
if(e->type() == QEvent::ToolTip){
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);
if(redRec.contains(helpEvent->pos()))
setToolTip(QObject::tr("red"));
else if(blueRec.contains(helpEvent->pos()))
setToolTip(QObject::tr("blue"));
else if(blackRec.contains(helpEvent->pos()))
setToolTip(QObject::tr("black"));
else if(whiteRec.contains(helpEvent->pos()))
setToolTip(QObject::tr("white"));
}
return QWidget::event(e);
}
void tipZone::paintEvent(QPaintEvent *event)
{
QPainter *painter = new QPainter(this);
painter->fillRect(redRec,Qt::red);
painter->fillRect(blueRec,Qt::blue);
painter->fillRect(blackRec,Qt::black);
painter->fillRect(whiteRec,Qt::white);
}