Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Developing a code difference widget



  • I want to make a widget that shows the differences between code like this:
    https://github.com/Fuchsiaff/PyPad/commit/c089a1110d7f8064f1f2ef3fc1008efeb8b36f45?diff=split

    I have a widget that has 2 QTextEdit widgets inside it aligned horizontally using QHBoxLayout.

    Now here comes the problem ( I am sorry if it's not really related to Qt5) the code I have right now is something like this:

     if f1_line != f2_line:
                    # If a line does not exist on file2 then mark the output with + sign
                    if f2_line == '' and f1_line != '':
                        self.textArea.append("<p style=\" color: #008000\">~~+ Line-{} {}".format(line_no, f1_line))
                    # otherwise output the line on file1 and mark it with > sign
                    elif f1_line != '':
                        self.textArea.append("<p style=\" color: #008000\">~~ Line-{} {}".format(line_no, f1_line))
    
                    # If a line does not exist on file1 then mark the output with + sign
                    if f1_line == '' and f2_line != '':
                        self.textArea.append("<p style=\" color: #ff0000\">==+Line-{} {}".format(line_no, f2_line))
                    # otherwise output the line on file2 and mark it with < sign
                    elif f2_line != '':
                        self.textArea.append("<p style=\" color: #ff0000\">== Line-{} {}".format(line_no, f2_line))
    
                    # Print a blank line
    
                    self.textArea.append("\n")
    

    It shows the differences between the files but it also accounts for whitespaces so if file1 is

    import sys
    
    sys.exit()
    

    and file2 is

    import sys
    sys.exit()
    

    Then the output of the code is this:

    Comparing files 
    ~~ test1.py 
    == test2.py
    
    
    ==+Line-2 sys.exit()
    
    
    ~~+ Line-3 sys.exit()
    
    

    But the way GitHub's code difference looks better and I'm just wondering how do I proceed to achieve something like they have.


  • Lifetime Qt Champion

    Hi @Fuchsiaff,

    you should look up e.g. https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/

    But there are plenty of ready-made diff tools, maybe you can just use one to generate the diff for your?

    If the files are under version control, you could ask the VCS for the difference, for example.

    Regards



  • @aha_1980

    Every time I try to google for said ready-made tools, I always find websites but no github projects. Do you happen to know any?


  • Lifetime Qt Champion

    Hi @Fuchsiaff

    How about meld? It uses the wrong framework (GNOME) but is written in Python.

    You can also look up the diff page in Wikipedia.


Log in to reply