How to catch exceptions with Qt platform independently? - c++

I'm using boost::date_time in my project. When date is not valid it thorws std::out_of_range C++ exception. In Qt's gui application on windows platform it becomes SEH exception, so it doesn't catched with try|catch paradigm and programm dies. How can I catch the exception platform independently?
try{
std::string ts("9999-99-99 99:99:99.999");
ptime t(time_from_string(ts))
}
catch(...)
{
// doesn't work on windows
}
EDITED:
If somebody didn't understand, I wrote another example:
Qt pro file:
TEMPLATE = app
DESTDIR = bin
VERSION = 1.0.0
CONFIG += debug_and_release build_all
TARGET = QExceptExample
SOURCES += exceptexample.cpp \
main.cpp
HEADERS += exceptexample.h
exceptexample.h
#ifndef __EXCEPTEXAMPLE_H__
#define __EXCEPTEXAMPLE_H__
#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <stdexcept>
class PushButton;
class QMessageBox;
class ExceptExample : public QMainWindow
{
Q_OBJECT
public:
ExceptExample();
~ExceptExample();
public slots:
void throwExcept();
private:
QPushButton * throwBtn;
};
#endif
exceptexample.cpp
#include "exceptexample.h"
ExceptExample::ExceptExample()
{
throwBtn = new QPushButton(this);
connect(throwBtn, SIGNAL(clicked()), this, SLOT(throwExcept()));
}
ExceptExample::~ExceptExample()
{
}
void ExceptExample::throwExcept()
{
QMessageBox::information(this, "info", "We are in throwExcept()",
QMessageBox::Ok);
try{
throw std::out_of_range("ExceptExample");
}
catch(...){
QMessageBox::information(this, "hidden", "Windows users can't see "
"this message", QMessageBox::Ok);
}
}
main.cpp
#include "exceptexample.h"
#include <QApplication>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
ExceptExample e;
e.show();
return app.exec();
}

Adding answer from the comments:
aschelper wrote:
Is your Qt library compiled with C++
exception support enabled? Sometimes
they're not, which causes problems.
hoxnox (OP) answered:
#aschelper I reconfigured Qt with
-exceptions option. It fixed situation. If you'll post the answer
I'll mark it as right.

Related

Can not get QT Bluetooth module to work with Virtual Box Ubuntu

I have created a small program using QT creator 4.14.0 (QT 5.15.2), using c++ and QML. I am creating, building and running the program on Ubuntu using Virtual box on a windows 10 system. I have installed bluez and other bluetooth packages on the virtual Ubuntu system as per instructions I've found online, and I have bluetooth working in the Ubuntu operating system, I can scan for devices using the Bluetooth quick-tray item and it finds what it's supposed to find, the bluetooth adapter works.
However, when I run my program I get the the following under Application output "qt.bluetooth: Dummy backend running. Qt Bluetooth module is non-functional.", and the bluetooth scan never starts (no further output). From what I can gather by research it seems like QT thinks that the system can not support Bluetooth, and uses a "dummy stub" in lieu of the actual working code. I have researched what I can about how to resolve this, but I can not find anything I can apply to my own code/setup. I would be appreciative of any help I can get.
Here's the relevant code:
// this is bluetooth_scanner.h
#ifndef BLUETOOTH_SCANNER_H
#define BLUETOOTH_SCANNER_H
#include <QObject>
#include <QBluetoothDeviceDiscoveryAgent>
#include <QBluetoothDeviceInfo>
#include <QDir>
#include <QTextStream>
class bluetooth_scanner : public QObject
{
Q_OBJECT
public:
bluetooth_scanner();
void startDeviceDiscovery();
public slots:
void deviceDiscovered(const QBluetoothDeviceInfo &device);
};
#endif // BLUETOOTH_SCANNER_H
// this is bluetooth_scanner.cpp
#include "bluetooth_scanner.h"
// constructor
bluetooth_scanner::bluetooth_scanner()
{
}
void bluetooth_scanner::startDeviceDiscovery()
{
// Create a discovery agent and connect to its signals
QBluetoothDeviceDiscoveryAgent *discoveryAgent = new QBluetoothDeviceDiscoveryAgent(); // was 'this' inside parantheses, got build error, removed == no build error
QObject::connect(discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),this, SLOT(deviceDiscovered(QBluetoothDeviceInfo)));
// Start a discovery
discoveryAgent->start();
}
// In your local slot, read information about the found devices
void bluetooth_scanner::deviceDiscovered(const QBluetoothDeviceInfo &device)
{
// init QT printing
QTextStream out(stdout);
out << "Found new device:" << device.name() << '(' << device.address().toString() << ')' << endl;
}
// this is main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <bluetooth_scanner.h>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
// test bluetooth C++ scan function
bluetooth_scanner *bt_scan = new bluetooth_scanner();
bt_scan->startDeviceDiscovery();
return app.exec();
}

