close
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMenuBar>
#include <QToolBar>
#include <QAction>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QStatusBar>
#include <QLabel>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
void initUI();
void createActions();
void showImage(QString filePath);
void setupShortcuts();
private slots:
void openImage();
private:
Ui::MainWindow *ui;
QMenu *fileMenu;
QMenu *viewMenu;
QToolBar *fileToolBar;
QToolBar *viewToolBar;
QGraphicsScene *imageScene;
QGraphicsView *imageView;
QStatusBar *mainStatusBar;
QLabel *mainStatusLabel;
QAction *openAction;
QString currentImagePath;
QGraphicsPixmapItem *currentImage;
};
#endif // MAINWINDOW_H
mainwindow.cpp
initUI()
void MainWindow::initUI()
{
//this->resize(800,600);
// setup menubar
fileMenu = menuBar()->addMenu("&File");
viewMenu = menuBar()->addMenu("&View");
// main area for image display
imageScene = new QGraphicsScene(this);
imageView = new QGraphicsView(imageScene);
setCentralWidget(imageView);
// setup status bar
mainStatusBar = statusBar();
mainStatusLabel = new QLabel(mainStatusBar);
mainStatusBar->addPermanentWidget(mainStatusLabel);
mainStatusLabel->setText("Image Information:");
}
create actions
1. Creating a new action call openAction, which is used for opening an image
2. Attatching the action, which is called openAction, to fileMenu.
3. Building a signal and slot mechanics between openAction->triggered(source) and this->openImage(target)
void MainWindow::createActions()
{
// create actions, add them to menus
openAction = new QAction("&Open", this);
fileMenu->addAction(openAction);
connect(openAction, SIGNAL(triggered()), this, SLOT(openImage()));
}
openImage()
void MainWindow::openImage()
{
QFileDialog dialog(this);
dialog.setWindowTitle("Open an image file");
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setNameFilter(tr("Images (*.png *bmp *.jpg"));
QStringList filePaths;
if(dialog.exec())
{
filePaths = dialog.selectedFiles();
showImage(filePaths.at(0));
}
}
showImage()
void MainWindow::showImage(QString filePath)
{
imageScene->clear();
imageView->resetMatrix();
QPixmap image(filePath);
currentImage = imageScene->addPixmap(image);
imageScene->update();
imageView->setSceneRect(image.rect());
QString info =QString("%1, %2x%3, %4 Bytes").arg(filePath)
.arg(image.width())
.arg(image.height())
.arg(QFile(filePath).size());
mainStatusLabel->setText(info);
currentImagePath = filePath;
}
全站熱搜
留言列表