vtabwidget.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <QtWidgets>
  2. #include <QtDebug>
  3. #include "vtabwidget.h"
  4. #include "vedit.h"
  5. VTabWidget::VTabWidget(const QString &welcomePageUrl, QWidget *parent)
  6. : QTabWidget(parent), welcomePageUrl(welcomePageUrl)
  7. {
  8. setTabsClosable(true);
  9. connect(tabBar(), &QTabBar::tabCloseRequested,
  10. this, &VTabWidget::handleTabCloseRequest);
  11. openWelcomePage();
  12. }
  13. void VTabWidget::openWelcomePage()
  14. {
  15. int idx = openFileInTab(welcomePageUrl, "");
  16. setTabText(idx, "Welcome to VNote");
  17. setTabToolTip(idx, "VNote");
  18. }
  19. int VTabWidget::insertTabWithData(int index, QWidget *page, const QString &label,
  20. const QJsonObject &tabData)
  21. {
  22. int idx = insertTab(index, page, label);
  23. QTabBar *tabs = tabBar();
  24. tabs->setTabData(idx, tabData);
  25. Q_ASSERT(tabs->tabText(idx) == label);
  26. return idx;
  27. }
  28. int VTabWidget::appendTabWithData(QWidget *page, const QString &label, const QJsonObject &tabData)
  29. {
  30. return insertTabWithData(count(), page, label, tabData);
  31. }
  32. void VTabWidget::openFile(QJsonObject fileJson)
  33. {
  34. if (fileJson.isEmpty()) {
  35. return;
  36. }
  37. qDebug() << "open file:" << fileJson;
  38. QString path = fileJson["path"].toString();
  39. QString name = fileJson["name"].toString();
  40. // Find if it has been opened already
  41. int idx = findTabByFile(path, name);
  42. if (idx > -1) {
  43. setCurrentIndex(idx);
  44. return;
  45. }
  46. idx = openFileInTab(path, name);
  47. setCurrentIndex(idx);
  48. }
  49. int VTabWidget::openFileInTab(const QString &path, const QString &name)
  50. {
  51. VEdit *edit = new VEdit(path, name);
  52. QJsonObject tabJson;
  53. tabJson["path"] = path;
  54. tabJson["name"] = name;
  55. int idx = appendTabWithData(edit, name, tabJson);
  56. setTabToolTip(idx, path);
  57. return idx;
  58. }
  59. int VTabWidget::findTabByFile(const QString &path, const QString &name)
  60. {
  61. QTabBar *tabs = tabBar();
  62. int nrTabs = tabs->count();
  63. for (int i = 0; i < nrTabs; ++i) {
  64. QJsonObject tabJson = tabs->tabData(i).toJsonObject();
  65. if (tabJson["name"] == name && tabJson["path"] == path) {
  66. return i;
  67. }
  68. }
  69. return -1;
  70. }
  71. void VTabWidget::handleTabCloseRequest(int index)
  72. {
  73. qDebug() << "request closing tab" << index;
  74. VEdit *edit = dynamic_cast<VEdit *>(widget(index));
  75. bool ok = edit->requestClose();
  76. if (ok) {
  77. removeTab(index);
  78. delete edit;
  79. }
  80. }