就是使用QTableWidget生成一个LED点阵, 使用网上的Arduino点阵数组, 应用在此;
LEDWidget.h
#ifndef LEDWIDGET_H
#define LEDWIDGET_H
#include <QWidget>
class LEDWidget : public QWidget
{
public:
LEDWidget(QWidget *parent = nullptr);
inline void controlLed(bool on=false)
{
if (on != m_on)
{
m_on = on;
update();
}
}
inline void toggleLed()
{
m_on = !m_on;
update();
}
protected:
void paintEvent(QPaintEvent *event) override;
bool m_on;
};
#endif // LEDWIDGET_H
LEDWidget.cpp
#include "ledwidget.h"
#include <QPainter>
#include <QColor>
#include <QPen>
LEDWidget::LEDWidget(QWidget *parent)
: QWidget(parent), m_on(false)
{
}
void LEDWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QPen pen;
pen.setColor(QColor(128, 128, 128)); // 设置线颜色为浅灰色
painter.setPen(pen);
// 设置LED灯的颜色和大小
// QColor ledColor(85, 239, 196); // 红色
int ledSize = std::max(20, width() >= height() ? height() - 10 : width() - 10);
QLinearGradient gradient(0, 0, width(), height());
if (m_on)
{
gradient.setColorAt(0, "#43e97b");
gradient.setColorAt(1, "#38f9d7");
}
else
{
gradient.setColorAt(0, "#e6e9f0");
gradient.setColorAt(1, "#eef1f5");
}
painter.setBrush(gradient);
// 计算LED灯的位置
int x = (width() - ledSize) / 2;
int y = (height() - ledSize) / 2;
// 绘制LED灯的主体
// painter.setBrush(ledColor);
painter.drawEllipse(x, y, ledSize, ledSize);
}
爱心点阵代码
int table[64] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 0, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0,
};
ui->tableWidget->setRowCount(8);
ui->tableWidget->setColumnCount(8);
for (int r = 0; r < ui->tableWidget->rowCount(); ++r)
{
for (int l = 0; l < ui->tableWidget->columnCount(); ++l)
{
MarqueeLED *wgt = new MarqueeLED(ui->tableWidget->rowCount()*5 + l);
wgt->controlLed(table[ui->tableWidget->rowCount()*r + l]);
ui->tableWidget->setColumnWidth(l, 100);
ui->tableWidget->setRowHeight(l, 100);
ui->tableWidget->setCellWidget(r, l, wgt);
}
}