QT的队列是类QQueue,它的原理其实就只是一个QList的结构,在继承QListj基础上封装了几个函数。
template <class T>
class QQueue : public QList<T>
{
public:
// compiler-generated special member functions are fine!
inline void swap(QQueue<T> &other) Q_DECL_NOTHROW { QList<T>::swap(other); } // prevent QList<->QQueue swaps
#ifndef Q_QDOC
// bring in QList::swap(int, int). We cannot say using QList<T>::swap,
// because we don't want to make swap(QList&) available.
inline void swap(int i, int j) { QList<T>::swap(i, j); }
#endif
inline void enqueue(const T &t) { QList<T>::append(t); }
inline T dequeue() { return QList<T>::takeFirst(); }
inline T &head() { return QList<T>::first(); }
inline const T &head() const { return QList<T>::first(); }
};
swap(int i, int j)//表示自己的i位置和j位置的元素调换位置。
swap(QQueue &other)//表示跟其它队列调换位置。
常用函数:
inline void enqueue(const T &t)//入队
inline T dequeue() //出队。
下面来一个例子来看看,它的使用方法。
#ifndef WIDGET_H
#define WIDGET_H
#include <QtWidgets>
#include <QThread>
#include <QQueue>
struct mydata
{
int id;
QString data;
};
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void slottest();
private:
QPushButton* m_btn;
};
class UThread : public QThread
{
public:
UThread();
void setExit(bool flag){m_isExit = flag;}
void addQueueData(mydata& info);
void run();
private:
QQueue<mydata> m_queue;
bool m_isExit;
};
#endif // WIDGET_H
#include "widget.h"
#include "unistd.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
m_btn = new QPushButton(this);
QVBoxLayout* lay = new QVBoxLayout(this);
lay->addWidget(m_btn);
setLayout(lay);
connect(m_btn,SIGNAL(clicked()),this,SLOT(slottest()));
}
Widget::~Widget()
{
}
void Widget::slottest()
{
UThread* thread = new UThread;
thread->start();
int i = 0;
while (i < 30)
{
mydata info;
info.id = i;
info.data = "test";
thread->addQueueData(info);
i++;
}
}
/*----------thread-----------*/
UThread::UThread()
{
m_isExit = true;
}
void UThread::addQueueData(mydata &info)
{
m_queue.enqueue(info);//入队
}
void UThread::run()
{
while (m_isExit)
{
if (m_queue.size() > 0)
{
mydata info = m_queue.dequeue();//出队
int id = info.id;
QString data = info.data;
qWarning()<<"id:"<<id<<"data:"<<data<<m_queue.size();
}
}
}
打印结果:
id: 0 data: "test" 29
id: 1 data: "test" 28
id: 2 data: "test" 27
id: 3 data: "test" 26
id: 4 data: "test" 25
id: 5 data: "test" 24
id: 6 data: "test" 23
id: 7 data: "test" 22
id: 8 data: "test" 21
id: 9 data: "test" 20
id: 10 data: "test" 19
id: 11 data: "test" 18
id: 12 data: "test" 17
id: 13 data: "test" 16
id: 14 data: "test" 15
id: 15 data: "test" 14
id: 16 data: "test" 13
id: 17 data: "test" 12
id: 18 data: "test" 11
id: 19 data: "test" 10
id: 20 data: "test" 9
id: 21 data: "test" 8
id: 22 data: "test" 7
id: 23 data: "test" 6
id: 24 data: "test" 5
id: 25 data: "test" 4
id: 26 data: "test" 3
id: 27 data: "test" 2
id: 28 data: "test" 1
id: 29 data: "test" 0
从结果不难看出它的入队出队操作,先进先出,后进后出。