用qt写一个电路网孔圈划算法
时间: 2023-05-23 22:03:15 浏览: 79
Dijkstra算法可视化模拟Qt.zip
好的,以下是一个用 Qt 写的电路网孔圈划算法:
```C++
#include <QtGui/QPainter>
#include <QtGui/QWidget>
#include <QtGui/QMouseEvent>
#include <QtCore/QVector>
class CircuitBoard : public QWidget
{
public:
explicit CircuitBoard(QWidget *parent = nullptr)
: QWidget(parent), m_boardSize(200, 200), m_maxGridSize(20),
m_selectedGrid(-1, -1), m_hoverGrid(-1, -1)
{
resize(m_boardSize);
setMouseTracking(true);
}
protected:
void paintEvent(QPaintEvent *event) override
{
Q_UNUSED(event);
QPainter painter(this);
// 画出网孔
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(Qt::white));
for (const auto &grid : m_grids) {
if (m_selectedGrid == grid) {
painter.setBrush(QBrush(Qt::gray));
} else if (m_hoverGrid == grid) {
painter.setBrush(QBrush(QColor(230, 230, 230)));
} else if (grid.x() % 5 == 0 && grid.y() % 5 == 0) {
painter.setBrush(QBrush(QColor(220, 220, 220)));
} else {
painter.setBrush(QBrush(Qt::white));
}
painter.drawRect(grid.x() * m_gridSize.width(), grid.y() * m_gridSize.height(), m_gridSize.width(), m_gridSize.height());
}
}
void mousePressEvent(QMouseEvent *event) override
{
m_selectedGrid = event->pos() / m_gridSize;
update();
}
void mouseMoveEvent(QMouseEvent *event) override
{
auto pos = event->pos() / m_gridSize;
if (pos != m_hoverGrid) {
m_hoverGrid = pos;
update();
}
}
void mouseReleaseEvent(QMouseEvent *event) override
{
Q_UNUSED(event);
if (m_selectedGrid != QPoint(-1, -1)) {
for (auto &grid : m_grids) {
if (grid == m_selectedGrid) {
grid = m_hoverGrid;
break;
}
}
m_selectedGrid = QPoint(-1, -1);
update();
}
}
void resizeEvent(QResizeEvent *event) override
{
auto oldSize = m_boardSize;
m_boardSize = event->size();
m_gridSize = QSize(m_boardSize.width() / m_maxGridSize, m_boardSize.height() / m_maxGridSize);
// 调整网格大小和位置
for (auto &grid : m_grids) {
grid.setX(grid.x() * m_boardSize.width() / oldSize.width());
grid.setY(grid.y() * m_boardSize.height() / oldSize.height());
}
// 创建新的网格
m_grids.clear();
for (int i = 0; i < m_maxGridSize; ++i) {
for (int j = 0; j < m_maxGridSize; ++j) {
m_grids.append(QPoint(i, j));
}
}
}
private:
QVector<QPoint> m_grids; // 网格
QSize m_boardSize; // 电路板大小
QSize m_gridSize; // 网格大小
int m_maxGridSize; // 最大网格数
QPoint m_selectedGrid; // 选中的网格
QPoint m_hoverGrid; // 鼠标所在的网格
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
CircuitBoard board;
board.show();
return app.exec();
}
```
这段代码可以在 Qt Creator 中编译运行,它创建了一个电路板窗口,可以用鼠标拖动网孔圈。
阅读全文