No reply data with QNetworkAccessManager when running on another machine

I have a simple program that should retrieve the HTML from a website URL.
main.cpp
#include "Downloader.h"
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
auto dl = new Downloader(&a);
QString url = "https://www.dognow.at/ergebnisse/?page=1";
dl->fetch(url);
return a.exec();
}
Downloader.h
#ifndef DOWNLOADER_H
#define DOWNLOADER_H
#include <QNetworkReply>
#include <QObject>
class Downloader : public QObject
{
Q_OBJECT
public:
explicit Downloader(QObject* parent = nullptr);
void fetch(QString &url);
private:
QNetworkAccessManager* m_manager;
private slots:
void replyFinished(QNetworkReply* rep);
};
#endif // DOWNLOADER_H
Downloader.cpp
#include "Downloader.h"
#include <QDebug>
Downloader::Downloader(QObject* parent): QObject(parent),
m_manager(new QNetworkAccessManager(parent))
{}
void Downloader::fetch(QString& url)
{
qDebug() << "fetch " << url;
connect(m_manager, &QNetworkAccessManager::finished, this, &Downloader::replyFinished);
m_manager->get(QNetworkRequest(QUrl(url)));
}
void Downloader::replyFinished(QNetworkReply* rep)
{
QByteArray data=rep->readAll();
QString str(data);
qDebug() << "data len: " << str.length();
rep->close();
}
When I run the program on my local PC it works fine. When I run it on another machine the reply data is empty. On both systems I use Linux (x86_64) and Qt 5.15.0.
I hope someone can give me a hint where I should have a look at.
UPDATE: 2022-04-04 - 16:22:
when I run a simple curl command on the failing machine it works fine.
Ok, I found the problem.
On the failing machin I have an older ubuntu (16.04 LTS) running with an incompatible openssl version.
I found it out because I copied my own Qt libs build (debug) to the other machine and I got SSL error (incompatbile version).
I installed a newer openssl version and know it works.

running draw_polygon example in CGAl package in qt widget application

