3、主窗口程序设计:
主窗口程序包括线程的启动与处理,通过信号与槽机制通过write按键实现写串口,通过定时器实现读串口操作,通过close按键实现串口关闭,同时把读取串口数据进行显示,其主要程序及分析如下:
1)新建一个mainwindow.h头文件,内容如下:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include"ui_mainwindow.h" // ui_mainwindow.h 文件为designer设计
mainwindow.ui文件后,经过make后会生成这个头文件,
#include"thread.h" //包含线程包头文件
class MainWindow:public QMainWindow,public Ui::MainWindow //多继承
{
Q_OBJECT
public:
MainWindow(QWidget *parent=0);
public slots:
void writeThread();
void readThread();
void closeThread();
void display();
private:
Thread *yy;
};
#endif
MainWindow继承于QMainWindow和MainWindow,即多继承,对于不是很复杂的程序,用多继承是一个较好的方法,如果程序较复杂,建议用单继承,具体原因待进一步研究,呵呵。
2)新建一个mainwindow.cpp文件,实现程序内容如下:
#include"mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
:QMainWindow(parent)
{
setupUi(this);
yy = new Thread;
yy->start(); //启动线程
yy->stopped=1; //初始化变量
yy->write_rs=0;
yy->read_rs=0;
QTimer *time = new QTimer(this); //新建定时类
time->start(50); //50ms定时
connect(writeButton,SIGNAL(clicked()),this,SLOT(writeThread()));
//通过信号与槽实现按键按下进行写串口操作
connect(time,SIGNAL(timeout()),this,SLOT(readThread()));
//定时溢出实现读串口操作
connect(closeButton,SIGNAL(clicked()),this,SLOT(closeThread()));
connect(yy,SIGNAL(finished()),this,SLOT(display())); //接收信号实现显示
}
void MainWindow::display()
{
textBrowser->setText(yy->buf); //读到的数据在textBrowser l显示
}
void MainWindow::writeThread() //写数据线程槽函数
{
yy->write_rs=1;
}
void MainWindow::readThread() //读数据线程槽函数
{
yy->read_rs=1;
}
void MainWindow::closeThread() //停止槽函数
{
yy->stopped=0;
}
4、main.cpp函数程序设计:
#include
#include"mainwindow.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
MainWindow mw;
mw.show();
return app.exec();
}
这样整个Linux环境下线程+定时实现的Qt串口编程的程序全部实现,可以通过串口发送,接收数据实现数据的测试。
