如图,绿色的和红色的代表两个不同窗口QWidget,分别叫做widgetDown, widgetUp,widgetUp开始是隐藏的。
现在来实现一个需求:
1.当鼠标移到widgetDown时,显示widgetUp;
2.当鼠标从widgetDown和widgetUp移开时widgetUp隐藏。
也就是说,当鼠标移到红色区域时显示绿色区域,当鼠标从红色区域加上绿色区域这个大的区域离开时才隐藏绿色区域。
代码如下:
#ifndef WIDGETUP_H
#define WIDGETUP_H
#include <QWidget>
class WidgetUp : public QWidget
{
Q_OBJECT
public:
explicit WidgetUp(QWidget *parent = 0);
signals:
void sigShow();
void sigHide();
public slots:
protected:
void enterEvent(QEvent *);
void leaveEvent(QEvent *);
};
#endif // WIDGETUP_H
#include "widgetup.h"
#include <QtWidgets>
WidgetUp::WidgetUp(QWidget *parent) :
QWidget(parent)
{
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(QColor(0, 255, 0)));
this->setPalette(palette);
this->setAutoFillBackground(true);
this->setMouseTracking(true);
}
void WidgetUp::enterEvent(QEvent *event)
{
emit sigShow();
QWidget::enterEvent(event);
}
void WidgetUp::leaveEvent(QEvent *event)
{
emit sigHide();
QWidget::leaveEvent(event);
}
#ifndef WIDGETDOWN_H
#define WIDGETDOWN_H
#include <QWidget>
class WidgetDown : public QWidget
{
Q_OBJECT
public:
explicit WidgetDown(QWidget *parent = 0);
signals:
void sigShow();
void sigHide();
protected:
void enterEvent(QEvent *);
void leaveEvent(QEvent *);
};
#endif // WIDGETDOWN_H
#include "widgetdown.h"
#include <QtWidgets>
WidgetDown::WidgetDown(QWidget *parent) :
QWidget(parent)
{
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(QColor(255, 0, 0)));
this->setPalette(palette);
this->setAutoFillBackground(true);
this->setMouseTracking(true);
}
void WidgetDown::enterEvent(QEvent *event)
{
emit sigShow();
QWidget::enterEvent(event);
}
void WidgetDown::leaveEvent(QEvent *event)
{
emit sigHide();
QWidget::leaveEvent(event);
}
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public slots:
void slotShow();
void slotHide();
private:
Ui::Dialog *ui;
bool isWidgetDownShow_;
bool isWidgetUpShow_;
};
#endif // DIALOG_H
#include "dialog.h"
#include "ui_dialog.h"
#include <QtWidgets>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
connect(ui->widgetDown, SIGNAL(sigShow()), this, SLOT(slotShow()));
connect(ui->widgetDown, SIGNAL(sigHide()), this, SLOT(slotHide()));
connect(ui->widgetUp, SIGNAL(sigShow()), this, SLOT(slotShow()));
connect(ui->widgetUp, SIGNAL(sigHide()), this, SLOT(slotHide()));
ui->widgetUp->hide();
isWidgetDownShow_ = true;
isWidgetUpShow_ = false;
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::slotShow()
{
if (this->sender() == ui->widgetDown) {
isWidgetDownShow_ = true;
} else if (this->sender() == ui->widgetUp) {
isWidgetUpShow_ = true;
}
ui->widgetUp->show();
}
void Dialog::slotHide()
{
if (this->sender() == ui->widgetDown) {
isWidgetDownShow_ = false;
} else if (this->sender() == ui->widgetUp) {
isWidgetUpShow_ = false;
}
if (!isWidgetDownShow_ && !isWidgetUpShow_) {
ui->widgetUp->hide();
}
}