I try to following CGAL example in Qt widget application :
example
main.ccp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.ccp :
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
void MainWindow::on_pushButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Open .off model"), "/home", tr("*.off"));
draw_poly(fileName);
}
void MainWindow::draw_poly(QString fileName)
{
QByteArray inBytes;
const char *c;
inBytes = fileName.toUtf8();
c = inBytes.constData();
std::ifstream input(c);
if (!input || !(input >> mesh) || mesh.is_empty()) {
std::cerr << "Not a valid off file." << std::endl;
// return 1;
}
input >> mesh;
CGAL::draw(mesh);
}
when I ran it , it open dialog file to select .off file ,then it shows the following error:
QCoreApplication::exec: The event loop is already running
any help ,please ?
I'm using Qt5 in daily business, and once considered CGAL as possible application base (without going further into this direction – not yet). Hence, this question made me curious.
I digged through the source code of CGAL on github and found out why the error message
QCoreApplication::exec: The event loop is already running
occurs.
For this, I copied the relevant lines from CGAL on github: Polyhedron/include/CGAL/draw_polyhedron.h:
template<class Polyhedron, class ColorFunctor>
void draw(const Polyhedron& apoly,
const char* title,
bool nofill,
const ColorFunctor& fcolor)
{
#if defined(CGAL_TEST_SUITE)
bool cgal_test_suite=true;
#else
bool cgal_test_suite=false;
#endif
if (!cgal_test_suite)
{
int argc=1;
const char* argv[2]={"polyhedron_viewer","\0"};
QApplication app(argc,const_cast<char**>(argv));
SimplePolyhedronViewerQt<Polyhedron, ColorFunctor>
mainwindow(app.activeWindow(), apoly, title, nofill, fcolor);
mainwindow.show();
app.exec();
}
}
Looking at this source code, it becomes obvious that CGAL::draw() is a small ful-featured Qt application in itself which establishs its own QApplication instance. The OP in turn tried to embed the CGAL::draw() in her/his own Qt application. It is not allowed to instance any derivates of QCoreApplication more than once (according to Qt doc. of QApplication):
For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time.
(Emphasizing not mine.)
The CGAL doc. provides an (even shorter) example in Polyhedron/draw_polyhedron.cpp to do this right:
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
int main(int argc, char* argv[])
{
Polyhedron P;
std::ifstream in1((argc>1)?argv[1]:"data/cross.off");
in1 >> P;
CGAL::draw(P);
return EXIT_SUCCESS;
}
but there is no place to insert the QFileDialog at the right point.
Hence, CGAL::draw() is the wrong tool for what OP (probably) intends to do – embed CGAL polyhedron rendering into a Qt application. For this, it is necessary to use the things directly which are called somewhere inside of CGAL::draw().
So, this is what seems appropriate to me:
making SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> a (main or child) widget in OPs Qt application.
I then walked a bit through the github repo to find out from which Qt widget CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> is actually derived from and found the following inheritance:
CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor>
|
V
CGAL::Basic_viewer_qt
|
V
CGAL::QGLViewer
|
+--------------+--------------+
| |
V V
QOpenGLWidget QOpenGLFunctions
So, CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> can be used like any QWidget (which involves making it the main window). It can become as well the center widget of a QMainWindow which gets a menu bar/tool bar with the QAction to open the QFileDialog, request a file path, open a file stream with this file path, and load a mesh from this file stream.
There is another minor detail where I stumbled over: The CGAL::Polyhedron has to be given to the CGAL::SimplePolyhedronViewerQt in the constructor and by const reference. To consider this, it's IMHO necessary (after successful loading of mesh) to construct the CGAL::SimplePolyhedronViewerQt instance by new and set/add it to parent widget afterwards. If this is not acceptable it's probably necessary to go even deeper and replace the CGAL::SimplePolyhedronViewerQt by an own implementation, using the source code of the former as “cheat-sheet”.
This is how such an application could look like:
#include <fstream>
#include <QtWidgets>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
CGAL::DefaultColorFunctorPolyhedron fColor;
Polyhedron mesh;
// setup UI
QMainWindow qWin;
QToolBar qToolbar;
QAction qCmdLoad(QString::fromUtf8("Load File..."));
qToolbar.addAction(&qCmdLoad);
qWin.addToolBar(&qToolbar);
qWin.show();
// install signal handlers
QObject::connect(&qCmdLoad, &QAction::triggered,
[&qWin, &mesh, &fColor]() {
const QString filePath = QFileDialog::getOpenFileName(
&qWin,
QString::fromUtf8("Open .off model"),
QString::fromUtf8("/home"),
QString::fromUtf8("*.off"));
if (filePath.isEmpty()) return;
std::ifstream fIn(filePath.toUtf8().data());
if (!(fIn >> mesh) || mesh.is_empty()) {
qDebug() << "Loading of" << filePath << "failed!";
return;
}
qWin.setCentralWidget(
new CGAL::SimplePolyhedronViewerQt<Polyhedron, CGAL::DefaultColorFunctorPolyhedron>(
&qWin, mesh, "Basic Polyhedron Viewer", false, fColor));
qWin.centralWidget()->show();
});
// runtime loop
return app.exec();
}
Please, take this with a “grain of salt” – I've no CGAL at hand and couldn't compile/test the above code.
CGAL::draw() already handles the Qt stuff. You are trying to open a mainwindow in another one. Just call CGAL::draw(mesh) in your main() function without anything else and it will work.
EDIT: Which is exactly what Sheff explained in a much more detailed way.

