-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschedulewidget.cpp
More file actions
421 lines (362 loc) · 14.2 KB
/
Copy pathschedulewidget.cpp
File metadata and controls
421 lines (362 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include "schedulewidget.h"
#include "ui_schedulewidget.h"
#include <QTableWidget>
#include <QComboBox>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QSqlQuery>
#include <QMessageBox>
#include <QFormLayout>
#include <QTimeEdit>
#include <QSqlError>
#include <QTableWidgetItem>
/// <summary>
/// 输入日期,来计算日期对应的周数
/// </summary>
int customWeekNumber(const QDate& date)
{
// 获取当前日期所在年份的1月1日的日期
QDate startOfYear(date.year(),1,1);
// 获取日期(startOfYear)对应星期几
int dayOfWeek = startOfYear.dayOfWeek();
// 根据输入日期,计算从年份第一天到该日期的天数差
int days = startOfYear.daysTo(date);
// 核心计算逻辑:
// 1. (days + dayOfWeek - 1):将天数偏移,使年份第一天所在的周从"周数计算起点"开始
// 2. 除以7得到完整的周数(整数除法)
// 3. 加1是因为周数从1开始计数(而非0)
int week = ( days + dayOfWeek - 1 ) / 7 + 1;
return week;
}
Schedulewidget::Schedulewidget(QWidget* parent)
: QWidget(parent)
,ui(new Ui::Schedulewidget())
{
ui->setupUi(this);
setupUI();
int currentYear = QDate::currentDate().year();
int currentWeek = customWeekNumber(QDate::currentDate());
yearComboBox->setCurrentText(QString::number(currentYear));
weekComboBox->setCurrentText(QString("第 %1 周").arg(currentWeek));
loadSchedule();
}
Schedulewidget::~Schedulewidget()
{
delete ui;
}
void Schedulewidget::setupUI()
{
QVBoxLayout* mainLayout = new QVBoxLayout(this);//总体容器用-垂直布局
QHBoxLayout* dateLayout = new QHBoxLayout();//第一个水平布局,放年份和周数选择
yearComboBox = new QComboBox(this);
weekComboBox = new QComboBox(this);
int currentYear = QDate::currentDate().year();//获取当前年份
for ( int year = 2020; year <= currentYear + 5; ++year )
yearComboBox->addItem(QString::number(year),year);
for ( int week = 1; week <= 52; ++week )
weekComboBox->addItem(QString("第 %1 周").arg(week),week);
// 起始日期标签
dateRangeLabel = new QLabel(this);
dateLayout->addWidget(new QLabel("年份:",this));
dateLayout->addWidget(yearComboBox);
dateLayout->addWidget(new QLabel("周数:",this));
dateLayout->addWidget(weekComboBox);
dateLayout->addWidget(dateRangeLabel);
dateLayout->addStretch();
//第二个水平布局
tableWidget = new QTableWidget(this);
tableWidget->setAlternatingRowColors(true);//设置交替行颜色
tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);//单选模式
//对整个tableWidget进行初始化设置
setupTable();
//第三个水平布局
// 添加周导航按钮
QPushButton* prevWeekBtn = new QPushButton("上一周",this);
QPushButton* nextWeekBtn = new QPushButton("下一周",this);
prevWeekBtn->setFixedWidth(200);
nextWeekBtn->setFixedWidth(200);
addButton = new QPushButton("添加课程",this);
deleteButton = new QPushButton("删除课程",this);
addButton->setFixedWidth(200);
deleteButton->setFixedWidth(200);
connect(yearComboBox,QOverload<int>::of(&QComboBox::currentIndexChanged),this,&Schedulewidget::loadSchedule);
connect(weekComboBox,QOverload<int>::of(&QComboBox::currentIndexChanged),this,&Schedulewidget::loadSchedule);
connect(addButton,&QPushButton::clicked,this,&Schedulewidget::addCourse);
connect(deleteButton,&QPushButton::clicked,this,&Schedulewidget::deleteCourse);
connect(prevWeekBtn,&QPushButton::clicked,this,&Schedulewidget::showPreviousWeek);
connect(nextWeekBtn,&QPushButton::clicked,this,&Schedulewidget::showNextWeek);
connect(tableWidget,&QTableWidget::itemChanged,this,&Schedulewidget::handleItemChanged);
QHBoxLayout* buttonLayout = new QHBoxLayout();
buttonLayout->addStretch();
buttonLayout->addWidget(prevWeekBtn);
buttonLayout->addWidget(nextWeekBtn);
buttonLayout->addWidget(addButton);
buttonLayout->addWidget(deleteButton);
buttonLayout->addStretch();
//将三个水平布局添加到主垂直布局中
mainLayout->addLayout(dateLayout);
mainLayout->addWidget(tableWidget);
mainLayout->addLayout(buttonLayout);
// mainLayout设置为当前窗口的布局
setLayout(mainLayout);
}
void Schedulewidget::setupTable()
{
QStringList days = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};//垂直标题
times = {"上午1","上午2","下午1","下午2","晚上1","晚上2"};//水平标题
tableWidget->setRowCount(days.count());//设置行数
tableWidget->setColumnCount(times.count());//设置列数
int year = yearComboBox->currentData().toInt();
int week = weekComboBox->currentData().toInt();
QPair<QDate,QDate> weekRange = getWeekRange(year,week);
QDate startDate = weekRange.first;
QStringList verticalHeaders;// 用于存储带日期的行标题
for ( int i = 0; i < days.count(); ++i )
{
QDate currentDate = startDate.addDays(i);
verticalHeaders.append(QString("%1\n%2").arg(days[i]).arg(currentDate.toString("MM/dd")));
}
tableWidget->setVerticalHeaderLabels(verticalHeaders);
tableWidget->setHorizontalHeaderLabels(times);
tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
}
/**
* @brief 获取指定年份和周数对应的周日期范围(周一至周日)
* @param year 目标年份
* @param week 目标周数(从1开始计数)
* @return 包含该周起始日期(周一)和结束日期(周日)的QPair
*/
QPair<QDate,QDate> Schedulewidget::getWeekRange(int year,int week)
{
QDate startDate(year,1,1);
// 计算需要向前调整的天数,使日期定位到当年第一个周一(或上一年的最后一个周一)
// Qt中:Qt::Monday=1,dayOfWeek()返回1-7(1=周一,7=周日)
// 例如:若1月1日是周三(dayOfWeek=3),则3-1=2,需向前减2天到周一
int daysToSubtract = startDate.dayOfWeek() - Qt::Monday;
// 若调整天数为正数(即1月1日不是周一),则向前调整到最近的周一
// 若1月1日是周一(daysToSubtract=0),则不调整
if ( daysToSubtract > 0 )//不是周一
startDate = startDate.addDays(-daysToSubtract);
// 计算目标周的起始日期(周一):以第一个周一为基准,加上(周数-1)*7天
QDate weekStart = startDate.addDays(( week - 1 ) * 7);
// 计算目标周的结束日期(周日):起始日期加6天(周一+6天=周日)
QDate weekEnd = weekStart.addDays(6);
// 返回该周的周一和周日组成的日期对
return qMakePair(weekStart,weekEnd);
}
void Schedulewidget::loadSchedule()
{
tableWidget->blockSignals(true);//防止加载数据时触发itemChanged信号
tableWidget->clearContents();//清空表格内容
int year = yearComboBox->currentData().toInt();//获取当前选择的年份
int week = weekComboBox->currentData().toInt();//获取当前选择的周数
QPair<QDate,QDate> weekRange = getWeekRange(year,week);//获取该周的日期范围
QDate startDate = weekRange.first;//周一 日期
QDate endDate = weekRange.second;//星期天 日期
dateRangeLabel->setText(startDate.toString("yyyy-MM-dd") + "到" + endDate.toString("yyyy-MM-dd"));
QVector<QVector<QString>> courses(7,QVector<QString>(times.count(),""));
QSqlQuery query;
query.prepare("SELECT date, time, course_name FROM schedule WHERE date BETWEEN ? AND ?");
query.addBindValue(startDate.toString("yyyy-MM-dd"));
query.addBindValue(endDate.toString("yyyy-MM-dd"));
if ( query.exec() )
{
while ( query.next() )
{
QDate date = QDate::fromString(query.value(0).toString(),"yyyy-MM-dd");
QString time = query.value(1).toString();
int dayIndex = startDate.daysTo(date);
int timeIndex = times.indexOf(time);
if ( dayIndex >= 0 && dayIndex < 7 && timeIndex != -1 )
{
courses[dayIndex][timeIndex] = query.value(2).toString();
}
}
}
for ( int day = 0; day < 7; ++day )
{
for ( int time = 0; time < times.count(); ++time )//6列
{
QTableWidgetItem* item = new QTableWidgetItem(courses[day][time]);
item->setTextAlignment(Qt::AlignCenter);
tableWidget->setItem(day,time,item);
}
}
tableWidget->blockSignals(false);
}
void Schedulewidget::addCourse()
{
int dayIndex = tableWidget->currentRow();
int timeIndex = tableWidget->currentColumn();
if ( dayIndex == -1 || timeIndex == -1 )
{ // 验证选中位置有效性
QMessageBox::warning(this,"错误","请先选择一个时间段!");
return;
}
// 检查时间段是否被占用
if ( !tableWidget->item(dayIndex,timeIndex)->text().isEmpty() )
{
QMessageBox::warning(this,"错误","该时间段已被占用!");
return;
}
QDialog dialog(this);// 创建自定义对话框
dialog.setWindowTitle("添加课程");
QFormLayout layout(&dialog);//布局控件有一行行添加控件的功能
QComboBox nameCombo;// 学生姓名下拉框
QSqlQuery nameQuery("SELECT name FROM studentInfo");
while ( nameQuery.next() )
nameCombo.addItem(nameQuery.value(0).toString());
// 时间映射表:列索引 -> 默认时间
QMap<int,QTime> timePresets = {// 上午1到晚上2
{0,QTime(9,0)},{1,QTime(11,0)},{2,QTime(14,0)},
{3,QTime(16,0)},{4,QTime(19,0)},{5,QTime(21,0)}
};
QTimeEdit timeEdit;// 时间选择控件
timeEdit.setDisplayFormat("HH:mm");
timeEdit.setTime(timePresets.value(timeIndex)); // 设置列对应默认时间
layout.addRow("学生姓名:",&nameCombo);//UI布局添加学生姓名
layout.addRow("课程时间:",&timeEdit);//UI布局添加课程时间
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
buttons.button(QDialogButtonBox::Ok)->setText("确定");
buttons.button(QDialogButtonBox::Cancel)->setText("取消");
layout.addRow(&buttons);
connect(&buttons,&QDialogButtonBox::accepted,&dialog,&QDialog::accept);//点击确定
connect(&buttons,&QDialogButtonBox::rejected,&dialog,&QDialog::reject);//点击取消
if ( dialog.exec() != QDialog::Accepted )
return;
// 生成组合字符串
QString courseName = QString("%1,%2").arg(nameCombo.currentText())
.arg(timeEdit.time().toString("HH:mm"));
// 获取日期信息
int year = yearComboBox->currentData().toInt();
int week = weekComboBox->currentData().toInt();
QPair<QDate,QDate> weekRange = getWeekRange(year,week);
QDate currentDate = weekRange.first.addDays(dayIndex);
QString timeSlot = times[timeIndex]; // 原始时间段标识(如"上午1")
// 数据库操作
QSqlQuery query;
query.prepare("INSERT INTO schedule (date, time, course_name) VALUES (?, ?, ?)");
query.addBindValue(currentDate.toString("yyyy-MM-dd"));
query.addBindValue(timeSlot); // 存储原始时间段标识
query.addBindValue(courseName); // 存储"姓名,HH:mm"格式
if ( !query.exec() )
QMessageBox::critical(this,"错误","添加失败:" + query.lastError().text());
else loadSchedule(); // 刷新显示
}
void Schedulewidget::handleItemChanged(QTableWidgetItem* item)
{
int day = item->row();
int timeSlot = item->column();
QString newCourse = item->text().trimmed();
int year = yearComboBox->currentData().toInt();
int week = weekComboBox->currentData().toInt();
QPair<QDate,QDate> weekRange = getWeekRange(year,week);
QDate date = weekRange.first.addDays(day);// 获取日期
QString time = times[timeSlot];// 获取时段
QSqlQuery query;
if ( newCourse.isEmpty() )// 如果选的为空,删除课程
{
query.prepare("DELETE FROM schedule WHERE date = ? AND time = ?");
query.addBindValue(date.toString("yyyy-MM-dd"));
query.addBindValue(time);
}
else // 更新(INSERT)或插入(REPLACE)
{
query.prepare("INSERT OR REPLACE INTO schedule (date, time, course_name) VALUES (?, ?, ?)");
query.addBindValue(date.toString("yyyy-MM-dd"));
query.addBindValue(time);
query.addBindValue(newCourse);
}
if ( !query.exec() )
{
QMessageBox::critical(this,"错误","操作失败:" + query.lastError().text());
loadSchedule(); // 恢复数据
}
}
void Schedulewidget::deleteCourse()
{
// 确认删除操作
QMessageBox confirmBox(this);
confirmBox.setWindowTitle("确认删除");
confirmBox.setText("确定要删除该记录吗?");
// 设置按钮为中文
QPushButton* yesButton = confirmBox.addButton("确定",QMessageBox::YesRole);
QPushButton* noButton = confirmBox.addButton("取消",QMessageBox::NoRole);
// 设置默认按钮为取消
confirmBox.setDefaultButton(noButton);
// 显示对话框并等待用户选择
confirmBox.exec();
if ( confirmBox.clickedButton() == yesButton )
{
int dayIndex = tableWidget->currentRow();
int timeIndex = tableWidget->currentColumn();
if ( dayIndex == -1 || timeIndex == -1 )
{
QMessageBox::warning(this,"错误","请先选择一个时间段!");
return;
}
QTableWidgetItem* item = tableWidget->item(dayIndex,timeIndex);
if ( !item || item->text().isEmpty() )
{
QMessageBox::warning(this,"错误","该时间段没有课程!");
return;
}
int year = yearComboBox->currentData().toInt();
int week = weekComboBox->currentData().toInt();
QPair<QDate,QDate> weekRange = getWeekRange(year,week);
QDate currentDate = weekRange.first.addDays(dayIndex);
QString time = times[timeIndex];
QSqlQuery query;
query.prepare("DELETE FROM schedule WHERE date = ? AND time = ?");
query.addBindValue(currentDate.toString("yyyy-MM-dd"));
query.addBindValue(time);
if ( !query.exec() )
{
QMessageBox::critical(this,"错误","删除失败:" + query.lastError().text());
}
else
{
loadSchedule();
}
}
}
void Schedulewidget::showPreviousWeek()
{
int currentWeek = weekComboBox->currentIndex();
int currentYear = yearComboBox->currentIndex();
if ( currentWeek > 0 )// 不是第一周
{
weekComboBox->setCurrentIndex(currentWeek - 1);
}
else// 是第一周
{
if ( yearComboBox->currentIndex() > 0 )
{
yearComboBox->setCurrentIndex(currentYear - 1);
// 跳转到上一年最后一周(第52周)
weekComboBox->setCurrentIndex(51);
}
}
}
void Schedulewidget::showNextWeek()
{
int currentWeek = weekComboBox->currentIndex();
int currentYear = yearComboBox->currentIndex();
if ( currentWeek < 51 )
{
weekComboBox->setCurrentIndex(currentWeek + 1);
}
else
{
if ( yearComboBox->currentIndex() < yearComboBox->count() - 1 )
{
yearComboBox->setCurrentIndex(currentYear + 1);
weekComboBox->setCurrentIndex(0);
}
}
}