小弟最近在学习Qt编写
串口通信程序,遇到一个
问题,自己想了想
没有解决,请教一下各路大神
。
想着设置QpushButton为checkable状态,
按钮弹起时串口处于关闭状态,按下时串口处于开启状态。
void MainWindow::
on_pushButton_switch_toggled(
bool checked)
//打开与关闭串口槽函数{
if(
checked)
{
if(
my_serialport->
open(
QIODevice::
WriteOnly))
{
my_serialport->
setBaudRate(
19200);
//设置波特率为19200 my_serialport->
setDataBits(
QSerialPort::
Data8);
//设置数据位为8 my_serialport->
setParity(
QSerialPort::
NoParity);
//设置为无奇偶检验 my_serialport->
setStopBits(
QSerialPort::
OneStop);
//设置停止位为1 my_serialport->
setFlowControl(
QSerialPort::
NoFlowControl);
//设置为无控制流 }
else {
//ui->pushButton_switch->setCheckable(false); ui->
pushButton_switch->
setChecked(!
checked);
FailPromptWindow();
//ui->pushButton_switch->setCheckable(true); cout
<<
"serial open fail" <<
endl;
}
}
else {
if(
my_serialport->
isOpen())
//若串口处于打开状态,关闭串口 {
my_serialport->
close();
}
}
}
connect(
ui->
pushButton_switch,
SIGNAL(toggled(
bool)),
this,
SLOT(on_pushButton_switch_toggled(
bool)));
//关联pushButton_swtich按键与打开关闭串口槽函数connect语句与开关函数如上所示,当串口打开
失败时,重设pushButton开关状态为弹起状态,并弹出串口打开失败的提示
窗口 FailPromptDialog(); 但是实际运行时发现,在打开失败情况下,可能是由于重置了开关状态:
ui->
pushButton_switch->
setChecked(!
checked);
所以失败提示窗口出现了两次,并且“serial open fail”也在控制台输出两次。
为了解决这个问题,想着在重置开关状态前先把开关设置成enable状态,但是好像失败了。
ui->
pushButton_switch->
setEnabled(
false);...(ui
->pushButton_switch->setChecked(!checked);)ui->
pushButton_switch->
setEnabled(
true);
虽然觉得不可行,但再次尝试设置为uncheckable状态,好像又失败了。
ui->pushButton_switch->setCheckable(false);...(ui->
pushButton_switch->
setChecked(!
checked);)ui->pushButton_switch->setCheckable(true);
有没有大神能指教一下怎么设置可以避免两次触发失败提示窗口
。
PS:最好能保留使用pushButton的check属性。