1. Is QTimer the way to get what I want? If so, what is the correct code (Line 2 above is not correct)
Seems reasonable. You need to connect the timeout signal correctly (line 2) and probably make sure that savefile only does something if the "document" is dirty.
2. If QTimer is the way to get what I want, where does the above code go? in the init of the module that contains self.savefile? If not, where?
Create the timer and connect it in the constructor/init.
Start the timer when a "document" is opened and stop it when the "document" is closed.[/LIST]
3. If QTimer is not correct, what is the better way?
You could call savefile() when the "document" is modified and and clear the modified flag when it is saved. This could impose an unacceptable load depending on how modifications occur.
Example opens a document and closes it 5 seconds later, with a save every 2 seconds. App will terminate after 10 seconds.
#!/usr/bin/env python3
import sys
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
self.autosaveTimer.setInterval(2000)
self.autosaveTimer.timeout.connect(self.saveFile)
def openFile(self):
# Open the document
print ("Open...")
self.autosaveTimer.start()
def closeFile(self):
# Close the document
print ("Close...")
self.autosaveTimer.stop()
def saveFile(self):
# Save the document if it is dirty
print ("Saving...")
if __name__ == '__main__':
QTimer.
singleShot(10000, app.
quit)
foo = Foo()
foo.openFile()
QTimer.
singleShot(5000, foo.
closeFile)
app.exec_();
#!/usr/bin/env python3
import sys
from PyQt5.QtCore import QCoreApplication, QObject, QTimer
class Foo(QObject):
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
self.autosaveTimer = QTimer()
self.autosaveTimer.setInterval(2000)
self.autosaveTimer.timeout.connect(self.saveFile)
def openFile(self):
# Open the document
print ("Open...")
self.autosaveTimer.start()
def closeFile(self):
# Close the document
print ("Close...")
self.autosaveTimer.stop()
def saveFile(self):
# Save the document if it is dirty
print ("Saving...")
if __name__ == '__main__':
app = QCoreApplication(sys.argv)
QTimer.singleShot(10000, app.quit)
foo = Foo()
foo.openFile()
QTimer.singleShot(5000, foo.closeFile)
app.exec_();
To copy to clipboard, switch view to plain text mode
Bookmarks