QCompleter::activated disconnected after losing and gaining focus

I found a strange case which I do not understand. Maybe it is a Qt bug, maybe I am doing something wrong.
A header:
// File mylineedit.h
#pragma once
#include <QLineEdit>
#include <QDebug>
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MyLineEdit(QWidget *parent = nullptr) : QLineEdit(parent) { }
public slots:
void onCompleterActivated(const QString& text) { qDebug() << "MyLineEdit" << text; }
};
And the main source file:
// File main.cpp
#include <QApplication>
#include <QWidget>
#include <QStringListModel>
#include <QCompleter>
#include <QVBoxLayout>
#include "mylineedit.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QLineEdit* lineEdit1 = new MyLineEdit();
QLineEdit* lineEdit2 = new MyLineEdit();
auto layout = new QVBoxLayout(&w);
layout->addWidget(lineEdit1);
layout->addWidget(lineEdit2);
lineEdit1->setCompleter(new QCompleter());
auto model = new QStringListModel(QStringList() << "A" << "B" << "C");
lineEdit1->completer()->setModel(model);
QObject::connect(lineEdit1->completer(), SIGNAL(activated(QString)), lineEdit1, SLOT(onCompleterActivated(QString)));
w.show();
return a.exec();
}
Once you run this, you can get a completer with values "A", "B", "C" in the first line edit. When you select any of these values, it will print the message to the console. This is correct. But then change focus to the other line edit and then back. Try picking "A", "B", "C" again. No message is printed out, the signal/slot seems disconnected. Any ideas?
Tested with MinGW 5.3.0 and MSVC 2015 using with Qt 5.9.2.
I modified your sample slightly and tried to reproduce the behavior you described but I couldn't:
#include <QtWidgets>
int main(int argc, char **argv)
{
qDebug() << "Qt Version: " << QT_VERSION_STR;
// main application
QApplication app(argc, argv);
// setup GUI
QWidget qWin;
QVBoxLayout qVBox;
QLineEdit qEdit1;
qVBox.addWidget(&qEdit1);
QCompleter qCompl1;
QStringListModel qComplModel(QStringList() << "A" << "B" << "C");
qCompl1.setModel(&qComplModel);
qEdit1.setCompleter(&qCompl1);
QLineEdit qEdit2;
qVBox.addWidget(&qEdit2);
qWin.setLayout(&qVBox);
qWin.show();
// install signal handlers
QObject::connect(&qCompl1,
static_cast<void(QCompleter::*)(const QString&)>(
&QCompleter::activated),
[](const QString &text)
{
qDebug() << "Activated: " << text;
});
// run-time loop
return app.exec();
}
The significant differences in my sample:
I used Qt5 style signal handlers (as I'm used to).
I didn't new the Qt widgets (as I'm used to when I write minimal samples).
For me, it's hard to believe that one of these changes makes your described issue unbroken.
I compiled and tested with VS2013, Qt 5.9.2 on Windows 10 (64 bit):
I did the following interactions:
click in qEdit1
type A and click on item A in the popup menu
Output:
Activated: "A"
I continued with:
click in qEdit2
type B
click in qEdit1
erase text, type B, and click on item B in the popup menu
Output:
Activated: "B"
It works like expected.
After some conversation, I had a look at woboq.org in the source code of QLineEdit:
The interesting part is in QLineEdit::focusOutEvent:
if (d->control->completer()) {
QObject::disconnect(d->control->completer(), 0, this, 0);
}
If I read this right, all signal handlers of QLineEdit (emitted by the set completer) are disconnected. I believe this is the reason for the observed issue. (Therefore, it works for lambdas and methods of other classes.)

