基于谷歌模型gemini-pro 的开发的QT 对话项目

支持的功能,新建对话框,目前发现相关梯子不支持访问谷歌的api 的可能代理设置的不对,

 QNetworkAccessManager manager;

    // Set up your request
    QNetworkRequest request;
    request.setUrl(QUrl("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=AIz****n_XRciLfpdkgruY"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // Set up your JSON data
    QJsonObject textObj1;
    textObj1["text"] = "写一个故事";

    QJsonObject userRole1;
    userRole1["role"] = "user";
    userRole1["parts"] = QJsonArray() << textObj1;

    QJsonObject textObj2;
    textObj2["text"] = "In the bustling city of Meadow brook, lived a young girl named Sophie. She was a bright and curious soul with an imaginative mind.";

    QJsonObject modelRole;
    modelRole["role"] = "model";
    modelRole["parts"] = QJsonArray() << textObj2;

    QJsonObject textObj3;
    textObj3["text"] = "你用中文写一个故事?";

    QJsonObject userRole2;
    userRole2["role"] = "user";
    userRole2["parts"] = QJsonArray() << textObj3;

    QJsonArray contents;
    contents << userRole1 << modelRole << userRole2;

    QJsonObject mainObj;
    mainObj["contents"] = contents;

    QJsonDocument doc(mainObj);

    // Send the POST request
    QNetworkReply *reply = manager.post(request, doc.toJson());

    // Create an event loop
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

    // Wait until 'finished()' is emitted
    loop.exec();

    // Check the reply
    if (reply->error() == QNetworkReply::NoError) {
        QString strReply = (QString)reply->readAll();

        // Parse the JSON response
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonObject jsonObject = jsonResponse.object();
        QJsonArray candidatesArray = jsonObject["candidates"].toArray();

        // Assume we only want the first candidate
        if (!candidatesArray.isEmpty()) {
            QJsonObject firstCandidate = candidatesArray[0].toObject();
            QJsonObject contentObject = firstCandidate["content"].toObject();
            QJsonArray partsArray = contentObject["parts"].toArray();

            // Assume we only want the text of the first part
            if (!partsArray.isEmpty()) {
                QJsonObject firstPart = partsArray[0].toObject();
                QString text = firstPart["text"].toString();

                qDebug() << "Extracted text: " << text;
            }
        }
    }
    else {
        qDebug() << "Failure" <<reply->errorString();
    }
    delete reply;

重点是QT的SSL :根据QT 的版本下载相关的ssl库

void MainWindow::provideContextMenu(const QPoint &pos) {
    QPoint globalPos = ui->listWidget->mapToGlobal(pos);

    QMenu menu;
    QAction *copyAction = menu.addAction("Copy");
    QAction *selectedItem = menu.exec(globalPos);

    if (selectedItem == copyAction) {
        QList<QListWidgetItem *> items = ui->listWidget->selectedItems();
        QStringList text;
        foreach(QListWidgetItem *item, items) {
            text.append(item->text());
        }
        QApplication::clipboard()->setText(text.join("\n"));
    }
}
void MainWindow::initializeChatSaveFile() {
    // 确保存储目录存在
      QString storeDirectory = "store";
      QDir dir(storeDirectory);
      if (!dir.exists()) {
          dir.mkpath("."); // 如果不存在,则创建目录
      }

      // 获取目录下所有的 txt 文件
      QStringList chatFiles = dir.entryList(QStringList() << "chat_*.txt", QDir::Files, QDir::Name);

      if (!chatFiles.isEmpty()) {
          // 如果至少存在一个文件,则读取第一个文件
          currentChatFileName = storeDirectory + "/" + chatFiles.first();
      } else {
          // 如果不存在任何文件,则创建一个新文件
          currentChatFileName = storeDirectory + "/chat_1.txt";
          QFile file(currentChatFileName);
          file.open(QIODevice::WriteOnly); // 创建新文件
          file.close();
      }
}

void MainWindow::saveChatAutomatically() {
    QFile file(currentChatFileName);
        if (!file.open(QIODevice::Append | QIODevice::Text)) {
            // 如果文件不能被打开,显示一个错误消息框
            QMessageBox::information(this, tr("Unable to open file"), file.errorString());
            return;
        }

        QTextStream out(&file);
        for (int i = 0; i < ui->listWidget->count(); ++i) {
            QListWidgetItem *item = ui->listWidget->item(i);
            out << item->text() << "\n"; // 写入每一行文本及一个换行符
        }

        file.close(); // 关闭文件
}
void MainWindow::showContextMenu(const QPoint &pos) {
    QPoint globalPos = ui->listView->mapToGlobal(pos);
       QMenu menu;

       QModelIndex index = ui->listView->indexAt(pos);
       if (index.isValid()) {
           // 如果点击的是有效项,则显示删除选项
           QAction *deleteAction = menu.addAction("删除对话");
           connect(deleteAction, &QAction::triggered, this, &MainWindow::deleteSelectedItem);
       } else {
           // 如果点击的是空白区域,则显示新建选项
           QAction *newAction = menu.addAction("添加新的对话");
           connect(newAction, &QAction::triggered, this, &MainWindow::createNewFile);
       }

       menu.exec(globalPos);
}

void MainWindow::deleteSelectedItem() {
    QModelIndex index = ui->listView->currentIndex();
    if (index.isValid()) {
        // 删除模型中的项
        model->removeRow(index.row());

        // 可选: 删除对应的文件
        QString fileName = model->itemFromIndex(index)->text();
        QFile::remove("store/" + fileName);
    }
}
void MainWindow::createNewFile() {
    // 获取下一个文件编号
       int fileNumber = 1;
       QString fileName;
       do {
           fileName = QString("store/chat_%1.txt").arg(fileNumber++);
       } while (QFile::exists(fileName));

       QFile file(fileName);
       if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
           // 错误处理,无法创建文件
           qDebug() << "Unable to create the file:" << fileName;
           return;
       }
       file.close();

       // 更新当前聊天文件名
       currentChatFileName = fileName;

       // 添加新项到ListView
       QStandardItem *item = new QStandardItem(QFileInfo(file).fileName());
       model->appendRow(item);

       // 选中并滚动到新创建的文件
       QModelIndex index = model->indexFromItem(item);
       ui->listView->setCurrentIndex(index);
       ui->listView->scrollTo(index);

       // 清空或加载新文件的内容到 QListWidget
       loadChatContent(); // 假设这个函数会清空当前内容并加载新文件的内容
}
void MainWindow::onFileDoubleClicked(const QModelIndex &index) {
    if (!index.isValid()) return;

    QString fileName = model->itemFromIndex(index)->text();
    currentChatFileName = "store/" + fileName; // 更新当前聊天文件名
    loadChatContent(); // 加载对应的聊天内容
}

完整版本代码,评论区留言邮箱发给你们(免费)

后续也会上传到github 上进行开源

想要获取直接运行版本的也可以直接留言私信我。

相关推荐
bug菌¹1 分钟前
滚雪球学Oracle[2.5讲]:数据库初始化配置
数据库·oracle·数据库初始化·初始化配置
一休哥助手9 分钟前
Redis 五种数据类型及底层数据结构详解
数据结构·数据库·redis
落落落sss12 分钟前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
翔云12345617 分钟前
MVCC(多版本并发控制)
数据库·mysql
简单.is.good30 分钟前
【测试】接口测试与接口自动化
开发语言·python
代码敲上天.33 分钟前
数据库语句优化
android·数据库·adb
Yvemil71 小时前
MQ 架构设计原理与消息中间件详解(二)
开发语言·后端·ruby
盒马盒马1 小时前
Redis:zset类型
数据库·redis
程序员是干活的1 小时前
私家车开车回家过节会发生什么事情
java·开发语言·软件构建·1024程序员节
静听山水1 小时前
mysql语句执行过程
数据库·mysql