Backstory:
I'm currently developing a program that has several qComboBox
and qLineEdit
elements that a user can enter data into or select a value. When the user selects "New File" or "Open File" I want to check if any values have changed, and present the user with the option to save their work. The output file is XML.
Problem:
Basically, I just need to know if any of the values are different than the default values. I'm not concerned with what exact values are different, I just need to know that they are different.
I have tried using xmldiff by creating an Element Tree that contains the initial values when the program starts, then comparing that to a second Element Tree with the current values. It does not appear to be capable of just giving a true or false value, and the second Element Tree varies in size so I don't think I can simply do a 1 for 1 comparison.
The second thing I tried was simply setting a boolean value when the element changed, but I couldn't account for an element being reset to a default value. For example if a qLineEdit
box had no value, and a user input something, that would set the boolean value to "true"; however, if they went back in and changed that value back to the default value the result would be "true" as well.
I was wondering if there is a "best practice" for doing this type of thing, or if someone could point me in the right direction. This seems like it should be trivial for the most part, but I don't know how to approach this.
EDIT … Added example for second attempt.
import sys
from PyQt5.QtWidgets import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.modified = False
self.edit1 = QLineEdit()
layout = QGridLayout(self)
layout.addWidget(self.edit1)
self.edit1.editingFinished.connect(self.valueChanged)
def valueChanged(self):
print('valueChanged Event')
self.modified = True
def closeEvent(self, event):
if self.modified:
prompt = QMessageBox.warning(
self, 'Save Changes?',
'This document has been modified.\n'
'Do you want to save these changes?',
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel
)
if prompt == QMessageBox.Yes:
event.accept()
if prompt == QMessageBox.No:
event.accept()
if prompt == QMessageBox.Cancel:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 100)
window.show()
sys.exit(app.exec_())