class ActionList(QWidget): def __init__(self): super().__init__() self.layout = QVBoxLayout() self.actions = [] self.add_button = QPushButton('Add new action') self.layout.addWidget(self.add_button) self.add_button.clicked.connect(self.add_button_click) self.setLayout(self.layout) def add_new_action_row(self): i = len(self.actions) name = 'label_{}'.format(i) action_row = ActionWidget() action_row.setObjectName(name) self.actions.append(action_row) self.layout.addWidget(action_row) self.layout.update() def get_actions(self): composed_actions = [] for action in self.actions: composed_actions.append(action.get_composed_string()) return composed_actions def add_button_click(self): self.add_new_action_row()
class TabLayout(QWidget): def __init__(self, toplabel): super().__init__() ## Get label from ctor args self.label = QLabel(toplabel) ## Create and bind spinbox to update function self.spinbox = QSpinBox() self.spinbox.setMinimum(1) self.spinbox.valueChanged.connect(self.update) ## Keep track of how many elements we have in sublayout 2 self.counter = 1 ## Layouts self.toplayout = QVBoxLayout() self.sublayout1 = QHBoxLayout() self.sublayout2 = QHBoxLayout() ## Build the first line with label and spinbox self.sublayout1.addWidget(self.label) self.sublayout1.addWidget(self.spinbox) ## Build the entity container self.sublayout2.addWidget( EntityData() ) ## Build top level layout self.toplayout.addLayout(self.sublayout1) self.toplayout.addLayout(self.sublayout2) ## Display self.setLayout(self.toplayout) def update(self): if self.spinbox.value() > self.counter: for i in range( 0, self.spinbox.value() - self.counter ): self.sublayout2.addWidget( EntityData() ) elif self.spinbox.value() < self.counter: # Delete all widgets while self.sublayout2.count() > self.spinbox.value(): item = self.sublayout2.takeAt( self.sublayout2.count() - 1 ) if not item: continue w = item.widget() if w: w.setParent(None) # Recreate all widgets #for i in range( 0, self.spinbox.value() ): # self.sublayout2.addWidget( EntityData() ) self.sublayout2.update() self.toplayout.update() self.counter = self.spinbox.value()
class ArnheimStageWidget(BaseWidget): def __init__(self, *args, rep=None, **kwargs) -> None: super().__init__(*args, **kwargs) self.layout = QVBoxLayout(self) self.suggestions = NodeListWidget(title="Fitting Nodes", base=self.base) self.layout.addWidget(self.suggestions) self.layout.update()
class ContextAwareWidget(BaseWidget): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.layout = QVBoxLayout(self) self.suggestions = QLabel("Waiting for suggestions") self.layout.addStretch() self.layout.addWidget(self.suggestions) self.viewer.events.emitters["active_layer"].connect( self.on_active_layer_changed) print("Received here") self.rebuildSuggestions() def replaceSuggestions(self, newWidget: QWidget): self.layout.removeWidget(self.suggestions) self.suggestions.close() self.suggestions = newWidget self.layout.addWidget(self.suggestions) self.layout.update() def rebuildSuggestions(self): if self.viewer.active_layer is not None: if "rep" in self.viewer.active_layer.metadata: #TODO: DO this according to the correct Typename self.replaceSuggestions(ArnheimStageWidget(base=self.base)) else: self.replaceSuggestions( NonArnheimStageWidget(base=self.base, layer=self.viewer.active_layer)) else: self.replaceSuggestions(EmptyStageWidget(base=self.base)) def on_active_layer_changed(self, *args, **kwargs): self.rebuildSuggestions()
class ActionWidget(QWidget): def __init__(self): super().__init__() self.layout = QVBoxLayout() self.layout.setDirection(QVBoxLayout.LeftToRight) self.labels = [] self.avaliable_actions = [ 'Pick action:', 'Pick up:', 'Travel to:', 'Leave cars at:' ] self.set_combobox() self.setLayout(self.layout) def set_combobox(self): self.combobox = QComboBox() for action in self.avaliable_actions: self.combobox.addItem(action) self.layout.addWidget(self.combobox) self.combobox.activated.connect(self.set_labels_by_combobox) def set_labels(self, label_text): if len(self.labels) != 0: self.purge_old_labels() self.update() for i in range(len(label_text)): label_name = 'label_{}'.format(i) label = DropInLabel(label_text[i]) label.setObjectName(label_name) self.labels.append(label) for label in self.labels: self.layout.addWidget(label) self.update() def purge_old_labels(self): for i in reversed(range(self.layout.count())): if i != 0: widgetToRemove = self.layout.itemAt(i).widget() self.layout.removeWidget(widgetToRemove) widgetToRemove.setParent(None) self.labels.clear() self.layout.update() def set_labels_by_combobox(self): if self.combobox.currentText() == 'Pick up:': self.set_labels( ['drop loco here', 'drop wagon here', 'drop station here']) elif self.combobox.currentText() == 'Travel to:': self.set_labels(['drop loco here', 'station from', 'station to']) elif self.combobox.currentText() == 'Leave cars at:': self.set_labels(['drop car here', 'drop station here']) def get_filler_text(self): filler_words = [] if self.combobox.currentText() == 'Pick up:': filler_words = [ 'Locomotive number ', 'pick up wagons ', 'at station ' ] elif self.combobox.currentText() == 'Travel to:': filler_words = [ 'Locomotive number ', 'travel from station ', 'to station ' ] elif self.combobox.currentText() == 'Leave cars at:': filler_words = ['Leave wagons ', 'at station '] return filler_words def get_composed_string(self): composed_string = "" filler_text = self.get_filler_text() i = 0 for label in self.labels: composed_string += filler_text[i] composed_string += label.text() composed_string += " " i += 1 return composed_string
class QTGui: def __init__(self): self.allCenters = [] self.checkedCenters = dict() self.removeAfter = 1000 self.dose = 1 def window(self): try: app = QApplication(sys.argv) window = QWidget() window.setWindowTitle('COWIN Slot Finder') window.setMinimumWidth(1000) window.setMinimumHeight(800) layout = QGridLayout() timer = QTimer() timer.timeout.connect(self.tick) timer.start(100) self.states = QComboBox() for elem in self.stateDict['states']: itemStr = str(elem["state_id"]) + ":" + str(elem["state_name"]) self.states.addItem(itemStr) row = 1 labelState = QLabel("States") labelState.setFont(QFont("Times", weight=QFont.Bold)) labelDist = QLabel("Districts") labelDist.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelState, row, 1, 1, 2) layout.addWidget(labelDist, row, 4, 1, 2) row += 1 self.states.currentIndexChanged.connect(self.stateSelectionchange) layout.addWidget(self.states, row, 1, 1, 2) self.districts = QComboBox() self.districts.currentIndexChanged.connect(self.districtSelectionchange) layout.addWidget(self.districts, row, 4, 1, 2) row += 1 self.searchBox = QLineEdit() self.searchBox.setPlaceholderText("Search...") self.searchBox.textChanged.connect(self.textChanged) layout.addWidget(self.searchBox, row, 1, 1, 3) labelDose = QLabel("Select Dose:") # labelDose.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelDose, row, 4, 1, 1) radiobutton = QRadioButton("Dose 1") radiobutton.setChecked(True) radiobutton.dose = 1 radiobutton.toggled.connect(lambda: self.onSelectRadio(radiobutton)) layout.addWidget(radiobutton, row, 5, 1, 1) radiobutton2 = QRadioButton("Dose 2") radiobutton2.setChecked(False) radiobutton2.dose = 2 radiobutton2.toggled.connect(lambda: self.onSelectRadio(radiobutton2)) layout.addWidget(radiobutton2, row, 6, 1, 1) row += 1 labelCenter = QLabel("Available Centers") labelCenter.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelCenter, row, 1, 1, 3) labelSelect = QLabel("Selected Centers") labelSelect.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelSelect, row, 4, 1, 3) row += 1 self.selectAllChk = QCheckBox("Select All") self.selectAllChk.stateChanged.connect(lambda: self.selectAll(self.selectAllChk)) layout.addWidget(self.selectAllChk, row, 1, 1, 3) row += 1 self.centreLayout = QVBoxLayout() self.checks = [] widget = QWidget() widget.setLayout(self.centreLayout) # Scroll Area Properties scroll = QScrollArea() # scroll.setFrameShape(frame) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(True) scroll.setWidget(widget) layout.addWidget(scroll, row, 1, 1, 3) self.selectedLayout = QVBoxLayout() widget2 = QWidget() widget2.setLayout(self.selectedLayout) # Scroll Area Properties scroll2 = QScrollArea() # scroll.setFrameShape(frame) scroll2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # scroll2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll2.setWidgetResizable(True) scroll2.setWidget(widget2) layout.addWidget(scroll2, row, 4, 1, 3) row += 1 self.button1 = QPushButton() self.button1.setText("Run Slot Notifier") self.button1.clicked.connect(self.runService) layout.addWidget(self.button1, row, 3, 1, 2) self.buttonClear = QPushButton() self.buttonClear.setText("Clear") self.buttonClear.clicked.connect(self.clearSelections) layout.addWidget(self.buttonClear, row, 6, 1, 1) row += 1 self.button2 = QPushButton() self.button2.setText("Stop Slot Notifier") self.button2.clicked.connect(self.stopService) layout.addWidget(self.button2, row, 3, 1, 2) row += 1 self.msgLayout = QVBoxLayout() widget3 = QWidget() widget3.setLayout(self.msgLayout) # Scroll Area Properties self.scroll3 = QScrollArea() # scroll.setFrameShape(frame) self.scroll3.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # scroll3.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scroll3.setWidgetResizable(True) self.scroll3.setWidget(widget3) layout.addWidget(self.scroll3, row, 1, 1, 6) row += 1 app.aboutToQuit.connect(self.closeEvent) window.setLayout(layout) window.show() sys.exit(app.exec_()) except BaseException as e: raise def stateSelectionchange(self, i): currentState = self.states.currentText() # print("Current index", i, "selection changed ", currentState) state_id = currentState[:currentState.index(":")] # print(state_id) distResp = self.getters.getDistricts(state_id) # print(distResp) self.districts.clear() for elem in distResp['districts']: itemStr = str(elem["district_id"]) + ":" + str(elem["district_name"]) self.districts.addItem(itemStr) self.districts.update() def districtSelectionchange(self, i): if i == -1: return currentDist = self.districts.currentText() # print("Current index", i, "selection changed ", currentDist) self.dist_id = currentDist[:currentDist.index(":")] # print(self.dist_id) curr_date = datetime.datetime.now().strftime("%d-%m-%Y") calendar = self.getters.getCalendarByDistrict(self.dist_id, curr_date) # print(calendar['centers']) for i in reversed(range(self.centreLayout.count())): widgetToRemove = self.centreLayout.itemAt(i).widget() # remove it from the layout list self.centreLayout.removeWidget(widgetToRemove) # remove it from the gui widgetToRemove.setParent(None) self.allCenters = [] self.checks = [] self.searchBox.setText("") anyUnchecked = False for elem in calendar['centers']: label = str(elem["center_id"]) + ":" + elem["name"] + "," + elem["address"] + "," + str(elem["pincode"]) self.allCenters.append(label) c = QCheckBox(label) self.centreLayout.addWidget(c) if label in self.checkedCenters.keys(): c.setChecked(True) else: anyUnchecked = True c.stateChanged.connect(self.selectionStateChanged) self.checks.append(c) self.centreLayout.update() self.selectAllChk.blockSignals(True) self.selectAllChk.setChecked(not anyUnchecked) self.selectAllChk.blockSignals(False) def selectionStateChanged(self, int): for elem in self.checks: if elem.isChecked() and elem.text() not in self.checkedCenters.keys(): self.checkedCenters[elem.text()] = self.dist_id if not elem.isChecked() and elem.text() in self.checkedCenters.keys(): del self.checkedCenters[elem.text()] # print(self.checkedCenters) for i in reversed(range(self.selectedLayout.count())): widgetToRemove = self.selectedLayout.itemAt(i).widget() # remove it from the layout list self.selectedLayout.removeWidget(widgetToRemove) # remove it from the gui widgetToRemove.setParent(None) for elem in self.checkedCenters.keys(): c = QLabel(elem) self.selectedLayout.addWidget(c) self.selectedLayout.update() def runService(self): MsgPass.MsgPass.runstatus = True slotNotifier = SlotNotifier.SlotNotifier() centers = copy.deepcopy(self.checkedCenters) t1 = threading.Thread(target=slotNotifier.runService, args=(centers, self.dose,)) t1.start() def stopService(self): MsgPass.MsgPass.runstatus = False def tick(self): if MsgPass.MsgPass.runstatus == False: self.button2.setEnabled(False) else: self.button2.setEnabled(True) if MsgPass.MsgPass.threadrunning == True: self.button1.setEnabled(False) else: self.button1.setEnabled(True) while len(MsgPass.MsgPass.msgQ) > 0: c = QLabel(MsgPass.MsgPass.msgQ.pop()) self.msgLayout.addWidget(c) if self.msgLayout.count() > self.removeAfter: for i in range(self.msgLayout.count() - self.removeAfter): widgetToRemove = self.msgLayout.itemAt(i).widget() # remove it from the layout list self.msgLayout.removeWidget(widgetToRemove) # remove it from the gui widgetToRemove.setParent(None) self.msgLayout.update() try: if self.scroll3.verticalScrollBar().maximum() - self.scroll3.verticalScrollBar().value() < 100: self.scroll3.verticalScrollBar().setValue(self.scroll3.verticalScrollBar().maximum()) except: pass def textChanged(self, text): for i in reversed(range(self.centreLayout.count())): widgetToRemove = self.centreLayout.itemAt(i).widget() # remove it from the layout list self.centreLayout.removeWidget(widgetToRemove) # remove it from the gui widgetToRemove.setParent(None) self.checks = [] for elem in self.allCenters: if text.lower() in elem.lower() or len(text) == 0: c = QCheckBox(elem) self.centreLayout.addWidget(c) if elem in self.checkedCenters.keys(): c.setChecked(True) c.stateChanged.connect(self.selectionStateChanged) self.checks.append(c) self.centreLayout.update() def selectAll(self, chk): for i in range(self.centreLayout.count() - 1): chkbox = self.centreLayout.itemAt(i).widget() chkbox.blockSignals(True) for i in range(self.centreLayout.count() - 1): chkbox = self.centreLayout.itemAt(i).widget() chkbox.setChecked(chk.isChecked()) for i in range(self.centreLayout.count() - 1): chkbox = self.centreLayout.itemAt(i).widget() chkbox.blockSignals(False) self.centreLayout.itemAt(self.centreLayout.count() - 1).widget().setChecked(chk.isChecked()) def onSelectRadio(self, button): if button.isChecked(): self.dose = button.dose def clearSelections(self): self.checkedCenters = {} for i in reversed(range(self.selectedLayout.count())): widgetToRemove = self.selectedLayout.itemAt(i).widget() # remove it from the layout list self.selectedLayout.removeWidget(widgetToRemove) # remove it from the gui widgetToRemove.setParent(None) self.districtSelectionchange(0) def closeEvent(self): print("Closing app") MsgPass.MsgPass.runstatus = False def start(self): try: self.getters = Getters.Getters() self.stateDict = self.getters.getStates() # print(self.stateDict) self.window() except BaseException as e: raise
class QueueItem(QWidget): def __init__(self, user_id, skill, queue_position, parent=None): QWidget.__init__(self, parent=parent) self.skill = skill self.user_id = user_id self.queue_position = queue_position self.setBackgroundColor() self.dbHandler = DatabaseHandler() self.staticData = self.dbHandler.getStaticSkillData(self.skill.skill_id) self.createLayout() if self.staticData is None: print("Queue Item Widget got a None Skill Static Data") else: # Int Values of the Characters primary and secondary Attributes, used for calculation charAttributes = self.dbHandler.getCharacterAttributes(self.user_id) charPrimaryAtt = tools.getCharPrimaryValue(charAttributes, self.staticData) charSecondaryAtt = tools.getCharSecondaryValue(charAttributes, self.staticData) self.spPerMinute = tools.spPerMinute(charPrimaryAtt, charSecondaryAtt) # Fill the Labels with Data, and update it every second for the 1st Skill in the Queue self.updateLabels() if self.queue_position == 1: self.startUpdateTimer() def createLayout(self): self.layout = QVBoxLayout() self.layout.addLayout(self.firstLine()) self.layout.addLayout(self.secondLine()) self.setLayout(self.layout) self.set_size_policy() def firstLine(self): hbox = QHBoxLayout() self.titleLabel = QLabel("x. Skill Name") self.rankLabel = QLabel("Rank x") self.levelLabel = QLabel("Level X") self.titleLabel.setFont(QFont("Arial", 8, QFont.Bold)) hbox.addWidget(self.titleLabel) hbox.addSpacing(5) hbox.addWidget(self.rankLabel) hbox.addStretch(1) hbox.addWidget(self.levelLabel) return hbox def secondLine(self): hbox = QHBoxLayout() self.spLabel = QLabel("SP: ") self.spPerHourLabel = QLabel("SP/Hour: ") self.trainingTimeLabel = QLabel("Training Time: ") self.progressLabel = QLabel(" % Done") hbox.addWidget(self.spLabel) hbox.addSpacing(5) hbox.addWidget(self.spPerHourLabel) hbox.addSpacing(5) hbox.addWidget(self.trainingTimeLabel) hbox.addStretch(1) hbox.addWidget(self.progressLabel) return hbox def updateLabels(self): #First Line ToDo: Optimize pos = str(self.queue_position) name = self.staticData.name self.titleLabel.setText(pos + ". " + name) self.rankLabel.setText("(Rank " + str(self.staticData.rank) + ")") self.levelLabel.setText("Level " + str(self.skill.finished_level)) if self.skill.finish_date is not None: self.trainingTimeLabel.setText("Training Time: " + tools.getSkillTrainingTime(self.skill)) # - # Second Line skillTrainingProgress = tools.getSkillTrainingProgress(self.skill, self.spPerMinute) # + self.spLabel.setText("SP: " + format(self.skill.level_start_sp + skillTrainingProgress) + "/" # + + format(self.skill.level_end_sp)) self.spPerHourLabel.setText("SP/Hour: " + str(int(60*self.spPerMinute))) # - self.progressLabel.setText(str(round(skillTrainingProgress / (self.skill.level_end_sp - self.skill.level_start_sp) * 100, 1)) + " % Done") # + self.layout.update() def setBackgroundColor(self): self.setAutoFillBackground(True) # Background Color pal = QPalette() mod = self.skill.queue_position % 2 if mod == 0: pal.setColor(self.backgroundRole(), QtCore.Qt.lightGray) else: pal.setColor(self.backgroundRole(), QtCore.Qt.white) self.setPalette(pal) def set_size_policy(self): self.layout.setContentsMargins(1, 1, 1, 1) self.layout.setSpacing(1) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) def startUpdateTimer(self): self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updateLabels) self.timer.setSingleShot(False) self.timer.start(1000)
class MyTableWidget(QWidget): """ setup of the tab containing all the buttons and data """ # ################################### # def __init__(self): super().__init__() self.layout = QVBoxLayout(self) # initialization of the filename containing the residual data self.filename = "" # initialize the tab screens self.tabs = QTabWidget() # add the tab screens to the tab widget self.tabs.resize(600, 600) # make the layout of the tabs self.make_tab() # initialize the tabs self.layout.addWidget(self.tabs) self.setLayout(self.layout) # setup a timer for plot update every 'setInterval' ms self.timer = QtCore.QTimer() self.timer.setInterval(500) self.timer.timeout.connect(self.plot_data) self.timer.start() # ################################### # def delete_tab(self): for i in range(len(self.chkbx)): self.btn_layout.removeWidget(self.chkbx[i]) self.chkbx[i].setParent(None) self.chkbx[i].deleteLater() self.btn_layout.update() def update_chkbx(self): self.chkbx = [] if (self.filename != ""): # pandas data, specific to su2 self.dataframe = pd.read_csv(self.filename) # get rid of quotation marks in the column names self.dataframe.columns = self.dataframe.columns.str.replace( '"', '') # get rid of spaces in the column names self.dataframe.columns = self.dataframe.columns.str.replace( ' ', '') # limit the columns to the ones containing the string 'rms' self.dfrms = self.dataframe.filter(regex='rms') for name in self.dfrms: self.chkbx.append(QCheckBox(name)) for i in range(len(self.chkbx)): self.chkbx[i].toggle() self.chkbx[i].toggled.connect(self.changedata) # ################################### # def update_tab(self): self.update_chkbx() '''Button layout section''' for i in range(len(self.chkbx)): self.btn_layout.addWidget(self.chkbx[i]) self.btn_layout.addStretch() self.btn_layout.update() # ################################### # def make_tab(self): self.update_chkbx() '''file dialog section''' self.btn_openfile = QPushButton("Select File") self.btn_openfile.clicked.connect(self.getfile) self.show_filename = QLabel("No file selected") self.btn_openfile.setToolTip( 'click to select the file containing the residual data') '''button section''' # temporarily stop the realtime update self.btn_plot_data = QPushButton('stop') self.btn_plot_data.setToolTip('Click to stop real time data gathering') # setting size of button (width,height) self.btn_plot_data.resize(50, 50) self.btn_plot_data.clicked.connect(self.timer_startstop) # this is a one-column list with the start/stop button at the top # followed by the list of lines self.btn_layout = QVBoxLayout() self.btn_layout.addWidget(self.btn_openfile) self.btn_layout.addWidget(self.show_filename) self.btn_layout.addWidget(self.btn_plot_data) for i in range(len(self.chkbx)): print("i=", i) self.btn_layout.addWidget(self.chkbx[i]) # this adds stretch, so the button is always top-aligned (in a vbox) self.btn_layout.addStretch() '''left-side layout''' left = QFrame() left.setLayout(self.btn_layout) self.figure = MatplotlibFigure() # combine the buttons and the canvas in a splitter layout splitter1 = QSplitter(QtCore.Qt.Horizontal) splitter1.addWidget(left) splitter1.addWidget(self.figure) splitter1.setSizes([75, 700]) '''master layout of tab''' self.tab = QWidget() # create tab with horizontal layout self.tab.layout = QHBoxLayout() # add the last splitter to the layout self.tab.layout.addWidget(splitter1) self.tab.setLayout(self.tab.layout) self.tabs.addTab(self.tab, 'Convergence plot') checklist = [] for c in self.chkbx: checklist.append(c.isChecked()) self.figure.plot(checklist, self.filename) # ################################### # # file dialog for monitor input def getfile(self): # now we need to clear the list of widgets self.delete_tab() fname = QFileDialog.getOpenFileName(self, 'Open file', 'history.csv', "csv files (*.txt *.csv)") self.filename = fname[0] # split the filename fn = os.path.basename(self.filename) fb = os.path.basename(os.path.dirname(self.filename)) self.show_filename.setText(os.path.join(fb, fn)) self.show_filename.setToolTip(self.filename) # update tab self.update_tab() # ################################### # # start or stop the realtime update using the start/stop button def timer_startstop(self): if (self.timer.isActive() == True): #print("timer is active. it will be stopped") self.timer.stop() self.btn_plot_data.setText('start') self.btn_plot_data.setToolTip( 'Click to start real time data gathering') self.btn_plot_data.update() self.btn_layout.update() else: self.timer.start() #print("timer is inactive. it will be started") self.btn_plot_data.setText('stop') self.btn_plot_data.setToolTip( 'Click to stop real time data gathering') self.btn_plot_data.update() self.btn_layout.update() # ################################### # def plot_data(self): checklist = [] for c in self.chkbx: checklist.append(c.isChecked()) self.figure.plot(checklist, self.filename) # ################################### # def changedata(self): checklist = [] for c in self.chkbx: checklist.append(c.isChecked()) self.figure.plot(checklist, self.filename)
class Personenfenster(QWidget): def __init__(self): super().__init__() self.init() self.suche=False def string2list(self,tupel): retlist=[] for index in range(len(tupel)): string = tupel[index][0] retlist.append(string) return retlist def init(self): #Daten aus der Datenbank c.execute("SELECT nachname FROM personen") nachnamenlistealsstring=c.fetchall() c.execute("SELECT vorname FROM personen") vornamenlistealsstring=c.fetchall() c.execute("SELECT geburtsdatum FROM personen") geburtsdatenlistealsstring=c.fetchall() c.execute("SELECT person_id FROM personen") idlistealsstring=c.fetchall() nachnamenliste = self.string2list(nachnamenlistealsstring) vornamenliste = self.string2list(vornamenlistealsstring) geburtsdatenliste = self.string2list(geburtsdatenlistealsstring) idliste = self.string2list(idlistealsstring) self.scrollmatrix = [] for index,item in enumerate(vornamenliste): self.scrollmatrix.append([nachnamenliste[index],item, geburtsdatenliste[index],idliste[index]]) #Suchenfeld self.Input = QLineEdit(self) self.Input.setPlaceholderText("Suchen...") self.Input.returnPressed.connect(self.Inputtext) #+-Button self.AddButton = QPushButton("+") self.AddButton.clicked.connect(self.addPerson) self.clearButton = QPushButton("reset") self.clearButton.clicked.connect(self.clear) #HBox mit dem Suchen Feld ganz links und dem +-Button ganz rechts self.suchen = QHBoxLayout() self.suchen.addWidget(self.Input) self.suchen.addStretch(1) #self.suchen.addWidget(self.clearButton) self.suchen.addWidget(self.AddButton) #HBox mit den Überschriften für die einzelnen Zeilen: self.row0 = QGridLayout() self.row0.addWidget(QLabel("Nachname"),0,0,1,2) self.row0.addWidget(QLabel("Vorname"),0,2,1,2) self.row0.addWidget(QLabel("Geburtsdatum"),0,4,1,2) self.row0.addWidget(QLabel("Beten/Bearbeiten"),0,6,1,2) #Hier kommt die Personenanzeige self.scroll = QScrollArea() self.personenanzeige = QWidget() self.scroll.setWidgetResizable(True) #Hier kommen die Personen self.personenanzeigenLayout = QVBoxLayout(self.personenanzeige) for person in self.scrollmatrix: self.personenanzeigenLayout.addLayout(Row(person)) self.personenanzeigenLayout.addStretch(1) self.personenanzeige.setLayout(self.personenanzeigenLayout) self.scroll.setWidget(self.personenanzeige) #setzt alles in eine große VBox self.vbox = QVBoxLayout() self.vbox.addLayout(self.suchen) self.vbox.addLayout(self.row0) self.vbox.addWidget(self.scroll) self.setLayout(self.vbox) def Inputtext(self): text1 = self.Input.text() if text1!=None and text1!="": text1=str(text1) c.execute("SELECT nachname FROM personen") nachnamenlistealsstring=c.fetchall() c.execute("SELECT vorname FROM personen") vornamenlistealsstring=c.fetchall() c.execute("SELECT geburtsdatum FROM personen") geburtsdatenlistealsstring=c.fetchall() c.execute("SELECT person_id FROM personen") idlistealsstring=c.fetchall() nachnamenliste = self.string2list(nachnamenlistealsstring) vornamenliste = self.string2list(vornamenlistealsstring) geburtsdatenliste = self.string2list(geburtsdatenlistealsstring) idliste = self.string2list(idlistealsstring) searchednachname=[] for nachname in nachnamenliste: if nachname: if text1 in nachname: searchednachname.append(nachname) searchedvorname=[] for vorname in vornamenliste: if vorname: if text1 in vorname: searchedvorname.append(vorname) idliste=[] searchednachname=list(set(searchednachname)) searchedvorname=list(set(searchedvorname)) for i in searchednachname: c.execute("""SELECT person_id FROM personen WHERE nachname="{}" """.format(i)) a=c.fetchall() for j in a: idliste.append(j[0]) for i in searchedvorname: c.execute("""SELECT person_id FROM personen WHERE vorname="{}" """.format(i)) a=c.fetchall() for j in a: idliste.append(j[0]) idliste=list(set(idliste)) if len(idliste)>0: nachnamenliste=[] vornamenliste=[] geburtsdatenliste=[] for i in idliste: c.execute("""SELECT nachname FROM personen WHERE person_id={}""".format(i)) nachnamenliste.append(c.fetchall()[0][0]) c.execute("""SELECT vorname FROM personen WHERE person_id={}""".format(i)) vornamenliste.append(c.fetchall()[0][0]) c.execute("""SELECT geburtsdatum FROM personen WHERE person_id={}""".format(i)) geburtsdatenliste.append(c.fetchall()[0][0]) #Neugestaltung mit gesuchten Werten self.scrollmatrix = [] for index,item in enumerate(vornamenliste): self.scrollmatrix.append([nachnamenliste[index],item, geburtsdatenliste[index],idliste[index]]) self.vbox.removeWidget(self.scroll) self.scroll.close() #Hier kommt die Personenanzeige self.scroll = QScrollArea() self.personenanzeige = QWidget() self.scroll.setWidgetResizable(True) #Hier kommen die Personen self.personenanzeigenLayout = QVBoxLayout(self.personenanzeige) for person in self.scrollmatrix: self.personenanzeigenLayout.addLayout(Row(person)) self.personenanzeigenLayout.addStretch(1) self.personenanzeige.setLayout(self.personenanzeigenLayout) self.scroll.setWidget(self.personenanzeige) self.vbox.addWidget(self.scroll) self.vbox.update() else: self.vbox.removeWidget(self.scroll) self.scroll.close() noresults = QWidget() noresultslayout=QVBoxLayout() noresultslabel=QLabel("""Zu diesem Suchbegriff wurden leider keine Ergebnisse gefunden\n Versuchen Sie es mit einem anderen Suchbegriff oder fügen Sie die gesuchte Person hinzu""") noresultslabel.setAlignment(Qt.AlignCenter) noresultslayout.addWidget(noresultslabel) noresults.setLayout(noresultslayout) self.scroll = QScrollArea() self.scroll.setWidget(noresults) self.vbox.addWidget(self.scroll) self.vbox.update() self.suchen.removeWidget(self.AddButton) #self.suchen.removeWidget(self.clearButton) if not self.suche: self.breaksearchButton=QPushButton("Suche abbrechen") self.breaksearchButton.clicked.connect(self.breaksearch) self.suchen.addWidget(self.breaksearchButton) self.suche=True #self.suchen.addWidget(self.clearButton) self.suchen.addWidget(self.AddButton) self.suchen.update() def breaksearch(self): self.suchen.removeWidget(self.breaksearchButton) self.suche=False self.breaksearchButton.close() self.Input.setText("") self.suchen.update() self.updatedata() def clear(self): c.execute("DROP TABLE IF EXISTS personen") c.execute("""CREATE TABLE IF NOT EXISTS personen ( person_id INT(10) NOT NULL AUTO_INCREMENT, nachname VARCHAR(50) default null, vorname VARCHAR(50) not null, geburtsdatum date default null, primary key (person_id))""") c.execute("DROP TABLE IF EXISTS gebete") c.execute("""CREATE TABLE IF NOT EXISTS gebete ( gebets_id INT(10) NOT NULL AUTO_INCREMENT, person_id INT(10) NOT NULL, gebetsart VARCHAR(5) NOT NULL, anliegen VARCHAR(1000) NOT NULL, PRIMARY KEY (gebets_id) )""") c.execute("DROP TABLE IF EXISTS oldidlist") c.execute("""CREATE TABLE IF NOT EXISTS oldidlist ( ID INTEGER NOT NULL )""") conn.commit() self.updatedata() def updatedata(self): c.execute("SELECT nachname FROM personen") nachnamenlistealsstring=c.fetchall() c.execute("SELECT vorname FROM personen") vornamenlistealsstring=c.fetchall() c.execute("SELECT geburtsdatum FROM personen") geburtsdatenlistealsstring=c.fetchall() c.execute("SELECT person_id FROM personen") idlistealsstring=c.fetchall() nachnamenliste = self.string2list(nachnamenlistealsstring) vornamenliste = self.string2list(vornamenlistealsstring) geburtsdatenliste = self.string2list(geburtsdatenlistealsstring) idliste = self.string2list(idlistealsstring) self.scrollmatrix = [] for index,item in enumerate(vornamenliste): self.scrollmatrix.append([nachnamenliste[index],item, geburtsdatenliste[index],idliste[index]]) self.vbox.removeWidget(self.scroll) self.scroll.close() #Hier kommt die Personenanzeige self.scroll = QScrollArea() self.personenanzeige = QWidget() self.scroll.setWidgetResizable(True) #Hier kommen die Personen self.personenanzeigenLayout = QVBoxLayout(self.personenanzeige) for person in self.scrollmatrix: self.personenanzeigenLayout.addLayout(Row(person)) self.personenanzeigenLayout.addStretch(1) self.personenanzeige.setLayout(self.personenanzeigenLayout) self.scroll.setWidget(self.personenanzeige) self.vbox.addWidget(self.scroll) self.vbox.update() def addPerson(self): self.f = addPersonDialog(self)
class GitWindow(QWidget): def __init__(self): super().__init__() self.create_window() def create_window(self): self.showMaximized() self.setWindowTitle("GitUpdates") print("Window visible") self.show() self.show_dialog() def show_dialog(self): user, userOk = QInputDialog.getText(self, "Git User Name", "Enter user name") password, passOk = QInputDialog.getText(self.parent(), self.tr("Enter Password"), self.tr("Password:"******"Add Properties", self) button.clicked.connect(self.on_click) self.layout.addWidget(button) clear = QPushButton("clear", self) clear.clicked.connect(self.on_clear) self.layout.addWidget(clear) self.layout.addWidget(self.table) self.setLayout(self.layout) def on_clear(self): for i in range(1, self.colorCount()): self.table.removeColumn(i) self.layout.update() def on_click(self): print("button clicked") # self.table.clear(self); print(self.properties.currentText()) self.add_columns(self.properties.currentText()) #self.process_repos(self.repos) def add_columns(self, columnData): row = 0 column = self.table.columnCount() self.table.insertColumn(column) self.table.setItem(row, column, QTableWidgetItem(str.upper(str(columnData)))) row += 1 for repo in self.repos: value = str(getattr(repo, str(columnData.strip("_")))) self.table.setItem(row, column, QTableWidgetItem(str(value))) row += 1 self.layout.update() def add_properties(self, repos): print("add properties") self.properties = QComboBox(self) count = 0 for repo in repos: if count == 0: cnt = 0 for prop, val in vars(repo).items(): self.properties.addItem(prop) cnt += 1 count = 1 def process_repos(self, repos): self.table = QTableWidget() self.table.setUpdatesEnabled(True) self.table.setRowCount(repos.totalCount) self.table.setColumnCount(1) self.table.setAutoScroll(True) self.table.setWindowTitle("Git Repositories") row = 0 column = 0 self.table.setItem(row, column, QTableWidgetItem(str.upper("Repository Name"))) row += 1 for repo in repos: self.table.setItem(row, column, QTableWidgetItem(repo.name)) row += 1 def closeEvent(self, event): print("Event called")
class CmdWindow(QWidget): ''' The Command window gives the user all the options to create and send a command message - Dropdown menus to select an Instance, Topic and Subcommand - Fields to enter payload values - A time stamped log showing the commands that were successfully sent ''' def __init__(self): super().__init__() self.title = "Telecommand System" self.top = 300 self.left = 300 self.width = 1000 self.height = 800 self.instance_name = GS_Model.data.instance_chooser self.topic_name = GS_Model.data.topic_chooser self.subcommand_name = GS_Model.data.subcommand_chooser self.payload_entries = [] self.payload_values = {} self.InitWindow() def InitWindow(self): ''' Initialize the Command window layout ''' self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Destination IP Address self.ip_label = QLabel("IP Address:") self.ip_textbox = QLineEdit("127.0.0.1") self.hbox_ip = QHBoxLayout() self.hbox_ip.addWidget(self.ip_label) self.hbox_ip.addWidget(self.ip_textbox) # Instance Menu self.instance_label = QLabel("Instance:") self.instance_menu = QComboBox(self) for instance in GS_Model.data.instance_keys: self.instance_menu.addItem(instance) self.instance_menu.currentIndexChanged.connect(self.UpdateInstance) self.hbox_instance = QHBoxLayout() self.hbox_instance.addWidget(self.instance_label) self.hbox_instance.addWidget(self.instance_menu) # Topic Menu self.topic_label = QLabel("Topic:") self.topic_menu = QComboBox(self) for topic in GS_Model.data.telecommand_topic_keys: self.topic_menu.addItem(topic) self.topic_menu.currentIndexChanged.connect(self.UpdateTopic) self.hbox_topic = QHBoxLayout() self.hbox_topic.addWidget(self.topic_label) self.hbox_topic.addWidget(self.topic_menu) # Subcommand Menu self.subcommand_label = QLabel("Subcommand:") self.subcommand_menu = QComboBox(self) for subcommand in GS_Model.data.subcommand_keys: self.subcommand_menu.addItem(subcommand) self.subcommand_menu.currentIndexChanged.connect(self.UpdateSubcommand) self.hbox_subcommand = QHBoxLayout() self.hbox_subcommand.addWidget(self.subcommand_label) self.hbox_subcommand.addWidget(self.subcommand_menu) # Payload Menu self.payload_label = QLabel("Payload:") self.vbox_payload = QVBoxLayout() self.vbox_payload.addWidget(self.payload_label) # Send Command Button self.send_cmd_button = QPushButton("Send Command") self.send_cmd_button.clicked.connect(self.SendCommand) # Command Log Display self.cmd_log_label = QLabel("Command Log:") self.cmd_log = QTextBrowser() # Save Command Log Button self.save_cmd_log = QPushButton("Save Command Log") self.save_cmd_log.clicked.connect(self.SaveCommandLog) # Overall Layout self.layout = QVBoxLayout() self.layout.addLayout(self.hbox_ip) self.layout.addLayout(self.hbox_instance) self.layout.addLayout(self.hbox_topic) self.layout.addLayout(self.hbox_subcommand) self.layout.addLayout(self.vbox_payload) self.layout.addWidget(self.send_cmd_button) self.layout.addWidget(self.cmd_log_label) self.layout.addWidget(self.cmd_log) self.layout.addWidget(self.save_cmd_log) self.setLayout(self.layout) self.show() def UpdateInstance(self): ''' This updates the instance variable when a new instance is selected in the GUI ''' self.instance_name = self.instance_menu.currentText() def UpdateTopic(self): ''' This updates the topic variable when a new topic is selected. It also updates the Subcommand dropdown and payload entries with new values (if available) ''' self.topic_name = self.topic_menu.currentText() if self.topic_name != GS_Model.data.topic_chooser: # Update the Subcommand dropdown menu GS_Model.data.UpdateSubcommands(self.topic_name) self.subcommand_menu.setCurrentIndex(0) for i in reversed(range(1, self.subcommand_menu.count())): self.subcommand_menu.removeItem(i) for subcommand in GS_Model.data.subcommand_keys: if subcommand != GS_Model.data.subcommand_chooser: self.subcommand_menu.addItem(subcommand) self.subcommand_menu.update() # Update payload layout if needed eds_id = GS_Controller.control.GetEdsIdFromTopic(self.topic_name) payload_struct = GS_Controller.control.GetPayload(eds_id) if payload_struct is not None: self.UpdatePayload(payload_struct) else: self.UpdatePayload([]) else: self.subcommand_menu.setCurrentIndex(0) for i in reversed(range(1, self.subcommand_menu.count())): self.subcommand_menu.removeItem(i) self.subcommand_menu.update() self.UpdatePayload([]) def UpdateSubcommand(self): ''' This updates the subcommand variable when a new subcommand is selected in the GUI If the new subcommand has new payload values, they are also updated ''' self.subcommand_name = self.subcommand_menu.currentText() eds_id = GS_Model.data.subcommand_dict[self.subcommand_name] if eds_id != 0: payload_struct = GS_Controller.control.GetPayload(eds_id) if payload_struct is not None: self.UpdatePayload(payload_struct) else: self.UpdatePayload([]) else: self.UpdatePayload([]) def ExtractEntries(self, payload_struct): ''' This method generates a list of all the payload entries throughout the payload structure. This list is used to update the display with all of the payload entries Inputs: payload_struct - The payload structure output from GS_Controller.GetPayloadStructure ''' if isinstance(payload_struct, dict): for item in list(payload_struct.keys()): self.ExtractEntries(payload_struct[item]) elif isinstance(payload_struct, list): for item in payload_struct: self.ExtractEntries(item) elif isinstance(payload_struct, tuple): label = QLabel("{:<30} {}".format(payload_struct[0], payload_struct[1])) if payload_struct[2] == 'entry': payloadinput = QLineEdit() elif payload_struct[2] == 'enum': payloadinput = QComboBox() for enum_label in list(payload_struct[3].keys()): payloadinput.addItem(enum_label) else: ErrorMessage("Error", "Something went wrong in the ExtractEntries function") return self.payload_entries.append((payload_struct[0], payload_struct[1], label, payloadinput)) else: ErrorMessage("Error", "Something went wrong in the ExtractEntries function") def UpdatePayload(self, payload_struct): ''' When the payload stucture changes, this method removes the old payload entries and adds new ones based on the payload_struct Inputs: payload_struct - The payload structure output from GS_Controller.GetPayloadStructure ''' # remove the current payload entires in the payload layout (each are their own hbox layouts) for i in reversed(range(1, self.vbox_payload.count())): layout_item = self.vbox_payload.itemAt(i) DeleteItemsOfLayout(layout_item.layout()) self.vbox_payload.removeItem(layout_item) self.vbox_payload.update() # add new widgets to represent the new payload entries self.payload_entries = [] self.ExtractEntries(payload_struct) for entry in self.payload_entries: hbox = QHBoxLayout() hbox.addWidget(entry[2]) hbox.addWidget(entry[3]) self.vbox_payload.addLayout(hbox) self.vbox_payload.update() def SendCommand(self): ''' This method takes the input IP Address and payload values and calls GS_Controller.control.SendCommand to send the packed message. If the command was successfully sent, the command log display will be updated with information related to the command. ''' ip_address = self.ip_textbox.text() valid_payload = True self.payload_values = {} for entry in self.payload_entries: try: value = entry[3].currentText() except AttributeError: value = entry[3].text() if not GS_Controller.ValidPayload(entry, value): ErrorMessage("Error", "Invalid input for '{}'".format(entry[0])) valid_payload = False else: self.payload_values[entry[0]] = value if valid_payload: (cmd_sent, msg, timestamp, port) = GS_Controller.control.SendCommand(ip_address, self.instance_name, self.topic_name, self.subcommand_name, self.payload_values) if cmd_sent: cmd_log_info = f"Command Sent: {timestamp}\n" cmd_log_info += "IP: {} ".format(ip_address) cmd_log_info += "Port: {}\n".format(port) cmd_log_info += "Instance: {} ".format(self.instance_name) cmd_log_info += "Topic: {} ".format(self.topic_name) if self.subcommand_name == GS_Model.data.subcommand_chooser: cmd_log_info += "Subcommand: None\n" else: cmd_log_info += "Subcommand: {}\n".format(self.subcommand_name) cmd_log_payload = '' payload_keys = list(self.payload_values.keys()) for key in payload_keys: cmd_log_payload += "{:<30}: ".format(key) cmd_log_payload += "{}\n".format(self.payload_values[key]) cmd_log_message = "Data to send: \n{}\n".format(GS_Model.HexString(msg, 8)) cmd_log_string = cmd_log_info + cmd_log_payload + cmd_log_message + '\n' self.cmd_log.append(cmd_log_string) self.cmd_log.verticalScrollBar().setValue(self.cmd_log.verticalScrollBar().maximum()) else: ErrorMessage("Error", msg) def SaveCommandLog(self): ''' This method outputs the command log to a time stamped text file. The command log is also cleared when the log file is written. ''' time_str = time.strftime("%Y-%m-%d__%H_%M_%S", time.gmtime()) if not os.path.isdir("output/"): os.mkdir("output/") filename = f"output/Command_Log_{time_str}.txt" fout = open(filename, 'w') fout.write(self.cmd_log.toPlainText()) fout.close() self.cmd_log.clear() self.cmd_log.update()
class App(QWidget): keys = [] def __init__(self): super().__init__() self.title = 'ganBreeder - ganTool' self.left = 10 self.top = 10 self.width = 500 self.height = 400 self.outputFolder = os.path.dirname(os.path.realpath(__file__))+'/output/' self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.hboxTotal = QHBoxLayout() self.vboxLeft = QVBoxLayout() self.vboxRight = QVBoxLayout() # LOGGING ############################################################# self.logLabel = QLabel() self.logLabel.setAlignment(Qt.AlignCenter) self.logLabel.setStyleSheet('color: green') self.pushLog('__ ready for input __') self.vboxLeft.addWidget(self.logLabel) # LOGIN ############################################################### # Username usernameLabel = QLabel() usernameLabel.setText('username') self.usernameLE = QLineEdit(self) # Password passwordLabel = QLabel() passwordLabel.setText('password') self.passwordLE = QLineEdit(self) self.passwordLE.setEchoMode(QLineEdit.Password) hboxLogin = QHBoxLayout() hboxLogin.addWidget(usernameLabel) hboxLogin.addWidget(self.usernameLE) hboxLogin.addWidget(passwordLabel) hboxLogin.addWidget(self.passwordLE) self.passwordLE.setEchoMode(QLineEdit.Password) self.vboxLeft.addLayout(hboxLogin) # FRAMES ############################################################## # Number of frames hboxNFrames = QHBoxLayout() nFramesLabel = QLabel() nFramesLabel.setText('nFrames') self.nFramesSB = QSpinBox() self.nFramesSB.setMinimum(0) self.nFramesSB.setMaximum(999) self.nFramesSB.setValue(10) hboxNFrames.addWidget(nFramesLabel) hboxNFrames.addWidget(self.nFramesSB) self.vboxLeft.addLayout(hboxNFrames) # OUTPUT FOLDER ####################################################### hboxOutput = QHBoxLayout() outputLabel = QLabel() outputLabel.setText('outputFolder') self.outputLE = QLineEdit(self) self.outputLE.setText(self.outputFolder) hboxOutput.addWidget(outputLabel) hboxOutput.addWidget(self.outputLE) self.vboxLeft.addLayout(hboxOutput) # KEYS ################################################################ hboxNKeys = QHBoxLayout() nKeysLabel = QLabel() nKeysLabel.setText('nKeys') self.nKeysSB = QSpinBox() self.nKeysSB.setMinimum(3) self.nKeysSB.setMaximum(10) self.nKeysSB.setValue(3) self.nKeysSB.valueChanged.connect(self.keyValueChange) hboxNKeys.addWidget(nKeysLabel) hboxNKeys.addWidget(self.nKeysSB) self.vboxLeft.addLayout(hboxNKeys) self.initKeys() self.vboxKeys = QVBoxLayout() self.setKeysWidgets() #puts keys in self.vboxKeys self.vboxLeft.addLayout(self.vboxKeys) self.vboxLeft.addStretch(1) # RIGHT VBOX ########################################################## runButton = QPushButton('run', self) runButton.clicked.connect(self.run) self.vboxRight.addWidget(runButton) viewButton = QPushButton('view', self) viewButton.clicked.connect(self.view) self.vboxRight.addWidget(viewButton) self.vboxRight.addStretch(1) # compiling total layout self.hboxTotal.addLayout(self.vboxLeft) self.hboxTotal.addLayout(self.vboxRight) self.setLayout(self.hboxTotal) self.setUserSettings() self.show() def pushLog(self,msg): self.logLabel.setText(msg) self.logLabel.update() def setUserSettings(self): #Fill here for auto-fill self.usernameLE.setText('') #<--- username self.passwordLE.setText('') #<--- passw self.keys[0].setText('b7be350699c9eef42f5e4c6a') self.keys[1].setText('b5c06f29c1b15039812bf45a') self.keys[2].setText('54fc255ae27d61ad87f34687') def initKeys(self): for i in range(self.nKeysSB.value()): self.addNewKey() def setKeysWidgets(self): for i in reversed(range(self.vboxKeys.count())): self.vboxKeys.itemAt(i).widget().setParent(None) for k in self.keys: self.vboxKeys.addWidget(k) self.vboxKeys.update() def addNewKey(self): keyVal = QLineEdit(self) keyVal.setText('') self.keys.append(keyVal) @pyqtSlot() def keyValueChange(self): newVal = self.nKeysSB.value() oldVal = len(self.keys) delta = newVal-oldVal if delta > 0: for i in range(delta): self.addNewKey() self.pushLog('__ added key __') elif delta < 0: for i in range(-delta): self.keys.pop() self.pushLog('__ removed key __') self.setKeysWidgets() print('change') @pyqtSlot() def run(self): self.pushLog('__ running : might take a while to load bigGAN __') self.logLabel.update() self.randHex = '%06x' % random.randint(0, 0xFFFFFF) outputDir = self.outputLE.text()+self.randHex print('calling command inside conda environment') print('bash command:') cmd = ['gantools'] cmd.append('--username') cmd.append(self.usernameLE.text()) cmd.append('--password') cmd.append(self.passwordLE.text()) cmd.append('--nframes') cmd.append(str(self.nFramesSB.value())) cmd.append('--output-dir') cmd.append(outputDir) cmd.append('--keys') for k in self.keys: if k.text() != '': cmd.append(k.text()) # create output folder if it doesn't exist try: os.mkdir(outputDir) except OSError: print ("%s Already exists" % outputDir) else: print ("Successfully created the directory %s " % outputDir) # run ganTools print(cmd) MyOut = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout,stderr = MyOut.communicate() print(stdout) print(stderr) self.pushLog('__ running : complete __') @pyqtSlot() def view(self): self.pushLog('__ viewing : %s.mp4 __' % self.randHex) print('calling command inside conda environment') print('bash command:') cmd = ['ffmpeg'] cmd.append('-f') cmd.append('image2') cmd.append('-i') cmd.append('output/'+self.randHex+'/%04d.jpeg') cmd.append('-crf') cmd.append('18') cmd.append('output/'+self.randHex+'.mp4') print(cmd) subprocess.run(cmd) #Play the file cmd = ['mpv','output/'+self.randHex+'.mp4','--loop'] print(cmd) subprocess.run(cmd) self.pushLog('__ viewing : done __')
class AnalysisTab(QTabWidget): def __init__(self): super().__init__() self.game_list = None self.game_selector = None self.scrollarea = None self.centralLayout = None self.analysisLayout = None self.graphics_layout = None self.spectrogram_widgets = [] self.eeg_graph_widgets = [] self.init_ui() def init_ui(self): self.centralLayout = QVBoxLayout() self.analysisLayout = QVBoxLayout() self.game_selector = self.create_game_selector() self.analysisLayout.addSpacing(40) self.analysisLayout.setSpacing(40) self.analysisLayout.addWidget(self.game_selector) self.analysisLayout self.analysisLayout.setAlignment(self.game_selector, Qt.AlignTop | Qt.AlignHCenter) self.populate_game_selector() if len(self.game_list): self.graphics_layout = self.create_graphics_layout( self.game_selector.currentText()) self.analysisLayout.addLayout(self.graphics_layout) scrollarea = self.create_scroll_area() self.centralLayout.addWidget(scrollarea) self.setLayout(self.centralLayout) def create_scroll_area(self): scrollarea = Scroller() widget = QWidget() widget.setMinimumHeight(SCROLL_AREA_HEIGHT) widget.setLayout(self.analysisLayout) scrollarea.setWidget(widget) scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scrollarea.setWidgetResizable(True) return scrollarea def create_game_selector(self): game_selector = QComboBox(self) game_selector.setToolTip( 'Please select a game to analyze the eeg activity.') game_selector.setFixedSize(230, 40) game_selector.currentTextChanged.connect(self.on_game_selector_change) return game_selector def populate_game_selector(self): self.game_list = get_available_games() self.game_selector.clear() if len(self.game_list): self.game_selector.addItems(self.game_list) else: line_edit = QLineEdit() line_edit.setPlaceholderText(NO_AVAILABLE_GAMES) line_edit.setReadOnly(True) self.game_selector.setLineEdit(line_edit) self.game_selector.update() def create_graphics_layout(self, game_name: str): ELECTRODES_NUMBER = 4 setConfigOptions(imageAxisOrder='row-major') graphics_layout = QGridLayout() graphics_layout.setHorizontalSpacing(100) graphics_layout.setVerticalSpacing(60) for i, player_name in enumerate(PlayerName): player_label = QLabel(player_name.value) player_label.setFont(QFont("Times", 22, QFont.Bold)) graphics_layout.addWidget(player_label, 0, i) for j in range(ELECTRODES_NUMBER): eeg_graph_widget = GraphicsLayoutWidget() spectrogram_widget = GraphicsLayoutWidget() self.eeg_graph_widgets.append( (eeg_graph_widget, player_name.value, j)) self.spectrogram_widgets.append( (spectrogram_widget, player_name.value, j)) graphics_layout.addWidget(eeg_graph_widget, j * 2 + 1, i) graphics_layout.addWidget(spectrogram_widget, j * 2 + 2, i) return graphics_layout def populate_eeg_graph_widget(self, widget: GraphicsLayoutWidget, game_name: str, player_name: PlayerName, electrode_name: str): data = self._acquire_eeg_signal(game_name, player_name, electrode_name) time = self._acquire_eeg_signal(game_name, player_name, 'time') plot = widget.addPlot() plot.plot(time, data, pen=mkPen({'color': "37AAD2"})) plot.setTitle('Amplitude of the EEG signal for electrode %s' % ELECTRODES[electrode_name]) plot.setLabel('bottom', "Time", units='s') plot.setLabel('left', "Amplitude", units='uV') def populate_spectrogram_widget(self, widget: GraphicsLayoutWidget, game_name: str, player_name: PlayerName, electrode_name: str): # https://stackoverflow.com/questions/51312923/plotting-the-spectrum-of-a-wavfile-in-pyqtgraph-using-scipy-signal-spectrogram f, t, Sxx = self._acquire_spectrogram_signal(game_name, player_name, electrode_name) plot = widget.addPlot() plot.setTitle('Frequency over time for electrode %s' % ELECTRODES[electrode_name]) img = ImageItem() plot.addItem(img) hist = HistogramLUTItem() hist.setImageItem(img) widget.addItem(hist) hist.setLevels(np.min(Sxx), np.max(Sxx)) hist.gradient.restoreState({ 'mode': 'rgb', 'ticks': [(0.5, (0, 182, 188, 255)), (1.0, (246, 111, 0, 255)), (0.0, (75, 0, 113, 255))] }) img.setImage(Sxx) img.scale(t[-1] / np.size(Sxx, axis=1), f[-1] / np.size(Sxx, axis=0)) plot.setLimits(xMin=0, xMax=t[-1], yMin=0, yMax=f[-1]) plot.setLabel('bottom', "Time", units='s') plot.setLabel('left', "Frequency", units='Hz') def set_delegate(self, delegate): self.delegate = delegate def on_game_selector_change(self, selected_game): if len(selected_game) and self.spectrogram_widgets is not None: for spectrogram_widget in self.spectrogram_widgets: spectrogram_widget[0].clear() self.populate_spectrogram_widget( spectrogram_widget[0], selected_game, spectrogram_widget[1], "electrode %i" % spectrogram_widget[2]) for eeg_graph_widget in self.eeg_graph_widgets: eeg_graph_widget[0].clear() self.populate_eeg_graph_widget( eeg_graph_widget[0], selected_game, eeg_graph_widget[1], "electrode %i" % eeg_graph_widget[2]) self.analysisLayout.update() def _acquire_eeg_signal(self, game_name: str, player_name: PlayerName, field: str): eeg_signal = read_player_signal(game_name, player_name) return eeg_signal[field] def _acquire_spectrogram_signal(self, game_name: str, player_name: PlayerName, electrode_name: str): eeg_signal = read_player_signal(game_name, player_name) f, t, Sxx = signal.spectrogram(np.array(eeg_signal[electrode_name]), MUSE_EEG_ACQUISITION_FREQUENCY, nperseg=128, detrend='linear', scaling='spectrum') return self._remove_high_frequencies(f, t, Sxx) def _remove_high_frequencies(self, f, t, Sxx): F_MAX = 40 freq_slice = np.where(f <= F_MAX) f = f[freq_slice] Sxx = Sxx[freq_slice, :][0] return (f, t, Sxx)
class SkillPlannerWindow(QMainWindow): def __init__(self, plan_id, parent=None): super(SkillPlannerWindow, self).__init__(parent) self.dbHandler = DatabaseHandler() self.plan = None self.loadPlan(plan_id) if self.plan is not None: self.user_id = self.plan.owner_id self.character_name = self.dbHandler.getCharacter(self.user_id).name self.set_main_window() self.initLayout() def set_main_window(self): # Standard Values for this Window standard_width = 860 standard_height = 600 minimum_width = 544 minimum_height = 300 """Sets the size policies of the main window""" self.resize(standard_width, standard_height) size_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QSize(minimum_width, minimum_height)) # self.setMaximumSize(QSize(standard_width, standard_height)) # main window icon self.setWindowIcon(QIcon(config.APP_ICON)) #self.setWindowTitle(self.character_name + self.plan.name + config.APP_NAME + " Skill Planner") # ToDo: Add plan owner and plan name def initLayout(self): self.centralwidget = QWidget(self) self.layout = QVBoxLayout(self.centralwidget) self.layout.setContentsMargins(20, 20, 20, 20) self.layout.setSpacing(5) self.setCentralWidget(self.centralwidget) self.plansCombo = QComboBox(self) self.plansCombo.addItem("Select Plan") self.plansCombo.addItem("New Plan") self.plansCombo.addItem("Create Plan from Skill Queue") self.plansCombo.activated.connect(self.handlePlansCombo) self.fillPlansCombo() self.layout.addLayout(self.firstLineOptions()) def firstLineOptions(self): ''' First Line Options: Select Plan Export Plan to Delete Plan Print Plan (drucken) Copy to clipboard Implant calculator atrribute optimizer :return: ''' hbox = QHBoxLayout() hbox.addWidget(self.plansCombo) hbox.addStretch(1) return hbox def skillPlannerTabs(self): print("") def handlePlansCombo(self, index): itemData = self.plansCombo.itemData(index) itemText = self.plansCombo.itemText(index) if itemData is not None: print(self.plansCombo.itemData(index)) def fillPlansCombo(self): plan_list = self.dbHandler.getCharacterPlans(self.user_id) for plan in plan_list: self.plansCombo.addItem(plan.name, plan.id) self.layout.update() def loadPlan(self, plan_id): if plan_id is not None: self.plan = self.dbHandler.getPlan(plan_id)
class App(QMainWindow): BAUDRATES = [ "9600", "19200", "38400", "57600", "74880", "115200", "230400", "250000", "500000", "1000000", "2000000" ] SERIAL_UPDATE_RATE = 100 def __init__(self): super().__init__() self.ports = [] self.serial = None self.line_buffer = "" self.tracked_variables = {} self.on_breakpoint = False uic.loadUi('SerialDebuggerInterface.ui', self) self.statusbar = self.findChild(QStatusBar, "statusbar") self.maincontainer = self.findChild(QScrollArea, "maincontainer") self.layout_main = QVBoxLayout() self.maincontainer.setLayout(self.layout_main) self.cb_port = self.findChild(QComboBox, "cb_port") self.cb_port.currentIndexChanged.connect(self.create_serial) self.cb_baud = self.findChild(QComboBox, "cb_baud") self.cb_baud.currentIndexChanged.connect(self.create_serial) self.cb_baud.addItems(App.BAUDRATES) self.cb_skip = self.findChild(QCheckBox, "cb_skip") self.cb_skip.stateChanged.connect(self.skip_breakpoint) self.btn_reset = self.findChild(QPushButton, "btn_reset") self.btn_reset.clicked.connect(self.reset) self.btn_next = self.findChild(QPushButton, "btn_next") self.btn_next.clicked.connect(self._btn_next_click) self.lbl_breakpoint = self.findChild(QLabel, "lbl_breakpoint") self.list_ports() self.show() # use timer for serial monitoring self.timer = QTimer() self.timer.timeout.connect(self.check_serial) self.timer.start(App.SERIAL_UPDATE_RATE) def _btn_next_click(self): self.skip_breakpoint() def create_serial(self): baud = int(self.cb_baud.itemText(self.cb_baud.currentIndex())) if len(self.ports) != 0: port = self.cb_port.itemText(self.cb_port.currentIndex()) if self.serial: self.serial.close() self.serial = Serial(port, baud) def list_ports(self): """Check available ports and add it to the combobox.""" self.ports = list_ports.comports() self.cb_port.clear() self.cb_port.addItems([val.device for val in self.ports]) def update_variable(self, name, value): """Register a variable by tracking it in the internal dictionary and adding a UI element for it.""" if name in self.tracked_variables: self.tracked_variables[name].add_variable_value(value) else: var = VariableView(name) self.tracked_variables[name] = var self.layout_main.addWidget(var) var.show() def skip_breakpoint(self): """Send ok message to skip current breakpoint.""" if not self.serial: self.statusbar.showMessage("Serial not initialized") else: self.serial.write(b"ok") self.on_breakpoint = False def check_serial(self): """Check serial port for new data.""" def evaluate_list(data): str2 = re.sub(r"[^\d_,.]", "", data) ret = [] for x in str2.split(","): if x != "": if "." in x: ret.append(float(x)) else: ret.append(int(x)) else: ret.append(0) return ret if len(ret) > 1 else ret[0] if not self.serial: self.statusbar.showMessage("Serial not initialized") else: self.statusbar.showMessage("Serial open") if self.serial.is_open and self.serial.in_waiting != 0: lines = self.serial.read(self.serial.in_waiting).split(b"\r\n") try: lines = [line.decode("utf-8") for line in lines] # use buffer to store unfinisched reads lines[0] = self.line_buffer + lines[0] if lines[-1] != "": self.line_buffer = lines.pop() else: self.line_buffer = "" except Exception as e: return for line in lines: parts = line.split(" ") if parts[0] == "log": if parts[1] == "breakpoint": if self.cb_skip.isChecked(): self.skip_breakpoint() else: self.on_breakpoint = True self.lbl_breakpoint.setText("Breakpoint " + str(parts[2])) elif parts[1] == "variable": name = parts[2] try: val = evaluate_list(parts[3]) except Exception as e: print(e) print("---", line) print("---", parts) return self.update_variable(name, val) else: print("Unknown log encountered: " + line) elif parts[0] == "": pass else: print("Unknown message encountered: " + line) else: self.statusbar.showMessage("Serial open, no messages") self.timer.start(App.SERIAL_UPDATE_RATE) def reset(self): """Reset all variable trackers.""" for _, var in self.tracked_variables.items(): # kill it. kill it with fire var.hide() self.layout_main.removeWidget(var) del var self.tracked_variables = {} self.maincontainer.update() self.layout_main.update()
class KnownSkillsItem(QWidget): def __init__(self, user_id, skill, position, parent=None): QWidget.__init__(self, parent=parent) self.skill = skill self.position = position self.user_id = user_id self.dbHandler = DatabaseHandler() self.staticData = self.dbHandler.getStaticSkillData( self.skill.skill_id) self.skillQueueItem = None # ToDo: If this skill is in this User's skillQueue activate updateTimer and update labels self.setBackgroundColor() self.createLayout() self.checkSkillQueue() if self.staticData is None: print("Completed Skill Item Widget got a None Skill Static Data") else: # Int Values of the Characters primary and secondary Attributes, used for calculation charAttributes = self.dbHandler.getCharacterAttributes( self.user_id) charPrimaryAtt = tools.getCharPrimaryValue(charAttributes, self.staticData) charSecondaryAtt = tools.getCharSecondaryValue( charAttributes, self.staticData) self.spPerMinute = tools.spPerMinute(charPrimaryAtt, charSecondaryAtt) # Fill the Labels with Data, and update it every second for the 1st Skill in the Queue self.updateLabels() def createLayout(self): self.layout = QVBoxLayout() self.layout.addLayout(self.firstLine()) self.layout.addLayout(self.secondLine()) self.setLayout(self.layout) self.set_size_policy() def firstLine(self): hbox = QHBoxLayout() self.titleLabel = QLabel("x. Skill Name") self.rankLabel = QLabel("Rank x") self.levelLabel = QLabel("Level X") self.titleLabel.setFont(QFont("Arial", 8, QFont.Bold)) hbox.addWidget(self.titleLabel) hbox.addSpacing(5) hbox.addWidget(self.rankLabel) hbox.addStretch(1) hbox.addWidget(self.levelLabel) return hbox def secondLine(self): hbox = QHBoxLayout() self.spLabel = QLabel("SP: ") self.progressLabel = QLabel(" % Done") hbox.addWidget(self.spLabel) hbox.addStretch(1) hbox.addWidget(self.progressLabel) return hbox def updateLabels(self): #First Line ToDo: Optimize #pos = str(self.queue_position) name = self.staticData.name self.titleLabel.setText(name) self.rankLabel.setText("(Rank " + str(self.staticData.rank) + ")") self.levelLabel.setText("Level " + str(self.skill.trained_skill_level)) # Second Line if self.skill.trained_skill_level == 5: modifier = 4 else: modifier = self.skill.trained_skill_level # Eve training multiplier formula: SP = 250 * multiplier * sqrt(32)^(level-1) skill_level_end_sp = 250 * self.staticData.rank * math.sqrt( 32)**modifier if self.skillQueueItem is None: skillTrainingProgress = 0 else: skillTrainingProgress = tools.getSkillTrainingProgress( self.skillQueueItem, self.spPerMinute) self.spLabel.setText("SP: " + format(self.skill.skillpoints_in_skill + skillTrainingProgress) + "/" + format(round(skill_level_end_sp))) self.progressLabel.setText( str( round( skillTrainingProgress / (skill_level_end_sp - self.skill.skillpoints_in_skill) * 100, 1)) + " % Done") # + self.layout.update() def checkSkillQueue(self): # ToDO: Might need improvement check if skill is already completed # we want to know if this skill is in this users skill queue self.skillQueueItem = dbHandler.getSkillQueueItem( self.user_id, self.skill.skill_id) if self.skillQueueItem is not None: self.startUpdateTimer() def setBackgroundColor(self): self.setAutoFillBackground(True) # Background Color pal = QPalette() mod = self.position % 2 if mod == 0: pal.setColor(self.backgroundRole(), QtCore.Qt.lightGray) else: pal.setColor(self.backgroundRole(), QtCore.Qt.white) self.setPalette(pal) def set_size_policy(self): self.layout.setContentsMargins(1, 1, 1, 1) self.layout.setSpacing(1) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) def startUpdateTimer(self): self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updateLabels) self.timer.setSingleShot(False) self.timer.start(1000)
class TopicsTab(QWidget): configChanged = pyqtSignal() def __init__(self): super(QWidget, self).__init__() self.config = None self.count = 0 self.topicRows = {} self.nameEdit = QLineEdit() self.dataTypeComboBox = QComboBox() self.fillDataTypes() self.opTypeComboBox = QComboBox() self.opTypeComboBox.addItem('sub', 'Subscribe') self.opTypeComboBox.addItem('pub', 'Publish') self.addButton = QPushButton('Add') self.addButton.clicked.connect(self.addClicked) self.mainLayout = QVBoxLayout() rowLayout = QHBoxLayout() rowLayout.addWidget(self.nameEdit) rowLayout.addWidget(self.dataTypeComboBox) rowLayout.addWidget(self.opTypeComboBox) rowLayout.addWidget(self.addButton) rowContainer = QWidget() rowContainer.setLayout(rowLayout) rowContainer.setObjectName('titleRow') self.mainLayout.addWidget(rowContainer) self.setLayout(self.mainLayout) def fillDataTypes(self): rosTypes = Interfaces.getRosMessageTypes() for type in rosTypes: concatType = type['typeDir'] + '/' + type['type'] self.dataTypeComboBox.addItem(concatType, concatType) def addTopicRow(self, name, type, opType): rowLayout = QHBoxLayout() rowLayout.addWidget(QLabel(name)) rowLayout.addWidget(QLabel(type)) rowLayout.addWidget(QLabel(opType)) removeButton = QPushButton('Remove') removeButton.clicked.connect(self.removeTopicClicked) removeButton.setObjectName(str(self.count)) rowLayout.addWidget(removeButton) rowContainer = QWidget() rowContainer.setLayout(rowLayout) rowContainer.setObjectName('row' + str(self.count)) self.mainLayout.addWidget(rowContainer) self.topicRows[self.count] = rowContainer self.count += 1 def addClicked(self): if self.config is not None: self.config.addTopic(self.count, self.nameEdit.text(), self.dataTypeComboBox.currentData(), self.opTypeComboBox.currentData()) self.addTopicRow(self.nameEdit.text(), self.dataTypeComboBox.currentData(), self.opTypeComboBox.currentData()) self.nameEdit.setText('') self.configChanged.emit() def removeTopicClicked(self): if self.config is not None: itemToRemove = None for i in range(self.mainLayout.count()): if self.mainLayout.itemAt(i).widget().objectName( ) == 'row' + self.sender().objectName(): itemToRemove = self.mainLayout.itemAt(i) break if itemToRemove is not None: self.mainLayout.removeItem(itemToRemove) itemToRemove.widget().setParent(None) self.mainLayout.update() self.configChanged.emit() self.config.removeTopic(int(self.sender().objectName())) del self.topicRows[int(self.sender().objectName())] def clearAllRows(self): clearList = [] for i in range(self.mainLayout.count()): item = self.mainLayout.itemAt(i) if item.widget().objectName() != 'titleRow': clearList.append(item) for item in clearList: self.mainLayout.removeItem(item) item.widget().setParent(None) self.mainLayout.update() self.count = 0 def setConfig(self, config): self.config = config self.clearAllRows() for topic in self.config.getTopics(): topic['id'] = self.count self.addTopicRow(topic['name'], topic['type'], topic['opType'])
class Gui: def __init__(self, spotify): self.app = QApplication([]) self.window = QWidget() self.layout = QVBoxLayout() self.spotify = spotify self.account = '3nf1gn8sgkpfdknxxch66kp7x' self.user_id = '' self.authenticated = False self.status_message = '' self.album_art_pic = QWidget() self.scrollArea = QScrollArea() def check_auth(self): print("checking user account") if self.authenticated: print("User already authenticated") status = self.spotify.status_code return status else: user_id = self.get_user() print(str(user_id) + " user not authenticated") status = self.spotify.status_code self.spotify.auth_user(user_id) self.login_success(self.spotify) #status = self.spotify.create_handler() return status def update_lyrics(self, lyrics): if lyrics: lyrics_arr = lyrics[:] lyrics_string = "\n".join(lyrics_arr) self.lyrics.setText(lyrics_string) print("lyrics string: " + lyrics_string) self.scrollArea.setWidget(self.lyrics) self.layout.addWidget(self.scrollArea) def scrape_for_lyrics(self): print("scraping") playback = self.spotify.check_if_playing() if playback: song, changed = self.spotify.get_current_song_info('') song_data = self.spotify.get_current_song_info(song) album_pic = self.spotify.get_album_art(song) self.display_album_art(album_pic) lyr = self.spotify.get_lyrics(song_data) for i in lyr: print(i) print() if lyr: self.update_lyrics(lyr) else: print("No song currently playing. Please try again later") #TODO: check if song changes def login_success(self, spotifyOb): playback = spotifyOb.check_if_playing() if playback: song = spotifyOb.get_current_song_info() self.layout.addWidget(self.get_lyrics_button) def display_album_art(self, art_url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36' } data = requests.get(art_url, headers=headers, timeout=10) print("Data is: " + str(data)) data = urllib.request.urlopen(art_url).read() palette = QPalette() pixmap = QPixmap() pixmap.loadFromData(data) brush = QBrush(pixmap) palette.setBrush(QPalette.Background, brush) self.album_art_pic.setAutoFillBackground(True) self.album_art_pic.setFixedWidth(300) self.album_art_pic.setFixedHeight(300) for i in range(self.layout.count()): if self.layout.itemAt(i).widget() != self.album_art_pic: self.layout.addWidget(self.album_art_pic) #else: #self.layout.itemAt(i).setAlignment(QtCore.Qt.AlignHCenter) self.layout.itemAt(5).setAlignment(QtCore.Qt.AlignHCenter) self.album_art_pic.setPalette(palette) self.layout.update() def setup_main_gui(self): self.user_id_field = QLineEdit() self.layout.addWidget(self.user_id_field) self.use_acc_button = QPushButton("Use Account") self.layout.addWidget(self.use_acc_button) self.get_lyrics_button = QPushButton("Get Lyrics") self.lyrics = QLabel() label = QLabel("Welcome to KiekerLyrics") self.layout.addWidget(label) label2 = QLabel( "User id (this can be acquired from your profile, otherwise just use your account name):" ) self.layout.addWidget(label2) self.window.setLayout(self.layout) def run_gui(self): self.use_acc_button.clicked.connect(self.check_auth) self.get_lyrics_button.clicked.connect(self.scrape_for_lyrics) self.window.show() self.app.exec_() def get_user(self): input_text = self.user_id_field.text() if input_text: self.account = input_text print("User account: " + self.account) return self.account else: return self.account def clearscreen(self): pass
class TopicsTab(QWidget): configChanged = pyqtSignal() def __init__(self): super(QWidget, self).__init__() self.config = None self.count = 0 self.topicRows = {} self.nameEdit = QLineEdit() self.dataTypeComboBox = QComboBox() self.fillDataTypes() self.opTypeComboBox = QComboBox() self.opTypeComboBox.addItem('sub', 'Subscribe') self.opTypeComboBox.addItem('pub', 'Publish') self.addButton = QPushButton('Add') self.addButton.clicked.connect(self.addClicked) self.mainLayout = QVBoxLayout() rowLayout = QHBoxLayout() rowLayout.addWidget(self.nameEdit) rowLayout.addWidget(self.dataTypeComboBox) rowLayout.addWidget(self.opTypeComboBox) rowLayout.addWidget(self.addButton) rowContainer = QWidget() rowContainer.setLayout(rowLayout) rowContainer.setObjectName('titleRow') self.mainLayout.addWidget(rowContainer) self.setLayout(self.mainLayout) def fillDataTypes(self): rosTypes = Interfaces.getRosMessageTypes() for type in rosTypes: concatType = type['typeDir'] + '/' + type['type'] self.dataTypeComboBox.addItem(concatType, concatType) def addTopicRow(self, name, type, opType): rowLayout = QHBoxLayout() rowLayout.addWidget(QLabel(name)) rowLayout.addWidget(QLabel(type)) rowLayout.addWidget(QLabel(opType)) removeButton = QPushButton('Remove') removeButton.clicked.connect(self.removeTopicClicked) removeButton.setObjectName(str(self.count)) rowLayout.addWidget(removeButton) rowContainer = QWidget() rowContainer.setLayout(rowLayout) rowContainer.setObjectName('row' + str(self.count)) self.mainLayout.addWidget(rowContainer) self.topicRows[self.count] = rowContainer self.count += 1 def addClicked(self): if self.config is not None: self.config.addTopic(self.count, self.nameEdit.text(), self.dataTypeComboBox.currentData(), self.opTypeComboBox.currentData()) self.addTopicRow(self.nameEdit.text(), self.dataTypeComboBox.currentData(), self.opTypeComboBox.currentData()) self.nameEdit.setText('') self.configChanged.emit() def removeTopicClicked(self): if self.config is not None: itemToRemove = None for i in range(self.mainLayout.count()): if self.mainLayout.itemAt(i).widget().objectName() == 'row' + self.sender().objectName(): itemToRemove = self.mainLayout.itemAt(i) break if itemToRemove is not None: self.mainLayout.removeItem(itemToRemove) itemToRemove.widget().setParent(None) self.mainLayout.update() self.configChanged.emit() self.config.removeTopic(int(self.sender().objectName())) del self.topicRows[int(self.sender().objectName())] def clearAllRows(self): clearList = [] for i in range(self.mainLayout.count()): item = self.mainLayout.itemAt(i) if item.widget().objectName() != 'titleRow': clearList.append(item) for item in clearList: self.mainLayout.removeItem(item) item.widget().setParent(None) self.mainLayout.update() self.count = 0 def setConfig(self, config): self.config = config self.clearAllRows() for topic in self.config.getTopics(): topic['id'] = self.count self.addTopicRow(topic['name'], topic['type'], topic['opType'])
class MainWindow(QMainWindow): """ Main class which holds all code relating to the main window and GUI interface """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # noinspection PyArgumentList # noinspection PyCallByClass QFontDatabase.addApplicationFont("fonts/krub/Krub-Regular.ttf") # Set window properties self.setWindowTitle("Converter") self.setWindowIcon(QIcon("images/app/logo.png")) self.setFixedSize(300, 500) self.setObjectName("main") self.setStyleSheet(open("main.css").read()) # Navigation buttons/labels placeholders self.previous: QLabel = None self.current: QLabel = None self.next: QLabel = None # Animation property for the navigation buttons/labels self.animation: QPropertyAnimation = None # List of available conversions self.options: helpers.ListHelper = helpers.ListHelper(CONVERSIONS) self.current_option_symbol: str = glfcn(self.options.current)[0].symbol # Create the navigation self.create_navigation() # Main conversion UI placeholders self.input: QLineEdit = None self.convert: QPushButton = None self.clear: QPushButton = None self.combo: QComboBox = None self.results: List[QLabel] = [] self.container: QWidget = None self.v_layout: QVBoxLayout = None self.scroll_area: QScrollArea = None # Create the main UI self.create_ui() # Show all self.show() def create_navigation(self): """ Creates the navigation UI """ self.previous = QLabel(self.options.previous, self) self.previous.mousePressEvent = self.previous_button_click self.previous.installEventFilter(self) self.previous.setToolTip(self.options.previous) self.previous.setObjectName("previous-category") self.previous.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.previous.setGeometry(-125, 20, 150, 50) self.current = QLabel(self.options.current, self) self.current.setObjectName("current-category") self.current.setAlignment(Qt.AlignCenter) self.current.setGeometry(helpers.set_to_middle(300, 200), 20, 200, 50) self.next = QLabel(self.options.next, self) self.next.mousePressEvent = self.next_button_click self.next.installEventFilter(self) self.next.setToolTip(self.options.next) self.next.setObjectName("next-category") self.next.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.next.setGeometry(275, 20, 150, 50) def create_ui(self): """ Creates the main UI for the conversions """ self.input = QLineEdit(self) self.input.setGeometry(0, 90, 250, 70) self.combo = QComboBox(self) self.combo.currentIndexChanged.connect(self.change_option_symbol) self.combo.setObjectName("combo") self.combo.addItems(glfcn(self.options.current)) self.combo.setGeometry(230, 90, 70, 70) self.convert = QPushButton("Convert", self) self.convert.clicked.connect(self.convert_click) self.convert.setObjectName("convert") self.convert.setGeometry(0, 160, 150, 70) self.clear = QPushButton("Clear", self) self.clear.clicked.connect(self.clear_click) self.clear.setObjectName("clear") self.clear.setGeometry(150, 160, 150, 70) def eventFilter(self, obj, event): """ Event filter for when the user hovers over the previous/next options in the navigation UI :param obj: Instance of the object that was clicked on :param event: Event type :return: Return true if event occurred """ if event.type() == QEvent.HoverEnter: self.animation = QPropertyAnimation(obj, b"geometry") self.animation.setDuration(100) self.animation.setStartValue(QRect(275, 20, 150, 50) if obj == self.next else QRect(-125, 20, 150, 50)) self.animation.setEndValue(QRect(265, 20, 150, 50) if obj == self.next else QRect(-115, 20, 150, 50)) self.animation.start() return True elif event.type() == QEvent.HoverLeave: self.animation = QPropertyAnimation(obj, b"geometry") self.animation.setDuration(100) self.animation.setStartValue(QRect(265, 20, 150, 50) if obj == self.next else QRect(-115, 20, 150, 50)) self.animation.setEndValue(QRect(275, 20, 150, 50) if obj == self.next else QRect(-125, 20, 150, 50)) self.animation.start() return True return False def update_navigation(self): """ Update the navigation when the user navigates between options """ # Set new option titles self.previous.setText(self.options.previous) self.previous.setToolTip(self.options.previous) self.current.setText(self.options.current) self.next.setText(self.options.next) self.next.setToolTip(self.options.next) # Update UI components self.previous.update() self.current.update() self.next.update() def previous_button_click(self, event): """ Called when the previous option button is clicked. Changes the conversion to the previous option :param event: Event type """ self.options.change_previous_to_current() self.combo.clear() self.combo.addItems(glfcn(self.options.current)) self.update_navigation() def next_button_click(self, event): """ Called when the next option button is clicked. Changes the conversion to the next option :param event: Event type """ self.options.change_next_to_current() self.combo.clear() self.combo.addItems(glfcn(self.options.current)) self.update_navigation() def change_option_symbol(self, i): """ Called when the user changed the unit of conversion for the given conversion type :param i: Current index """ self.current_option_symbol = glfcn(self.options.current)[i].symbol def convert_click(self): """ Called when the user clicks the convert button Takes the given input and outputs all the possible conversions """ # If no input don't attempt to convert if self.input.text() == "" or self.input.text().isspace(): return if self.container is not None: self.container.deleteLater() self.container.update() self.v_layout.deleteLater() self.v_layout.update() self.scroll_area.deleteLater() self.scroll_area.update() # Delete all the current results for result in self.results: result.deleteLater() result.update() # Clear the results list self.results.clear() # Create the converter converter = \ glfcn(self.options.current)\ .get_unit_from_symbol(self.current_option_symbol)\ .cls(self.input.text()) self.container = QWidget(self) self.v_layout = QVBoxLayout() # Get all the results and append them to the results list and crate a visible label for each result for i, (key, value) in enumerate(converter.all().items()): value = round(value, 6) if type(value) != str else value label = QLabel(f"{value} <strong>{key}</strong>", self) label.setProperty("class", "result" if i != len(converter.all().items()) - 1 else "result no-border") label.setGeometry(0, 230 + (i * 70), 300, 70) label.setFixedSize(300, 70) self.v_layout.addWidget(label, alignment=Qt.AlignLeft) # Append the results self.results.append(label) self.container.setLayout(self.v_layout) self.container.setFixedWidth(300) self.scroll_area = QScrollArea(self) self.scroll_area.setWidget(self.container) self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scroll_area.setGeometry(0, 230, 300, 270) self.scroll_area.show() self.container.show() def clear_click(self): """ Clears the input box """ self.input.clear() if self.container is not None: self.container.deleteLater() self.container.update() self.v_layout.deleteLater() self.v_layout.update() self.scroll_area.deleteLater() self.scroll_area.update() # Delete all the current results for result in self.results: result.deleteLater() result.update() # Clear the results list self.results.clear()
class QGroup(QWidget): def __init__(self, group_id: int, title='', cards=[], parent=None): super().__init__(parent) # Title of the group self.title = title # List of cards in group self.cards = cards # Id of current group self.group_id = group_id self.init_ui() def init_ui(self): # Widget with main layout self.group_widget_main = QWidget(self) # Title of the group self.lineEdit_title = QLineEdit(self.title) self.lineEdit_title.mouseDoubleClickEvent = lambda event: self.lineEdit_title.selectAll() self.lineEdit_title.focusInEvent = lambda event: None self.lineEdit_title.setStyleSheet(""" QLineEdit { margin-right: 8px; background:rgba(0, 0, 0, 0); color: rgba(255, 255, 255, 93%); border-style:None }""") self.lineEdit_title.setFont(QtGui.QFont("Nirmala UI", pointSize=12)) self.lineEdit_title.setAlignment(Qt.AlignLeft | Qt.AlignCenter) self.lineEdit_title.setMaxLength(30) self.label_add_group = QLabel("+ Добавить ещё одну карточку") self.label_add_group.setFont(QtGui.QFont("Nirmala UI", pointSize=10)) self.label_add_group.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.label_add_group.setStyleSheet(""" QLabel { color: rgba(255, 255, 255, 79%); padding: 4px 4px 4px 4px; } QLabel:hover { background: #302746; }""") self.label_add_group.mousePressEvent = lambda event: self.add_card() # Layout with all cards of this group self.vlayout_cards = QVBoxLayout() self.vlayout_cards.setSpacing(6) for card_data in self.cards: widget_cart_current = QCard(self.vlayout_cards.count(), card_data.title, card_data.marks_colors, card_data.description, parent=self) self.vlayout_cards.addWidget(widget_cart_current) # Scroll area for displaying all widgets self.scroll_area = QScrollArea(self) self.scroll_area.setFrameStyle(QFrame.NoFrame) self.scroll_area.setStyleSheet("QScrollArea{background:transparent;}") self.scroll_area.setAutoFillBackground(False) # Container for scroll area self.widget_cards_container = QWidget() self.widget_cards_container.setAutoFillBackground(False) self.widget_cards_container.setObjectName("widget_cards_container") self.widget_cards_container.setStyleSheet("""#widget_cards_container{ background:#241E35; border-style: outset; border-radius: 25px;}""") # Layout for container self.widget_cards_container.setLayout(self.vlayout_cards) self.scroll_area.setWidget(self.widget_cards_container) self.scroll_area.setWidgetResizable(True) # Combine all widgets to main layout self.vlayout_main = QVBoxLayout() self.vlayout_main.addWidget(self.lineEdit_title) self.vlayout_main.addWidget(self.scroll_area) self.vlayout_main.addWidget(self.label_add_group) self.vlayout_main.setAlignment(self.label_add_group, Qt.AlignLeft | Qt.AlignCenter) self.vlayout_main.setContentsMargins(5, 5, 5, 5) self.group_widget_main.setLayout(self.vlayout_main) # Layout with group_widget_main self.vlayout_group_container = QVBoxLayout() self.vlayout_group_container.addWidget(self.group_widget_main) self.setLayout(self.vlayout_group_container) def add_card(self, marks_colors=[], title="Без названия", description="Без описания") -> None: """ Method add cart to QGroup :param title: Title for new card :param description: Description for card :param marks_colors: HEX colors for marks on card """ card = QCard(len(self.cards), title=title, marks_colors=list(marks_colors), description=description, parent=self) # Append card in QGroup list self.cards.append(card) # Adding card to current group self.vlayout_cards.addWidget(card) def remove_card(self, card: QCard) -> None: if card in self.cards: # Remove card from QGroup list self.cards.remove(card) # Remove card from current group\ self.vlayout_cards.removeWidget(card) card.setParent(None) self.vlayout_cards.update() del card def to_dict(self) -> dict: result = { "title": self.title, "cards": [] } for card in self.cards: result["cards"].append(card.to_dict()) return result