qt QPainter实现24小时时间轴 ,并且可以移动,鼠标按下后可以左右任意移动并且时间也会随之改变,24小时是固定的但是日期不是固定的
时间: 2024-01-21 11:16:35 浏览: 167
qt绘制时间轴,自由设置时间刻度
以下是一个简单的实现示例,其中使用了QPainter绘制时间轴,并在QWidget上实现了鼠标按下事件来实现拖动:
```cpp
#include <QtWidgets>
class TimeAxis : public QWidget {
public:
explicit TimeAxis(QWidget *parent = nullptr)
: QWidget(parent)
{
setFixedSize(600, 50);
m_startTime = QDateTime::currentDateTime();
m_endTime = m_startTime.addDays(1);
}
void paintEvent(QPaintEvent *) override
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// 绘制背景
painter.fillRect(rect(), Qt::white);
// 绘制时间刻度
const int hourWidth = width() / 24;
for (int hour = 0; hour <= 24; ++hour) {
const QPoint p1(hour * hourWidth, 0);
const QPoint p2(hour * hourWidth, height());
painter.drawLine(p1, p2);
if (hour == 0 || hour == 24) continue;
const QString text = QString::number(hour);
const QRect textRect(hour * hourWidth - 10, height() / 2 - 10, 20, 20);
painter.drawText(textRect, Qt::AlignCenter, text);
}
// 绘制起始时间和结束时间
const QRect rectStart(0, 0, hourWidth, height());
const QRect rectEnd(width() - hourWidth, 0, hourWidth, height());
painter.drawText(rectStart, Qt::AlignCenter, m_startTime.toString("hh:mm"));
painter.drawText(rectEnd, Qt::AlignCenter, m_endTime.toString("hh:mm"));
}
void mousePressEvent(QMouseEvent *event) override
{
m_dragging = true;
m_dragStart = event->globalPos();
m_startTimeDrag = m_startTime;
m_endTimeDrag = m_endTime;
}
void mouseReleaseEvent(QMouseEvent *) override
{
m_dragging = false;
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (!m_dragging) return;
const int dx = event->globalX() - m_dragStart.x();
// 计算拖动后的时间
const int duration = m_endTimeDrag.toSecsSinceEpoch() - m_startTimeDrag.toSecsSinceEpoch();
const QDateTime newStartTime = m_startTimeDrag.addSecs(dx * 3600 / width() * 3600);
const QDateTime newEndTime = newStartTime.addSecs(duration);
// 检查时间是否超过范围
if (newStartTime < QDateTime::currentDateTime()) {
m_startTime = QDateTime::currentDateTime();
m_endTime = m_startTime.addSecs(duration);
} else if (newEndTime > QDateTime::currentDateTime().addDays(1)) {
m_endTime = QDateTime::currentDateTime().addDays(1);
m_startTime = m_endTime.addSecs(-duration);
} else {
m_startTime = newStartTime;
m_endTime = newEndTime;
}
update();
}
private:
QDateTime m_startTime;
QDateTime m_endTime;
bool m_dragging;
QPoint m_dragStart;
QDateTime m_startTimeDrag;
QDateTime m_endTimeDrag;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TimeAxis widget;
widget.show();
return app.exec();
}
```
在这个示例中,我们使用QDateTime来处理时间变化,并使用QPainter绘制时间轴。在鼠标按下、移动和释放事件中,我们计算拖动后的时间范围,并更新绘制。
阅读全文