Skip to content

Commit

Permalink
fixed slider and save, working on load
Browse files Browse the repository at this point in the history
  • Loading branch information
KylieGong committed Aug 14, 2023
1 parent 5999da1 commit 93f0d47
Showing 1 changed file with 119 additions and 59 deletions.
178 changes: 119 additions & 59 deletions pyqt.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import os
from PyQt5 import QtCore, QtWidgets
import argparse
import re
import subprocess

class MainWindow(QtWidgets.QMainWindow):

def __init__(self, parameters):
def __init__(self, parameters, param_file):
super(MainWindow, self).__init__()

self.groups = groups
self.groups = parameters
self.radio_groups = []
self.loadFile = None
self.ofile = None
self.saveFile = None
self.contents = None
self.param_file = param_file
self.sliderMultiplier = []

self.initUI()

Expand Down Expand Up @@ -60,19 +62,63 @@ def run(self):
print('run')

def save(self):
self.contents = self.gatherData()
for i in self.contents:
if i['name'] == self.ofile+":":
self.saveFile = ''.join(i['default'])
self.update_and_save(self.inputFile, self.saveFile)
print("saved")
contents = self.gatherData()
# for i in self.contents:
# if i['name'] == self.ofile+":":
# self.saveFile = ''.join(i['default'])
# self.update_and_save(self.inputFile, self.saveFile)
default_file_path = self.param_file + ".key"
file_path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Save File", default_file_path, "All Files (*)")
if file_path:
with open(file_path, "w") as file:
for line in contents:
for key, value in line.items():
file.write(f"{key}{','.join(value)}")
file.write("\n")
print("saved to " + file_path)

def load(self):
# options = QtWidgets.QFileDialog.Options()
# file, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Choose a File", "", "All Files (*)", options=options)
# if file:
# self.close()
# subprocess.call(["python", "pyqt.py", file])
options = QtWidgets.QFileDialog.Options()
file, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Choose a File", "", "All Files (*)", options=options)
load_file = self.param_file +".key" if os.path.exists(self.param_file +".key") else ""
file, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Choose a File", load_file, "All Files (*)", options=options)
#alter the values of each option
if file:
self.close()
subprocess.call(["python", "pyqt.py", file])
#turn the parameters in the file into a dictionary
default_values = {}
with open(file, "r") as f:
for line in f:
label, value = line.strip().split(":")
label = label.split(":")[0]
value = value.split(",") if "," in value else [value]
default_values[label] = value
print(default_values)

#go through the elements in the widget
for elements in range(self.pagelayout.count()):
element = self.pagelayout.itemAt(elements).layout()
if element is not None:
for widget_index in range(element.count()):
widget = element.itemAt(widget_index).widget()

if isinstance(widget, QtWidgets.QLineEdit):
widget.setText(values[0])

elif isinstance(widget, QtWidgets.QRadioButton) or isinstance(widget, QtWidgets.QCheckBox):
if widget.text() == values[0]:
widget.setChecked(True)
values.pop(0)

elif isinstance(widget, QtWidgets.QSlider):
multiplier = self.sliderMultiplier.pop(0)
defaults[key].append(str(widget.value()/multiplier))
self.sliderMultiplier.append(multiplier)



def quit(self):
self.close()
Expand Down Expand Up @@ -157,16 +203,19 @@ def createWidgetsFromGroups(self):

print("slider created")
#creates a horizontal decimal slider
decimals = len(str(options[2]).split('.')[1]) if '.' in str(options[2]) else 0
multiplier = 10**decimals
slider = QtWidgets.QSlider(self)
slider.setOrientation(QtCore.Qt.Horizontal)
slider.setSingleStep(int(float(options[2])*100))
slider.setPageStep(int(float(options[2])*100)) #moves the slider when clicking or up/down
slider.setRange(int(options[0])*100, int(options[1])*100)
slider.setValue(int(float(default_option[0])*100))
slider.setSingleStep(int(float(options[2])*multiplier))
slider.setPageStep(int(float(options[2])*multiplier)) #moves the slider when clicking or up/down
slider.setRange(int(options[0])*multiplier, int(options[1])*multiplier)
slider.setValue(int(float(default_option[0])*multiplier))

label_slider = QtWidgets.QLabel(str(default_option[0]))
slider.valueChanged.connect(lambda value, lbl=label_slider: self.updateLabel(lbl, value))
slider.valueChanged.connect(lambda value, lbl=label_slider: self.updateLabel(lbl, value, multiplier))

