Skip to content

Instantly share code, notes, and snippets.

@T31337
Last active December 28, 2024 02:43
Show Gist options
  • Save T31337/f0f050afec74580f2f4b05921ba2ffeb to your computer and use it in GitHub Desktop.
Save T31337/f0f050afec74580f2f4b05921ba2ffeb to your computer and use it in GitHub Desktop.
Simple Python List App Using PySide6
#Simple List In Python Using Pyside6 GUI Library
import sys
import os
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QListWidget, QMessageBox, QFileDialog, QMenu, QSystemTrayIcon
from PySide6.QtCore import Qt, QSize, QFile, QTextStream
from PySide6.QtGui import QPixmap, QIcon
import myResources
class PyListApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("PyList")
self.setFixedSize(350, 550)
self.icon = QIcon()
self.icon.addFile(":icon.png", QSize(32,32), QIcon.Normal, QIcon.Off)
self.pixmap = QPixmap(":icon.png")
self.icon.addPixmap(self.pixmap, QIcon.Normal, QIcon.Off)
self.setWindowIcon(self.icon)
print("Creating menu...")
menu = QMenu()
saveAction = menu.addAction("Save List")
saveAction.triggered.connect(self.saveList)
loadAction = menu.addAction("Load List")
loadAction.triggered.connect(self.loadList)
clearAction = menu.addAction("Clear List")
clearAction.triggered.connect(self.clearList)
quitAction = menu.addAction("Quit")
quitAction.triggered.connect(self.quitApp)
print("Creating tray...")
trayIcon = QSystemTrayIcon(self.icon, app)
trayIcon.setContextMenu(menu)
print("Showing tray...")
trayIcon.show()
trayIcon.setToolTip("PyList!")
#trayIcon.showMessage("PyList", "Thank You For Using PyList!", msecs=5000)
self.txtBox = QLineEdit(self)
self.myList = QListWidget(self)
# Save Button
self.btnSave = QPushButton("Save List", self)
self.btnSave.resize(250, 50)
self.btnSave.move(50, 500)
self.btnSave.clicked.connect(self.saveList)
# Load Button
self.btnLoad = QPushButton("Load List", self)
self.btnLoad.resize(250, 50)
self.btnLoad.move(50, 450)
self.btnLoad.clicked.connect(self.loadList)
# Clear Button
self.btnClear = QPushButton("Clear List", self)
self.btnClear.resize(250, 35)
self.btnClear.move(50, 5)
self.btnClear.clicked.connect(self.clearList)
# Add Button
self.btnAdd = QPushButton("Add Item!", self)
self.btnAdd.resize(250, 50)
self.btnAdd.move(50, 400)
self.btnAdd.clicked.connect(self.btnAddClicked)
# List
self.myList.move(50, 50)
self.myList.resize(250, 300)
self.txtBox.move(50, 360)
self.txtBox.resize(250, 32)
self.myList.itemClicked.connect(self.delItem)
#self.show()
def clearList(self):
self.myList.clear()
def delItem(self, item):
try:
self.myList.takeItem(self.myList.row(item))
except Exception as e:
print(f"Error deleting item: {e}")
def btnAddClicked(self):
item_text = self.txtBox.text()
if item_text:
if self.myList.findItems(item_text, Qt.MatchContains):
print("Item Already Exists In List.")
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Item Already Exists In List.")
msg.setWindowTitle("PyList")
msg.setStandardButtons(QMessageBox.Ok)
msg.exec_()
self.txtBox.clear()
else:
self.myList.addItem(item_text)
self.txtBox.clear()
print(f"Item: {item_text} Added To List!")
self.txtBox.setFocus()
#Load A List From A File
def loadList(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "Load File", "", "List Files (*.lst);;All Files (*)", options=options)
try:
if not file_path:
print("File Does Not Exist!")
QMessageBox.information(self, "PyList", "List File Does Not Exist!")
return
with open(file_path, 'r', encoding='UTF-8') as file:
for line in file:
self.myList.addItem(line.rstrip())
print(f"Item: {line.rstrip()} Loaded From File: {file_path}")
file.close()
print("List Loaded!")
except Exception as e:
print(f"Error loading list: {e}")
QMessageBox.critical(self, "Error", f"Failed to load file: {e}")
#Save List With Custom File Name (For Saving Multiple Lists)
def saveList(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getSaveFileName(self, "Save File", "", "List Files (*.lst);;All Files (*)", options=options)
if file_path is None or file_path == "":
print("Save Aborted")
try:
if not os.path.exists(file_path):
print("File Does Not Exist! Creating a new one.")
with open(file_path, 'w', encoding='UTF-8') as file:
file.write("")
file.close()
with open(file_path, 'w', encoding='UTF-8') as file:
for i in range(self.myList.count()):
line = self.myList.item(i).text()
file.write(line + "\n")
print("List Saved!")
file.close()
self.change_extension(file_path, ".lst")
QMessageBox.information(self, "Success", f"File saved at: {file_path}")
except Exception as e:
if "2" in str(e):
print("File Does Not Exit, User Cancled Saving List")
else:
QMessageBox.critical(self, "Error", f"Failed to save file: {e}")
#Bind Enter Key To Add Item Button
def keyPressEvent(self, event):
if event.key() in (Qt.Key_Return, Qt.Key_Enter):
self.btnAddClicked()
super().keyPressEvent(event)
#Change/Append File Extension To .lst
def change_extension(self, file_path, new_extension):
base_name, _ = os.path.splitext(file_path)
new_file_path = base_name + new_extension
os.rename(file_path, new_file_path)
def quitApp(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Question)
msg.setText("Save List Before Quitting?")
msg.setWindowTitle("PyList")
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msg.setDefaultButton(QMessageBox.No)
msg.buttonClicked.connect(self.quitClicked)
msg.exec_()
def quitClicked(self, button):
print("Button Clicked: ",button.text())
if button.text() == "Yes":
print(f"Saveing List To File: {self.file_path}")
try:
self.saveList()
except Exception as e:
print(f"Error saving list: {e}")
QApplication.quit()
sys.exit()
else:
print("Not Saving List.")
QApplication.quit()
sys.exit()
def test_action(self):
print("Test Action!")
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Test Action OK!")
msg.setWindowTitle("PyList")
msg.setStandardButtons(QMessageBox.Ok)
msg.exec_()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = PyListApp()
window.show()
sys.exit(app.exec())
@T31337
Copy link
Author

T31337 commented Dec 28, 2024

myResources.txt, needs to be converted to RCC file named myResources.py

<RCC version="1.0"> <qresource> <file>icon.png</file> </qresource> </RCC>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment