用QT写一个查看图片的程序,要求点击“上一张”和“下一张”实现显示图片
时间: 2024-05-12 19:20:10 浏览: 8
以下是一个简单的示例程序,可以实现查看图片并通过点击“上一张”和“下一张”按钮切换图片。
main.cpp:
```
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
```
mainwindow.h:
```
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QLabel *imageLabel; // 显示图片的标签
QPushButton *prevButton; // 上一张按钮
QPushButton *nextButton; // 下一张按钮
QStringList imageList; // 图片路径列表
int currentIndex; // 当前显示的图片索引
void showImage(const QString &fileName); // 显示指定的图片
private slots:
void prevImage(); // 显示上一张图片
void nextImage(); // 显示下一张图片
};
#endif // MAINWINDOW_H
```
mainwindow.cpp:
```
#include "mainwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 初始化图片路径列表和当前索引
imageList << "image1.jpg" << "image2.jpg" << "image3.jpg";
currentIndex = 0;
// 创建标签和按钮
imageLabel = new QLabel(this);
imageLabel->setAlignment(Qt::AlignCenter);
prevButton = new QPushButton("上一张", this);
nextButton = new QPushButton("下一张", this);
// 创建布局并添加控件
QVBoxLayout *mainLayout = new QVBoxLayout;
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(prevButton);
buttonLayout->addWidget(nextButton);
mainLayout->addWidget(imageLabel);
mainLayout->addLayout(buttonLayout);
// 设置窗口的主布局
QWidget *mainWidget = new QWidget(this);
mainWidget->setLayout(mainLayout);
setCentralWidget(mainWidget);
// 显示第一张图片
showImage(imageList[currentIndex]);
// 连接信号槽
connect(prevButton, &QPushButton::clicked, this, &MainWindow::prevImage);
connect(nextButton, &QPushButton::clicked, this, &MainWindow::nextImage);
}
MainWindow::~MainWindow()
{
}
void MainWindow::showImage(const QString &fileName)
{
// 加载图片并显示在标签上
QPixmap pixmap(fileName);
imageLabel->setPixmap(pixmap);
imageLabel->adjustSize();
}
void MainWindow::prevImage()
{
// 显示上一张图片
currentIndex--;
if (currentIndex < 0) {
currentIndex = imageList.size() - 1;
}
showImage(imageList[currentIndex]);
}
void MainWindow::nextImage()
{
// 显示下一张图片
currentIndex++;
if (currentIndex >= imageList.size()) {
currentIndex = 0;
}
showImage(imageList[currentIndex]);
}
```
这个程序的主要思路是,使用一个字符串列表来存储图片的路径,然后通过当前索引来确定当前显示的图片。在“上一张”和“下一张”按钮的槽函数中,改变当前索引并调用showImage函数来显示对应的图片。在showImage函数中,使用QPixmap来加载图片并显示在标签上。