修一个链表存储读取QImage
时间: 2023-07-25 19:48:23 浏览: 51
好的,下面是一个简单的链表存储读取QImage的示例代码:
```cpp
#include <QtCore>
#include <QtGui>
class Node {
public:
QImage image;
Node* next;
};
class ImageList {
public:
ImageList() {
head = nullptr;
tail = nullptr;
}
~ImageList() {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
void addImage(const QString& fileName) {
QImage image(fileName);
if (!image.isNull()) {
Node* node = new Node;
node->image = image;
node->next = nullptr;
if (tail == nullptr) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
}
QImage getImage(int index) {
Node* node = getNode(index);
if (node != nullptr) {
return node->image;
} else {
return QImage();
}
}
int count() {
int n = 0;
Node* node = head;
while (node != nullptr) {
n++;
node = node->next;
}
return n;
}
private:
Node* head;
Node* tail;
Node* getNode(int index) {
if (index < 0 || index >= count()) {
return nullptr;
}
Node* node = head;
for (int i = 0; i < index; i++) {
node = node->next;
}
return node;
}
};
```
在这个示例代码中,我们使用一个 Node 类表示链表中的节点,节点包含一个 QImage 对象和一个指向下一个节点的指针。然后,我们定义了一个 ImageList 类,这个类包含一个指向链表头和尾的指针,以及一些用于添加、获取和计算链表长度的成员函数。在 addImage() 函数中,我们读取指定文件名的 QImage 对象,并将其存储到一个新的节点中,然后将这个节点添加到链表的末尾。在 getImage() 函数中,我们根据指定的索引获取节点,并返回节点中存储的 QImage 对象。在 count() 函数中,我们遍历整个链表,并计算节点数量。
在实际使用中,您可以通过调用 ImageList 的 addImage() 函数来添加新的 QImage 对象,然后通过调用 getImage() 函数来获取指定索引的 QImage 对象。下面是一个简单的示例:
```cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
ImageList imageList;
imageList.addImage("image1.png");
imageList.addImage("image2.png");
imageList.addImage("image3.png");
QImage image1 = imageList.getImage(0);
QImage image2 = imageList.getImage(1);
QImage image3 = imageList.getImage(2);
return app.exec();
}
```
在这个示例中,我们先创建了一个 ImageList 对象,然后调用 addImage() 函数来添加三个 QImage 对象。最后,我们通过调用 getImage() 函数来获取第 1、2、3 张图片,并将它们存储到三个 QImage 变量中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)