Search code examples
pythonpyqtqlistwidget

View textfile in QListWidget, add and remove


I want to be able to add timestamps to a QListWidget instance and save this to a textfile. As well as view the items already in the textfile so the items are saved after program exit.

The code I have at the moment saves it to the list as I want to, but I do not see the items I added before closing and reopening the program:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from datetime import datetime


class feedingTime(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        layout = QVBoxLayout()
        self.feedList = QListWidget()
        self.label = QLabel(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),self)
        self.button = QPushButton("Add time")
        self.info = QLabel("Baby was last fed:")

        layout.addWidget(self.label)
        layout.addWidget(self.button)
        layout.addWidget(self.info)
        layout.addWidget(self.feedList)
        self.setLayout(layout)

        self.timer = QTimer(self.label)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.displayTime)
        self.timer.start()

        self.button.clicked.connect(self.feedAdd)

    def feedAdd(self):
        self.feedList.addItem(self.label.text())

    def displayTime(self):
        self.label.setText(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dialog = feedingTime()
    dialog.show()
    sys.exit(app.exec_())

Is there and easy way to read list from textfile as well as appending new timestamps when button is pressed? It would also be nice to add a button that removes the "oldest" timestamp when clicked.

Im trying to make a brestfeeding app for my wife :)

PyQt noob here. Thanks for the help.


Solution

  • Saving data to a log has nothing to do with PyQt. All you need is basic knowledge of working with I/O in Python. I used simple log file which must be located in same directory as the script does (could be improved to something more sophisticated). I implemented also desired delete button, however, I'm not sure if I correctly understood meaning of "oldest" timestamp.

    import sys
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from datetime import datetime
    
    FILENAME = "history.log"
    
    class feedingTime(QDialog):
        def __init__(self):
            QDialog.__init__(self)
            layout = QVBoxLayout()
            self.feedList = QListWidget()
            self.label = QLabel(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),self)
            self.button = QPushButton("Add time")
            self.info = QLabel("Baby was last fed:")
            self.buttonDelete = QPushButton("Delete oldest")
    
            layout.addWidget(self.label)
            layout.addWidget(self.button)
            layout.addWidget(self.info)
            layout.addWidget(self.feedList)
            layout.addWidget(self.buttonDelete)
            self.setLayout(layout)
    
            self.timer = QTimer(self.label)
            self.timer.setInterval(1000)
            self.timer.timeout.connect(self.displayTime)
            self.timer.start()
    
            self.button.clicked.connect(self.feedAdd)
            self.buttonDelete.clicked.connect(self.deleteOldest)
    
            self.loadOldData()
    
        def deleteOldest(self):
            self.feedList.takeItem(self.feedList.count() - 1)
            lines = open(FILENAME).readlines()
            with open(FILENAME, 'w') as f:
                f.writelines(lines[1:])
    
        def feedAdd(self):
            date = self.label.text()
            self.feedList.addItem(date)
            f = open(FILENAME, 'a')
            f.write(date + '\n')
            f.close()
            self.feedList.sortItems(Qt.DescendingOrder) # change to AscendingOrder if want inverted order
    
        def fillData(self, lines):
            for line in lines:
                self.feedList.addItem(line.rstrip())
    
        def loadOldData(self):
            try:
                file = open(FILENAME)
                lines = file.readlines()
                self.fillData(lines)
            except IOError:
                print "File" + FILENAME + "not found, skipping..."
    
        def displayTime(self):
            self.label.setText(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        dialog = feedingTime()
        dialog.show()
        sys.exit(app.exec_())