【发布时间】:2015-12-15 03:11:09
【问题描述】:
我有一组小弹出窗口小部件,它们出现在不同的地方,但每次只有一个。对于简单的功能,new-to-show 和 delete-to-hide 是可以的,并且工作正常,但是当他们开始处理自己的数据时,我可以看到内存泄漏。
所以因为我只需要每一种,我想我会在父构造函数中预先创建所有它们,并根据需要显示和隐藏它们。据我所知,这应该可以,但是 popup->show() 没有显示。此示例所基于的复杂应用程序表明弹出窗口确实存在于正确的位置,并且可以与用户交互...除了它是不可见的。
这是显示的惰性版本:
#ifndef MAIN_H
#define MAIN_H
#include <QtWidgets>
class Popup : public QLabel
{
Q_OBJECT
public:
explicit Popup(int x, int y, int width, int height, QWidget* parent = 0);
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget* parent = 0);
~MainWindow() {}
void mousePressEvent(QMouseEvent* ev);
private:
Popup* popup;
};
#endif // MAIN_H
/***************
*** main.cpp ***
***************/
#include "main.h"
#include <QApplication>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
{
popup = 0;
QWidget* cWidget = new QWidget(this);
cWidget->setStyleSheet("background-color: lightgray");
setCentralWidget(cWidget);
showMaximized();
}
void MainWindow::mousePressEvent(QMouseEvent* ev)
{
if(popup != 0)
{
if(!popup->geometry().contains(ev->x(), ev->y()))
{
delete popup;
popup = 0;
}
}
else
{
popup = new Popup(ev->x(), ev->y(), 100, 100, this);
popup->show();
}
ev->accept();
}
Popup::Popup(int x, int y, int width, int height, QWidget* parent) :
QLabel(parent)
{
setStyleSheet("background-color: black");
setGeometry(
x - (width / 2), // Left
y - (height / 2), // Top
width , // Width
height // Height
);
}
这是未显示的预创建版本:
#ifndef MAIN_H
#define MAIN_H
#include <QtWidgets>
class Popup : public QLabel
{
Q_OBJECT
public:
explicit Popup(QWidget* parent = 0);
void setup(int x, int y, int width, int height);
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget* parent = 0);
~MainWindow() {}
void mousePressEvent(QMouseEvent* ev);
private:
Popup* popup;
};
#endif // MAIN_H
/***************
*** main.cpp ***
***************/
#include "main.h"
#include <QApplication>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
{
popup = new Popup(this);
QWidget* cWidget = new QWidget(this);
cWidget->setStyleSheet("background-color: lightgray");
setCentralWidget(cWidget);
showMaximized();
}
void MainWindow::mousePressEvent(QMouseEvent* ev)
{
if(popup->isVisible())
{
if(!popup->geometry().contains(ev->x(), ev->y()))
{
popup->hide();
}
}
else
{
popup->setup(ev->x(), ev->y(), 100, 100);
popup->show();
}
ev->accept();
}
Popup::Popup(QWidget* parent) :
QLabel(parent)
{
setStyleSheet("background-color: black");
}
void Popup::setup(int x, int y, int width, int height)
{
setGeometry(
x - (width / 2), // Left
y - (height / 2), // Top
width , // Width
height // Height
);
}
我错过了什么?
【问题讨论】:
标签: c++ qt user-interface qwidget