fb2tree.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "fb2tree.h"
  2. #include <QTextDocument>
  3. #include <QTextDocumentFragment>
  4. #include <QTextFrame>
  5. Fb2TreeModel::Fb2TreeModel(QTextEdit &text, QObject *parent)
  6. : QAbstractItemModel(parent)
  7. , m_text(text)
  8. {
  9. }
  10. Fb2TreeModel::~Fb2TreeModel()
  11. {
  12. }
  13. int Fb2TreeModel::columnCount(const QModelIndex &parent) const
  14. {
  15. Q_UNUSED(parent);
  16. return 1;
  17. }
  18. QModelIndex Fb2TreeModel::index(int row, int column, const QModelIndex &parent) const
  19. {
  20. void *data = parent.isValid() ? (void*)frame(parent) : NULL;
  21. return createIndex(row, column, data);
  22. }
  23. QModelIndex Fb2TreeModel::parent(const QModelIndex &child) const
  24. {
  25. if (QTextFrame * frame = static_cast<QTextFrame*>(child.internalPointer())) {
  26. if (QTextFrame * parent = frame->parentFrame()) {
  27. int row = 0;
  28. foreach (QTextFrame * f, parent->childFrames()) {
  29. if (f == frame) return createIndex(row, 0, (void*)parent); else row++;
  30. }
  31. }
  32. }
  33. return QModelIndex();
  34. }
  35. int Fb2TreeModel::rowCount(const QModelIndex &parent) const
  36. {
  37. QTextFrame * f = frame(parent);
  38. return f ? f->childFrames().count() : 0;
  39. }
  40. QTextFrame * Fb2TreeModel::frame(const QModelIndex &index) const
  41. {
  42. if (!index.isValid()) {
  43. QTextDocument * doc = m_text.document();
  44. return doc ? doc->rootFrame() : NULL;
  45. }
  46. if (QTextFrame * parent = frame(index.parent())) {
  47. int i = index.row();
  48. foreach (QTextFrame * frame, parent->childFrames()) {
  49. if (i == 0) return frame; else i--;
  50. }
  51. }
  52. return NULL;
  53. }
  54. QVariant Fb2TreeModel::data(const QModelIndex &index, int role) const
  55. {
  56. if (role != Qt::DisplayRole) return QVariant();
  57. if (QTextFrame * f = frame(index)) {
  58. QTextCursor cursor(f);
  59. cursor.setPosition(f->firstPosition(), QTextCursor::MoveAnchor);
  60. cursor.setPosition(f->lastPosition(), QTextCursor::KeepAnchor);
  61. QTextDocumentFragment fragment(cursor);
  62. QString text = fragment.toPlainText();
  63. return text.simplified();
  64. }
  65. return tr("<section>");
  66. }