Home > other >  Qt show the differences between texts
Qt show the differences between texts

Time:10-12

I am beginner in C and Qt. I want to create (using Qt C ) a text compare application which can choose two text files and display and highlight difference between them (or at least in one of them). I have already added to the application the ability to select files, read them and display text in QTextEdit. I also studied a little about Myers' diff algorithm, but i have no idea how to show differences.
How I can display differences like WinMerge do ?

CodePudding user response:

In the following snippet I assume you keep your text edit in textEdit variable. And I assume that each individual text difference is kept in DiffEntry struct as defined below, all of them are kept in iterable diffEntries container (vector, list, ... they do not need to be sorted by position). Your responsibility is to fill this container in diff algorithm.


// this is a struct which keeps information about each difference in text which should be highlighted
struct DiffEntry
{
  int pos = -1;
  int length = -1;
  QColor background;
  QColor foreground;
};

// and this is the code which does the actual formatting

QList<QTextEdit::ExtraSelection> extraSelections;

for (auto diffEntry : diffEntries)
{
  QTextCursor textCursor = QTextCursor(textEdit->document());
  textCursor.setPosition(diffEntry.pos);
  textCursor.setPosition(diffEntry.pos   diffEntry.length, QTextCursor::KeepAnchor);
  auto extraSelection = QTextEdit::ExtraSelection();
  extraSelection.cursor = textCursor;
  extraSelection.format.setBackground( diffEntry.background );
  extraSelection.format.setForeground( diffEntry.foreground );
  extraSelections.append( extraSelection );
}

textEdit->setExtraSelections(extraSelections);

Of course I have not tested the code, but I think it can give you some hints how to implement the formatting.

CodePudding user response:

KDE has an application for this: https://github.com/KDE/kdiff3

  • Related