Qt Serial with Arduino Due Native USB port and Bluetooth NR 42 configuring through Xbee explorer

I am trying to make an application in Qt to configure a bluetooth module RN42 http://ww1.microchip.com/downloads/en/DeviceDoc/rn-42-ds-v2.32r.pdf . In order to configure the module some command have to be sent via serial port, but here is where the extrange things start happening. I conecto it to the computer via xbee xplorer and I can configure it without any problems using my application, but when I try to retreive the current configuration no response is got, I can see that the device enters in configuration mode because the led blinks faster, but I cannot get any feedback from the device via serial port.
So I decided to start debugging with arduino due, if I connect it via programming port I can comunicate wihout problems, but if I connect it with the USB native port I do not get any information from the device. But if I open the port with the arduino serial monitor, the comunication starts, then close the arduino serial monitor, open my application and I am comunicating without problems.
I have also tried to comunicate with docklight (a serial monitor application) and again I have no problem comunicating, but if after comunicating with docklight I try to comunicate with my application no response will be got, unlike arduino serial monitor.
Eventhough I debugged with an oscilloscope and I can see that the information is sent once the port is closed.
I have tried many different things and I do not know what I am doing wrong. I tink it is related with the configuration of the port, but not sure, could it be a bug with the QtSerialport?
Here are my programs. I am using Qt creator 5.9.1 in windows with MinGW53_32
QT
.pro
#-------------------------------------------------
#
# Project created by QtCreator 2017-07-25T08:39:59
#
#-------------------------------------------------
QT += core gui
QT += serialport
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = BT_Config_Tool
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
bluetooth_config.cpp
HEADERS += \
bluetooth_config.h
FORMS += \
bluetooth_config.ui
bluetooth_config.h
#ifndef BLUETOOTH_CONFIG_H
#define BLUETOOTH_CONFIG_H
#include <QMainWindow>
#include <QTimer>
#include <QSerialPort>
#include <QtSerialPort>
#include <QtSerialPort/QtSerialPort>
#include <stdio.h>
#include <math.h>
#include <QSerialPortInfo>
#define BUFFMAX 1000
namespace Ui {
class bluetooth_config;
}
class bluetooth_config : public QMainWindow
{
Q_OBJECT
public slots:
void ReadDevice(void);
void FlashDevice(void);
void UpdateCombobox(void);
void ReadSerial(void);
public:
explicit bluetooth_config(QWidget *parent = 0);
~bluetooth_config();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::bluetooth_config *ui;
QSerialPort *_port;
QTimer *_timerRead;
QTimer *_timerFlash;
QTimer *_timerUpdateCombobox;
QSerialPortInfo *_serialPortInfo;
int _cFlash = 0;
int _cRead = 0;
char _buffer[BUFFMAX];
//QByteArray _buffer;
int c;
};
#endif // BLUETOOTH_CONFIG_H
bluetooth_config.cpp
#include "bluetooth_config.h"
#include "ui_bluetooth_config.h"
const char *nameFlash;
const char *passFlash;
const char *nameRead;
char trama[BUFFMAX];
int item = 0;
bluetooth_config::bluetooth_config(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::bluetooth_config)
{
ui->setupUi(this);
ui->label_4->setVisible(false);
ui->label_5->setVisible(false);
_timerRead = new QTimer(this);
connect(_timerRead,SIGNAL(timeout()),this, SLOT(ReadDevice()));
_timerFlash = new QTimer(this);
connect(_timerFlash,SIGNAL(timeout()),this, SLOT(FlashDevice()));
_timerUpdateCombobox = new QTimer(this);
connect(_timerUpdateCombobox,SIGNAL(timeout()),this, SLOT(UpdateCombobox()));
_timerUpdateCombobox->start(2000);
_port = new QSerialPort();
_port->setBaudRate(QSerialPort::Baud115200);
_port->setDataBits(QSerialPort::Data8);
_port->setParity(QSerialPort::NoParity);
_port->setStopBits(QSerialPort::OneStop);
_port->setFlowControl(QSerialPort::NoFlowControl);
connect(_port,SIGNAL(readyRead()),this,SLOT(ReadSerial()));
//ui->tabWidget->setTabEnabled(0, false);
}
bluetooth_config::~bluetooth_config()
{
delete ui;
}
void bluetooth_config::ReadDevice()
{
_cRead ++;
if (_cRead == 1){
_port->write("$$$");
ui->lcdNumber_2->display(_cRead);
_timerRead->stop();
}
else if (_cRead == 2){
_port->write("---\r\n");
_port->waitForBytesWritten();
ui->lcdNumber_2->display(_cRead);
_timerRead->stop();
}
else if (_cRead == 3){
ui->label_5->setVisible(true);
ui->lcdNumber_2->display(_cRead);
_timerRead->stop();
_cRead = 0;
}
}
void bluetooth_config::FlashDevice()
{
_cFlash ++;
if (_cFlash == 1){
_port->write("$$$");
}
else if (_cFlash == 2){
nameFlash = ui->lineEdit->displayText().toUtf8().constData();
strcpy(trama, "SN,");
strcat(trama,nameFlash);
strcat(trama,"\n\r");
_port->write(trama);
}
else if (_cFlash == 3){
passFlash = ui->lineEdit_2->displayText().toUtf8().constData();
strcpy(trama, "SP,");
strcat(trama,passFlash);
strcat(trama,"\n\r");
_port->write(trama);
}
else if (_cFlash == 4){
_port->write("---\n\r");
}
else if (_cFlash == 5){
_cFlash = 0;
_timerFlash->stop();
ui->label_4->setVisible(true);
}
}
void bluetooth_config::UpdateCombobox()
{
item = ui->comboBox->currentIndex();
ui->comboBox->clear();
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts())
{
ui->comboBox->addItem(serialPortInfo.portName());
}
if (item <= (ui->comboBox->count() - 1) && item >= 0){
ui->comboBox->setCurrentIndex(item);
}
else {
ui->comboBox->setCurrentIndex(ui->comboBox->count() - 1);
}
}
void bluetooth_config::ReadSerial()
{
int ojete = _port->bytesAvailable();
ui->lcdNumber->display(ojete);
//_port->read(_buffer,BUFFMAX);
QByteArray a = _port->readAll();
//ui->plainTextEdit->appendPlainText(_buffer);
ui->plainTextEdit->appendPlainText(a);
if (_cRead == 1 || _cRead == 2){
_timerRead->start(50);
}
}
void bluetooth_config::on_pushButton_clicked()
{
ui->label_5->setVisible(false);
_timerRead->start(50);
_port->flush();
}
void bluetooth_config::on_pushButton_2_clicked()
{
ui->label_4->setVisible(false);
_timerFlash->start(50);
_port->flush();
}
void bluetooth_config::on_pushButton_3_clicked()
{
if (!_port->isOpen()){
_port->setPortName(ui->comboBox->currentText());
if (_port->open(QIODevice::ReadWrite)){
ui->label_3->setText("Puerto abierto");
ui->pushButton_3->setText("Cerrar");
ui->pushButton->setEnabled(true);
ui->pushButton_2->setEnabled(true);
}
else {
ui->label_3->setText("Ha ocurrido un error al abrir el puerto");
}
}
else {
_port->close();
ui->label_3->setText("Puerto cerrado");
ui->pushButton_3->setText("Abrir");
ui->pushButton->setEnabled(false);
ui->pushButton_2->setEnabled(false);
}
}
main.cpp
#include "bluetooth_config.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
bluetooth_config w;
w.show();
return a.exec();
}
Thank you very much.
Alejandro