self.sliderMultiplier.append(multiplier)
group_layout.addWidget(label_slider)
group_layout.addWidget(slider)
self.pagelayout.addLayout(group_layout)
Expand All @@ -178,8 +227,8 @@ def createWidgetsFromGroups(self):
separator.setFixedHeight(1) # Set a fixed height for the separator
self.pagelayout.addWidget(separator)

def updateLabel(self, label, value):
label.setText(str(value/100))
def updateLabel(self, label, value, multiplier):
label.setText(str(value/multiplier))

def browse(self, gtype, txt):
options = QtWidgets.QFileDialog.Options()
Expand All @@ -195,64 +244,66 @@ def browse(self, gtype, txt):
def gatherData(self):
layout_data = []

for hbox_layout_index in range(1, self.pagelayout.count()):
for hbox_layout_index in range(self.pagelayout.count()):
hbox_layout = self.pagelayout.itemAt(hbox_layout_index).layout()

if hbox_layout is not None:
defaults = {'name': '',
'default':[]}
# defaults = {'name': '',
# 'default':[]}
defaults = {}
key = None

for widget_index in range(hbox_layout.count()):
widget = hbox_layout.itemAt(widget_index).widget()

if widget_index == 0 and isinstance(widget, QtWidgets.QLabel):
defaults['name'] = widget.text()
# defaults['name'] = widget.text()
defaults[widget.text()] = []
key = widget.text()

elif isinstance(widget, QtWidgets.QLineEdit):
defaults['default'].append(widget.text())
defaults[key].append(widget.text())

elif isinstance(widget, QtWidgets.QRadioButton) or isinstance(widget, QtWidgets.QCheckBox):
if widget.isChecked():
defaults['default'].append(widget.text())
defaults[key].append(widget.text())

elif isinstance(widget, QtWidgets.QSlider):
defaults['default'].append(str(widget.value()/100))
multiplier = self.sliderMultiplier.pop(0)
defaults[key].append(str(widget.value()/multiplier))
self.sliderMultiplier.append(multiplier)

layout_data.append(defaults)
return layout_data

def update_and_save(self, input_file_path, output_file_path):
with open(input_file_path, 'r') as input_file:
lines = input_file.readlines()

updated_lines = []
for line in lines:
if '#>' in line:
parts = line.split('=')
if len(parts) == 2:
parts = line.split('=')
if len(parts) == 2:
after = parts[1].split(' ', 1)
updated_line = parts[0]+"="+','.join(self.contents.pop(0)['default'])+after[1]
updated_lines.append(updated_line)
else:
updated_lines.append(line)
else:
updated_lines.append(line)
else:
updated_lines.append(line)

with open(output_file_path, 'w') as output_file:
output_file.writelines(updated_lines)

if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Dynamic GUI Builder")
parser.add_argument("param_file", help="Path to the text file containing parameters")
args = parser.parse_args()

with open(args.param_file, "r") as file:
# def update_and_save(self, filepath):
# with open(input_file_path, 'r') as input_file:
# lines = input_file.readlines()

# updated_lines = []
# for line in lines:
# if '#>' in line:
# parts = line.split('=')
# if len(parts) == 2:
# parts = line.split('=')
# if len(parts) == 2:
# after = parts[1].split(' ', 1)
# updated_line = parts[0]+"="+','.join(self.contents.pop(0)['default'])+after[1]
# updated_lines.append(updated_line)
# else:
# updated_lines.append(line)
# else:
# updated_lines.append(line)
# else:
# updated_lines.append(line)

# with open(output_file_path, 'w') as output_file:
# output_file.writelines(updated_lines)

def parsefile(file):
with open(file, "r") as f:
# content = file.read()
lines = file.readlines()
lines = f.readlines()

groups = []
pattern = r"\s*(\w+)\s*=\s*([^\s#]+)\s*#\s*([^\#]+)\s*#\s*>\s*(\w+)(?:\s+(\S+))?"
Expand All @@ -266,9 +317,18 @@ def update_and_save(self, input_file_path, output_file_path):
help = match.group(3)

groups.append((group_type, group_name, options, default_option, help))

return groups

if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Dynamic GUI Builder")
parser.add_argument("param_file", help="Path to the text file containing parameters")
args = parser.parse_args()

groups = parsefile(args.param_file)

app = QtWidgets.QApplication(sys.argv)
w = MainWindow(groups)
w = MainWindow(groups, args.param_file)
w.inputFile = args.param_file
w.adjustSize() #adjust to fit elements accordingly

Expand Down

0 comments on commit 93f0d47

Please sign in to comment.