以下是修改后的代码,请替换掉原来的on_pushButton_history_clicked()函数:
void videoplayer::on_pushButton_history_clicked() {
QString recordPath = "/path/to/record.txt"; // 历史记录文件路径
// 判断历史记录文件是否存在,不存在则创建一个新的文件
if (!QFile::exists(recordPath)) {
QFile file(recordPath);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
file.close();
}
}
// 读取历史记录
QStringList records;
QFile file(recordPath);
if (file.open(QIODevice::ReadOnly)) {
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QString imagePath = line.trimmed();
records << imagePath;
}
file.close();
}
// 打开编辑窗口
bool ok;
QString newName = QInputDialog::getText(this, "编辑历史记录",
"请输入新名称:", QLineEdit::Normal,
records[0], &ok);
if (ok && !newName.isEmpty()) {
records[0] = newName;
// 将修改后的历史记录写入文件
QFile file(recordPath);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QTextStream out(&file);
for (QString& record : records) {
out << record << "\n";
}
file.close();
}
// 初始化QTableWidget窗口
m_tableWidget = new QTableWidget(records.size(), 1, this);
m_tableWidget->setWindowTitle("历史记录");
m_tableWidget->setHorizontalHeaderLabels(QStringList() << "路径");
// 添加数据到表格中
for (int i = 0; i < records.size(); i++) {
QTableWidgetItem* item = new QTableWidgetItem(records[i]);
m_tableWidget->setItem(i, 0, item);
}
m_tableWidget->setVerticalHeaderLabels(QStringList());
m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
m_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
m_tableWidget->setColumnWidth(0, 400);
// 显示窗口
m_tableWidget->show();
}
}