//QT 中,按钮数量比较少,可以分别用各按钮的信号和槽处理。
//当按钮数量较多时,用QButtonGroup可以实现共用一个槽函数,批量处理,减少垃圾代码,
//减少出错。
//开发平台:win10+QT6.2.4 MSVC2019 64 bit
//1.画面
//2.头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QButtonGroup>
#include <QList>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
void initGroupBoxPLCOutButton();
QButtonGroup * btnGroup=nullptr;
QTimer *timer2=nullptr;
void DispButtons();
private slots:
void OnButtonGroup(QAbstractButton *button, bool checked);
void loop2();
};
#endif // WIDGET_H
//3. cpp文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
initGroupBoxPLCOutButton();
timer2=new QTimer(this);
connect(timer2, SIGNAL(timeout()), this, SLOT(loop2())); // SLOT填入一个槽函数
timer2->start(100); // 100毫秒, 等于 1 秒
}
Widget::~Widget()
{
delete ui;
}
void Widget::initGroupBoxPLCOutButton()
{
btnGroup=new QButtonGroup(this);
btnGroup->addButton(ui->bt_Y00,0);
btnGroup->addButton(ui->bt_Y01,1);
btnGroup->addButton(ui->bt_Y02,2);
btnGroup->setExclusive(false);
QString color_off="background-color: rgb(150, 150, 150)";
QList buttonList = btnGroup->buttons();
for (int i = 0; i < buttonList.count(); i++) {
QAbstractButton *button = buttonList.at(i);
button->setCheckable(true);
button->setStyleSheet(color_off);
button->setFixedSize(30, 30);
button->setText("");
}
connect(btnGroup, SIGNAL(buttonToggled(QAbstractButton *, bool)), this, SLOT(OnButtonGroup(QAbstractButton *, bool)));
}
void Widget::OnButtonGroup(QAbstractButton *button, bool checked)
{
//qDebug() << "OnButtonGroup";
unsigned int out=0;
unsigned int temp =1;
if(button != NULL)
{
qDebug() << button->objectName();
qDebug() << checked;
QString str;
QList buttonList = btnGroup->buttons();
for (int i = 0; i < buttonList.count(); i++)
{
QAbstractButton *bt = buttonList.at(i);
if (bt->isChecked())
{
out=out | temp;
}
temp*=2;
if(bt==button)
{
str="输出点";
str+=QString::number(i);
str+="=";
str+=checked?"on":"off";
}
}
qDebug()<<str;
}
}
void Widget::loop2()
{
DispButtons();
}
void Widget::DispButtons()//显示按钮不同状态的颜色
{
QList buttonList = btnGroup->buttons();
QString color_on="background-color: rgb(0, 255, 0)";//按下,绿
QString color_off="background-color: rgb(111, 111, 111)";//未按下
for (int i = 0; i < buttonList.count(); i++)
{
QAbstractButton *button = buttonList.at(i);
if (button->isChecked())
button->setStyleSheet(color_on);
else
button->setStyleSheet(color_off);
}
}
//4.代码下载链接:
https://download.csdn.net/download/weixin_39926429/88975226