- 主窗口头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class ColorWgt;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void showColorWgt(bool checked);
void hideColorWgt();
private:
Ui::Widget *ui;
ColorWgt *m_pColorWgt;
};
#endif
- 主窗口cpp文件
#include "widget.h"
#include "ui_widget.h"
#include "colorwgt.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_pColorWgt = new ColorWgt(this);
ui->pushButton->setCheckable(true);
connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(showColorWgt(bool)));
connect(m_pColorWgt, SIGNAL(hideColorWgt()), this, SLOT(hideColorWgt()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::showColorWgt(bool checked)
{
if(checked)
{
m_pColorWgt->show();
}
else
{
m_pColorWgt->hide();
}
}
void Widget::hideColorWgt()
{
if(m_pColorWgt != NULL && ui->pushButton->isChecked() && !ui->pushButton->geometry().contains(this->mapFromGlobal(QCursor::pos())))
{
ui->pushButton->setChecked(false);
}
}
- 弹窗头文件
#ifndef COLORWGT_H
#define COLORWGT_H
#include <QWidget>
namespace Ui {
class ColorWgt;
}
class ColorWgt : public QWidget
{
Q_OBJECT
public:
explicit ColorWgt(QWidget *parent = 0);
~ColorWgt();
protected:
bool event(QEvent *event);
signals:
void hideColorWgt();
private:
Ui::ColorWgt *ui;
};
#endif
- 弹窗cpp文件
#include "colorwgt.h"
#include "ui_colorwgt.h"
ColorWgt::ColorWgt(QWidget *parent) :
QWidget(parent),
ui(new Ui::ColorWgt)
{
ui->setupUi(this);
this->setWindowFlags(Qt::Popup);
}
ColorWgt::~ColorWgt()
{
delete ui;
}
bool ColorWgt::event(QEvent *event)
{
if(event->type() == QEvent::HideToParent)
{
emit hideColorWgt();
}
return QWidget::event(event);
}
参考博文链接点此处