【发布时间】:2017-05-08 08:20:08
【问题描述】:
目前我正在使用QLabels 在我正在开发的 GUI 应用程序上显示图像。它的工作原理是当用户单击“添加图形”按钮时,会创建一个新的动态标签并出现在窗口上。当用户双击标签时,文件对话框打开,用户可以选择要显示的图像,效果很好。
应用程序的要求是在应用程序关闭时恢复图像,以便用户不必再次输入图像,我正在努力想出一个解决方案。我正在尝试使用QBuffers 和QSettings 来恢复图像,但是有一行代码只会使应用程序崩溃。
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
readSettings();
ui->setupUi(this);
// Set up the window size
this->setWindowTitle(QString::fromUtf8("Raspberry PI GUI v1.0"));
this->resize(800, 400);
// Add label Button
button = new QPushButton("Add Graphic", this);
button->setGeometry(QRect(QPoint(10, 20), QSize(200, 50)));
button->show();
QObject::connect(button, SIGNAL(pressed()), this, SLOT(input_label()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::input_label()
{
Label *label = new Label(this);
label->setText("New Graphic");
label->show();
}
void MainWindow::writeSettings()
{
QByteArray bArray;
QBuffer buffer(&bArray);
buffer.open(QIODevice::WriteOnly);
this->label->pixmap()->save(&buffer, "PNG"); // This line of code is crashing everything
QSettings settings("Save state", "GUIApp");
settings.beginGroup("MainWindow");
settings.setValue("image", bArray);
}
void MainWindow::readSettings()
{
QSettings settings("Save state", "GUIApp");
settings.beginGroup("MainWindow");
QByteArray image = settings.value("image", QByteArray()).toByteArray();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
writeSettings();
event->accept();
}
label.cpp
#include "label.h"
//---------------------------------------
// Deconstructor
//---------------------------------------
Label::~Label()
{
}
void Label::mousePressEvent(QMouseEvent *event)
{
// Move the coordinates on the main window
m_nMouseClick_X_Coordinate = event->x();
m_nMouseClick_Y_Coordinate = event->y();
}
void Label::mouseMoveEvent(QMouseEvent *event)
{
//-------------------------------------------------------------
// Allow the user to drag the graphics on the Display
//-------------------------------------------------------------
move(event->globalX()-m_nMouseClick_X_Coordinate-m_pParentWidget->geometry().x(),
event->globalY()-m_nMouseClick_Y_Coordinate-m_pParentWidget->geometry().y());
}
void Label::mouseDoubleClickEvent(QMouseEvent *event)
{
//QByteArray bArray;
//QBuffer buffer(&bArray);
//buffer.open(QIODevice::WriteOnly);
//--------------------------------
// Open file dialog
//--------------------------------
QFileDialog dialog(this);
dialog.setNameFilter(tr("Images(*.png, *.dxf, *.jpg"));
dialog.setViewMode(QFileDialog::Detail);
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Images"),
"/home",
tr("Image Files (*.png *.jpg *.bmp)"));
if (!fileName.isEmpty())
{
QImage image(fileName);
Label::setPixmap(fileName);
Label::adjustSize();
}
}
【问题讨论】:
-
this->label->pixmap() 可能会返回 0,这可能会使您的应用程序崩溃。您能否检查是否返回了有效的像素图?