接受框:plain text edit设置为只读
设置下拉框的内容combox
双击框框就可以编辑 设置默认选项:currentIndex
改变pro文件
QT += core gui serialport
代码
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QSerialPortInfo>
#include <QMessageBox>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QStringList serialNamePort;
serialPort = new QSerialPort(this);
connect(serialPort,SIGNAL(readyRead()),this,SLOT( serialPortReadyRead_slot()));
foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts()) {
serialNamePort<<info.portName();
}
ui->serNumber->addItems(serialNamePort);
}
Widget::~Widget()
{
delete ui;
}
void Widget::serialPortReadyRead_slot(){
QString buf;
buf = QString (serialPort->readAll());
ui->receivebox->appendPlainText(buf);
}
void Widget::on_openbt_clicked()
{
QSerialPort::BaudRate baudRate;
QSerialPort::DataBits databits;
QSerialPort::Parity parity;
QSerialPort::StopBits stopbits;
if(ui->bodrate->currentText()=="4800"){
baudRate = QSerialPort::Baud4800;
}else if(ui->bodrate->currentText()=="9600"){
baudRate= QSerialPort::Baud9600;
}else if(ui->bodrate->currentText()=="115200"){
baudRate=QSerialPort::Baud115200;
}
if(ui->databit->currentText()=="5"){
databits = QSerialPort::Data5;
}else if(ui->databit->currentText()=="6"){
databits = QSerialPort::Data6;
}else if(ui->databit->currentText()=="7"){
databits = QSerialPort::Data7;
}else if(ui->databit->currentText()=="8"){
databits = QSerialPort::Data8;
}
if(ui->stopbit->currentText()=="1"){
stopbits=QSerialPort::OneStop;
}else if(ui->stopbit->currentText()=="1.5"){
stopbits=QSerialPort::OneAndHalfStop;
}else if(ui->stopbit->currentText()=="2"){
stopbits=QSerialPort::TwoStop;
}
if(ui->checkbit->currentText()=="none"){
parity = QSerialPort::NoParity;
}
serialPort->setPortName(ui->serNumber->currentText());
serialPort->setBaudRate(baudRate);
serialPort->setDataBits(databits);
serialPort->setStopBits(stopbits);
serialPort->setParity(parity);
if(serialPort->open(QIODevice::ReadWrite)==true){
QMessageBox::information(this,"提示","成功");
}else{
QMessageBox::critical(this,"提示","失败");
}
}
void Widget::on_closebt_clicked()
{
serialPort->close();
}
void Widget::on_sendbt_clicked()
{
serialPort->write(ui->sendbox->text().toLocal8Bit().data());
}
void Widget::on_clearbt_clicked()
{
ui->receivebox->clear();
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSerialPort>
#include <QString>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QSerialPort *serialPort;
private slots:
void on_openbt_clicked();
void on_closebt_clicked();
void serialPortReadyRead_slot();
void on_sendbt_clicked();
void on_clearbt_clicked();
private:
Ui::Widget *ui;
};
#endif
|