Qt面试题----利用多线程切换图片

功能要求

1. 两个线程同时按指定顺序读取文件(图片) 需要注意线程冲突

2. 读取的文件显示在主窗口的两个QLabel当中

3. 开始按钮 实现启动线程,开始更新图片

4. 暂停按钮 实现图片暂停刷新

5. 结束按钮 实现停止刷新图片,退出线程

程序界面要求:

需要显示的图片:

 

 设计思路:

1,主进程负责将两个线程读取到Qpixmap分别添加到两个Qlabel中,并设计三个按钮的信号槽

2,两个子线程负责读取不同的图片,然后传到主线程

具体代码:

主线程Mainwindows.h:


QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

public slots:
    void thread1Slot(QPixmap);
    void thread2Slot(QPixmap);

private slots:
    void on_pushButton_start_clicked();

    void on_pushButton_pause_clicked();

    void on_pushButton_end_clicked();

signals:
    void closeThread();


private:
    Ui::MainWindow *ui;

    thread_1 *t1;
    thread_2 *t2;

};

主线程MainWindow.cpp


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    t1 = new thread_1(this);
    t2 = new thread_2(this);

    //建立信号与槽
    connect(t1,SIGNAL(thread1Signal(QPixmap)),this,SLOT(thread1Slot(QPixmap)));
    connect(t2,SIGNAL(thread2Signal(QPixmap)),this,SLOT(thread2Slot(QPixmap)));


}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::thread1Slot(QPixmap p)
{
    ui->label1->setPixmap(p);
}

void MainWindow::thread2Slot(QPixmap p)
{
    ui->label2->setPixmap(p);
}


void MainWindow::on_pushButton_start_clicked()
{
    t1->start();
    t2->start();
}


void MainWindow::on_pushButton_pause_clicked()
{
    t1->terminate();
    t2->terminate();
}


void MainWindow::on_pushButton_end_clicked()
{
    //发送一个关闭线程信号,该信号会在两个子线程里面监听
    emit closeThread();

    t1->exit();
    t2->exit();

    t1->wait();
    t2->wait();


}

线程1.h


#include<QObject>
#include<QThread>
#include<QPixmap>

class thread_1: public QThread
{
    Q_OBJECT

public:
    explicit thread_1(QObject *parent = nullptr);

signals:
    void thread1Signal(QPixmap);

public slots:
    void recThread1Slot();      //接受主线程中的退出信号的槽

protected:
    void run();

private:
    bool stop = false;      //设置退出变量

};

线程2.cpp

#include "thread_1.h"

thread_1::thread_1(QObject *parent):QThread(parent)
{
    connect(parent,SIGNAL(closeThread()),this,SLOT(recThread1Slot()));

}


void thread_1::run()
{
    static int i = 1;
    while(!stop)
    {
        if(i>10)
        {
            i=1;
        }
        QString path = QString("://res/%0.png").arg(i);
        QPixmap p = QPixmap(path);

        QThread::sleep(2);
        emit thread1Signal(p);

        i+=2;

    }
}

void thread_1::recThread1Slot()
{
    qDebug("线程1退出");
    stop = true;
}

-------线程2同线程1写法

这个题目是我面试的一家qt岗的面试题,之前不会写这种多线程的题目。最近学习了一下,完成了这个题目。实现思路有很多,各位看官也可以提出更多想法和意见

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值