您好,我最近制作了一个应用,下面将向您展示。在pyqt5中,我想将qlistwidget项目保存在txt或数据库文件中,但我不知道该怎么做,而且我想在运行应用程序时在qlistwidget中自动显示保存的qlistwidget项目。我也想从数据库的qlistwidget和qlistwidget中删除选定的项目。请帮我该怎么办,我不知道从哪里开始
我不知道该怎么做
# I am using Pyqt5
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QInputDialog, QLineEdit
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.MW = MainWindow
MainWindow.setObjectName("MainWindow")
MainWindow.resize(288, 267)
MainWindow.setMinimumSize(QtCore.QSize(270, 114))
MainWindow.setMaximumSize(QtCore.QSize(630, 540))
MainWindow.setBaseSize(QtCore.QSize(285, 260))
MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight)
MainWindow.setStyleSheet("QMainWindow{background-color:#6F2232;}")
MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.centralwidget.setStyleSheet("QWidget{background-color:#6F2232;}")
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setContentsMargins(9, 9, -1, -1)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setContentsMargins(0, -1, -1, -1)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(13)
self.listWidget.setFont(font)
self.listWidget.setFocusPolicy(QtCore.Qt.StrongFocus)
self.listWidget.setAutoFillBackground(False)
self.listWidget.setStyleSheet("QListWidget{Background-color:#282828;\n"
"color:#FFFFFF}")
self.listWidget.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.listWidget.setFrameShadow(QtWidgets.QFrame.Sunken)
self.listWidget.setLineWidth(1)
self.listWidget.setModelColumn(0)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 288, 21))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.menubar.sizePolicy().hasHeightForWidth())
self.menubar.setSizePolicy(sizePolicy)
self.menubar.setLayoutDirection(QtCore.Qt.LeftToRight)
self.menubar.setStyleSheet("QMenuBar{background-color:#C3083F;\n"
"color:#FFFFFF}")
self.menubar.setDefaultUp(False)
self.menubar.setNativeMenuBar(True)
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.menuFile.setFont(font)
self.menuFile.setLayoutDirection(QtCore.Qt.LeftToRight)
self.menuFile.setStyleSheet("background-color:#C3083F;\n"
"color:#FFFFFF;")
self.menuFile.setToolTipsVisible(True)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.toolBar.sizePolicy().hasHeightForWidth())
self.toolBar.setSizePolicy(sizePolicy)
self.toolBar.setFocusPolicy(QtCore.Qt.StrongFocus)
self.toolBar.setLayoutDirection(QtCore.Qt.LeftToRight)
self.toolBar.setStyleSheet("QToolBar{background-color:#282828;\n"
"border:#282828;\n"
"padding:2px;}\n")
self.toolBar.setMovable(True)
self.toolBar.setAllowedAreas(QtCore.Qt.AllToolBarAreas)
self.toolBar.setOrientation(QtCore.Qt.Vertical)
self.toolBar.setIconSize(QtCore.QSize(25, 39))
self.toolBar.setFloatable(True)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.LeftToolBarArea, self.toolBar)
self.actionAdd = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\plus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAdd.setIcon(icon)
self.actionAdd.setShortcutContext(QtCore.Qt.WindowShortcut)
self.actionAdd.setAutoRepeat(True)
self.actionAdd.setVisible(True)
self.actionAdd.setMenuRole(QtWidgets.QAction.TextHeuristicRole)
self.actionAdd.setIconVisibleInMenu(True)
self.actionAdd.setShortcutVisibleInContextMenu(False)
self.actionAdd.setObjectName("actionAdd")
self.actionRemove = QtWidgets.QAction(MainWindow)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\minus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionRemove.setIcon(icon1)
self.actionRemove.setAutoRepeat(True)
self.actionRemove.setVisible(True)
self.actionRemove.setIconVisibleInMenu(True)
self.actionRemove.setShortcutVisibleInContextMenu(False)
self.actionRemove.setObjectName("actionRemove")
self.actionUp = QtWidgets.QAction(MainWindow)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\up-arrow (1).png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionUp.setIcon(icon2)
self.actionUp.setAutoRepeat(True)
self.actionUp.setVisible(True)
self.actionUp.setIconVisibleInMenu(True)
self.actionUp.setShortcutVisibleInContextMenu(False)
self.actionUp.setObjectName("actionUp")
self.actionDown = QtWidgets.QAction(MainWindow)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionDown.setIcon(icon3)
self.actionDown.setAutoRepeat(True)
self.actionDown.setVisible(True)
self.actionDown.setIconVisibleInMenu(True)
self.actionDown.setShortcutVisibleInContextMenu(False)
self.actionDown.setObjectName("actionDown")
self.actionSort = QtWidgets.QAction(MainWindow)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(r"C:\Users\User\Desktop\WORK\test\task\sort (1).png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionSort.setIcon(icon4)
self.actionSort.setAutoRepeat(True)
self.actionSort.setVisible(True)
self.actionSort.setIconVisibleInMenu(True)
self.actionSort.setShortcutVisibleInContextMenu(False)
self.actionSort.setObjectName("actionSort")
self.actionNotepad = QtWidgets.QAction(MainWindow)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(":/task/spiral_bound_booklet_64px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionNotepad.setIcon(icon5)
self.actionNotepad.setObjectName("actionNotepad")
self.menuFile.addAction(self.actionAdd)
self.menuFile.addAction(self.actionRemove)
self.menuFile.addAction(self.actionUp)
self.menuFile.addAction(self.actionDown)
self.menuFile.addAction(self.actionSort)
self.menuFile.addAction(self.actionNotepad)
self.menubar.addAction(self.menuFile.menuAction())
self.toolBar.addAction(self.actionAdd)
self.toolBar.addAction(self.actionRemove)
self.toolBar.addAction(self.actionUp)
self.toolBar.addAction(self.actionDown)
self.toolBar.addAction(self.actionSort)
self.actionAdd.triggered.connect(self.actAdd)
self.actionRemove.triggered.connect(self.actRemove)
self.actionUp.triggered.connect(self.actUp)
self.actionDown.triggered.connect(self.actDown)
self.actionSort.triggered.connect(self.actSort)
#self.actionRemove.triggered.connect(self.actEdit)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.actionAdd.setText(_translate("MainWindow", "Add"))
self.actionRemove.setText(_translate("MainWindow", "Remove"))
self.actionUp.setText(_translate("MainWindow", "Up"))
self.actionDown.setText(_translate("MainWindow", "Down"))
self.actionSort.setText(_translate("MainWindow", "Sort"))
self.actionNotepad.setText(_translate("MainWindow", "Notepad"))
#Here when I will trigger this function I want to add item
#qlistwidget and also add what I wrote in database or txt file
#AUTOMATICALLY. I dont know how to do it please help
def actAdd(self):
row = self.listWidget.currentRow()
QInputDialog.setStyleSheet(self.MW,"QInputDialog{background-color:#C3083F;}")
text, ok = QInputDialog.getText(self.MW,"Add","Add Task")
if ok and text is not None:
self.listWidget.insertItem(row,text)
# Here I want to remove qlistwidget item and remove it from database or in
# txt file too
def actRemove(self):
row = self.listWidget.currentRow()
item = self.listWidget.item(row)
if item is None:
return
else:
item = self.listWidget.takeItem(row)
del item
def actUp(self):
row = self.listWidget.currentRow()
if row >=1:
item = self.listWidget.takeItem(row)
self.listWidget.insertItem(row -1, item)
self.listWidget.setCurrentItem(item)
def actDown(self):
row = self.listWidget.currentRow()
if row < self.listWidget.count() -1:
item = self.listWidget.takeItem(row)
self.listWidget.insertItem(row +1, item)
self.listWidget.setCurrentItem(item)
def actSort(self):
self.listWidget.sortItems()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
您不必每次在列表中添加或删除条目时都将数据写入磁盘,而只能在应用程序存在时才将数据写入磁盘。可以通过子类化QMainWindow
并覆盖closeEvent
来实现,如下面的示例所示。在此示例中,数据被保存到save_file.txt
。要在启动窗口时自动读取保存的数据,您可以覆盖MyMainWindow.__init__
,例如
# Ui_MainWindow() as before
class MyMainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.save_file = 'save_file.txt'
self.read_from_file(self.save_file)
def write_to_file(self, file):
try:
list_widget = self.ui.listWidget
entries = '\n'.join(list_widget.item(ii).text() for ii in range(list_widget.count()))
with open(file, 'w') as fout:
fout.write(entries)
except OSError as err:
print(f"file {file} could not be written")
def read_from_file(self, file):
try:
list_widget = self.ui.listWidget
with open(file, 'r') as fin:
entries = [e.strip() for e in fin.readlines()]
list_widget.insertItems(0, entries)
except OSError as err:
with open(file, 'w'):
pass
def closeEvent(self, event):
should_save = QtWidgets.QMessageBox.question(self, "Save data",
"Should the data be saved?",
defaultButton = QtWidgets.QMessageBox.Yes)
if should_save == QtWidgets.QMessageBox.Yes:
self.write_to_file(self.save_file)
return super().closeEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MyMainWindow()
MainWindow.show()
sys.exit(app.exec_())