class Config(SignalNode.Config): """Config widget displayed for LSLInput.""" def __init__(self, parent=None): super().__init__(parent=parent) self.data_source = QComboBox() for source in LSLInput.data_sources: self.data_source.addItem(source.name) self.data_source.currentTextChanged.connect(self._adjust) self.channel_count = QLabel() self.channel_count.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.channel_count.setAlignment(Qt.AlignCenter) self.channel_count.setMargin(5) self.frequency = QLabel() self.frequency.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.frequency.setAlignment(Qt.AlignCenter) self.frequency.setMargin(5) layout = QFormLayout() self.setLayout(layout) layout.addRow("Data source:", self.data_source) layout.addRow("Channel count:", self.channel_count) layout.addRow("Frequency:", self.frequency) self._adjust() def _adjust(self): """Adjust displayed values after a change.""" # Sync changes with the node self.updateModel() # Find the data_source with the selected name for data_source in LSLInput.data_sources: if data_source.name == self.data_source.currentText(): break else: data_source = None # Update displays to show new information self.channel_count.setText(str(data_source.channel_count)) self.frequency.setText(str(data_source.frequency) + " Hz") def updateModel(self): n = self.node() if n is None: return n.setDataSource(self.data_source.currentText()) def updateView(self): n = self.node() if n is None: return self.data_source.blockSignals(True) self.data_source.setCurrentText(n.dataSource()) self.data_source.blockSignals(False)
class DemoPlotWidget(QWidget): tips = sns.load_dataset("tips") def __init__(self): super().__init__() self._setupView() self._updatePlot() self._connectSignals() def _setupView(self): self.dropdown1 = QComboBox() self.dropdown1.addItems(["sex", "time", "smoker"]) self.dropdown2 = QComboBox() self.dropdown2.addItems(["sex", "time", "smoker", "day"]) self.dropdown2.setCurrentIndex(2) self._createFigure() self.layout = QGridLayout(self) self.layout.addWidget(QLabel("Select category for subplots")) self.layout.addWidget(self.dropdown1) self.layout.addWidget(QLabel("Select category for markers")) self.layout.addWidget(self.dropdown2) self.layout.addWidget(self.canvas) self.label = QLabel("A plot:") def _createFigure(self): self.fig = Figure() self.ax1 = self.fig.add_subplot(121) self.ax2 = self.fig.add_subplot(122, sharex=self.ax1, sharey=self.ax1) self.axes = [self.ax1, self.ax2] self.canvas = FigureCanvas(self.fig) self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.canvas.updateGeometry() def _connectSignals(self): self.dropdown1.currentIndexChanged.connect(self._updatePlot) self.dropdown2.currentIndexChanged.connect(self._updatePlot) def _updatePlot(self): colors = ["b", "r", "g", "y", "k", "c"] self.ax1.clear() self.ax2.clear() cat1 = self.dropdown1.currentText() cat2 = self.dropdown2.currentText() for i, value in enumerate(self.tips[cat1].unique().to_numpy()): df = self.tips.loc[self.tips[cat1] == value] self.axes[i].set_title(cat1 + ": " + value) for j, value2 in enumerate(df[cat2].unique().to_numpy()): df.loc[self.tips[cat2] == value2].plot( kind="scatter", x="total_bill", y="tip", ax=self.axes[i], c=colors[j], label=value2 ) self.axes[i].legend() self.fig.canvas.draw_idle()
class mySearch(QWidget): def __init__(self): super().__init__() vbox = QVBoxLayout() self.mylist = ["Sepia","Thumbnail","Negative","Grayscale","None"] self.userline = QLineEdit("Enter a image tag") self.userline.setMinimumWidth(250) self.userline.returnPressed.connect(self.on_submit) self.filterbox = QComboBox() self.filterbox.addItems(self.mylist) self.nameline = QLabel("") vbox.addWidget(self.userline) vbox.addWidget(self.filterbox) vbox.addWidget(self.nameline) self.setLayout(vbox) @Slot() def on_submit(self): search = self.userline.text() keylist = search.split() self.nameline.setText("Image name: " + image_info[keyimage(image_info,keylist)]['title']) imageopen = Image.open(image_info[keyimage(image_info,keylist)]['id'] + ".jpg") filter1(imageopen,self.filterbox.currentText()).show() print(self.filterbox.currentText())
class Config(SignalNode.Config): """Config widget displayed for LSLInput.""" def __init__(self, parent=None): super().__init__(parent=parent) self.smoothing_factor = QDoubleSpinBox() self.smoothing_factor.setMinimum(0) self.smoothing_factor.setMaximum(1) self.smoothing_factor.setSingleStep(0.1) self.smoothing_factor.setPrefix("x") self.smoothing_factor.valueChanged.connect(self.updateModel) self.method = QComboBox() self.method.addItem("Rectification") self.method.addItem("Fourier Transform") self.method.addItem("Hilbert Transform") self.method.addItem("cFIR") self.method.currentTextChanged.connect(self.updateModel) self.smoother_type = QComboBox() for name in EnvelopeDetector.smoother_name_to_type: self.smoother_type.addItem(name) self.smoother_type.currentTextChanged.connect(self.updateModel) layout = QFormLayout() self.setLayout(layout) layout.addRow("Smoothing factor", self.smoothing_factor) layout.addRow("Method", self.method) layout.addRow("Smoother type", self.smoother_type) def updateModel(self): n = self.node() if n is None: return smoothing_factor = self.smoothing_factor.value() method = self.method.currentText() smoother_type = n.smoother_name_to_type[self.smoother_type.currentText()] n.setSmoothingFactor(smoothing_factor) n.setMethod(method) n.setSmootherType(smoother_type) def updateView(self): n = self.node() if n is None: return self.smoothing_factor.blockSignals(True) self.method.blockSignals(True) self.smoother_type.blockSignals(True) self.smoothing_factor.setValue(n.smoothingFactor()) self.method.setCurrentText(n.method()) self.smoother_type.setCurrentText(n.smoother_type_to_name[n.smootherType()]) self.smoothing_factor.blockSignals(False) self.method.blockSignals(False) self.smoother_type.blockSignals(False)
def set_module_layout(self, module_name="screenshot"): """Sets the layout which can execute modules. :type module_name: str """ self._current_layout = "Module" self._clear_layout() command_type_label = QLabel("Command type: ") command_type_combobox = QComboBox() command_type_combobox.addItem("Module") command_type_combobox.addItem("Shell") module_label = QLabel("Module name: ") module_combobox = QComboBox() for module_name in modules.get_names(): module_combobox.addItem(module_name) module_combobox.currentTextChanged.connect(self._on_module_change) command_type_combobox.currentTextChanged.connect(self._on_command_type_change) self._layout.setColumnStretch(1, 1) self._layout.addWidget(command_type_label, 0, 0) self._layout.addWidget(command_type_combobox, 0, 1) self._layout.addWidget(module_label, 1, 0) self._layout.addWidget(module_combobox, 1, 1) # Module layout cached_module = modules.get_module(module_name) if not cached_module: cached_module = modules.load_module(module_name, self._module_view, self._model) input_fields = [] for option_name in cached_module.get_setup_messages(): input_field = QLineEdit() self._sub_layout.addWidget(QLabel(option_name)) self._sub_layout.addWidget(input_field) input_fields.append(input_field) run_button = QPushButton("Run") run_button.setMaximumWidth(250) run_button.setMinimumHeight(25) run_button.pressed.connect(lambda: self._on_module_run(module_combobox.currentText(), input_fields)) self._sub_layout.addWidget(QLabel("")) self._sub_layout.addWidget(run_button) self._sub_layout.setContentsMargins(0, 15, 0, 0) self._layout.addLayout(self._sub_layout, self._layout.rowCount() + 2, 0, 1, 2) self._on_module_change(module_combobox.currentText())
class CustomDialog(QDialog): def __init__(self): QDialog.__init__(self) self.setWindowTitle("Paramétrage") # Widgets self.combo_players = QComboBox() self.combo_players.addItems([str(i) for i in range(2, 11)]) self.combo_players.setFixedWidth(100) self.combo_players.activated.connect(self.__on_nb_players_changed) self.btn_validate = QPushButton("Valider") self.btn_validate.clicked.connect(self.accept) self.line_edits = [] self.player_name = [] for _ in range(9): self.line_edits.append(QLineEdit()) self.line_edits[-1].setVisible(False) # solde de départ self.start_money_name = QLabel() self.start_money_name.setText("Argent de départ") self.start_money = QLineEdit() # Layouts self.layout_param = QVBoxLayout() self.layout_param.addWidget(self.combo_players) for i in self.line_edits: self.layout_param.addWidget(i) self.layout_start_money = QHBoxLayout() self.layout_start_money.addWidget(self.start_money_name) self.layout_start_money.addWidget(self.start_money) self.layout_param.addLayout(self.layout_start_money) self.layout_param.addWidget(self.btn_validate) self.setLayout(self.layout_param) self.__on_nb_players_changed() def __on_nb_players_changed(self): for i in range(len(self.line_edits)): self.line_edits[i].setVisible(i < int(self.combo_players.currentText())) def get_players(self): return [self.line_edits[i].text() for i in range(int(self.combo_players.currentText()))] def get_start_money(self): return int(self.start_money.text())
class Voyage(QWidget): def __init__(self, parent=None): super(Voyage, self).__init__(parent) self.data = np.loadtxt(open("DS_P6_Voyage_Data.txt", "r"), delimiter=";", skiprows=1, dtype='str') self.cbCompagnie = QComboBox() self.cbCompagnie.currentIndexChanged.connect(self.updateDestinations) self.cbDestination = QComboBox() self.cbDestination.currentIndexChanged.connect(self.updateCourbe) self.imgCourbe = QLabel() self.imgCourbe.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) genLayout = QHBoxLayout() layoutCombo = QVBoxLayout() layoutCombo.addWidget(self.cbCompagnie) layoutCombo.addWidget(self.cbDestination) genLayout.addLayout(layoutCombo) genLayout.addWidget(self.imgCourbe) self.setLayout(genLayout) self.updateCompagnie() def updateCompagnie(self): companies = np.unique(self.data[:,0]) self.cbCompagnie.addItems(companies) def updateDestinations(self): print("updateDestinations") self.cbDestination.clear() # vide la comboBox pour y afficher du nouveau contenu après companie = self.cbCompagnie.currentText() filtre1 = self.data[self.data[:,0]==companie] # conserve tous les éléments sur lignes contenant la compagnie selectionnée destinations = filtre1[:, 4] self.cbDestination.addItems(np.unique(destinations)) self.updateCourbe() def updateCourbe(self): companie = self.cbCompagnie.currentText() filtre1 = self.data[self.data[:, 0] == companie] destination = self.cbDestination.currentText() filtre2 = filtre1[filtre1[:,4]==destination] tarifs = filtre2[:,1] plt.plot(tarifs) plt.savefig('tutu.png', format='png') # creation d'un fichier temporaire self.imgCourbe.setPixmap('tutu.png') plt.clf()
class Voyage(QWidget): def __init__(self, parent=None): super(Voyage, self).__init__(parent) self.data = np.loadtxt(open("voyage.csv", "r"), delimiter=";", skiprows=1, dtype='str') self.cbCompagnie = QComboBox() self.cbCompagnie.currentIndexChanged.connect(self.updateDestinations) self.cbDestination = QComboBox() self.cbDestination.currentIndexChanged.connect(self.updateCourbe) self.imgCourbe = QLabel() self.imgCourbe.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) genLayout = QHBoxLayout() layoutCombo = QVBoxLayout() layoutCombo.addWidget(self.cbCompagnie) layoutCombo.addWidget(self.cbDestination) genLayout.addLayout(layoutCombo) genLayout.addWidget(self.imgCourbe) self.setLayout(genLayout) self.updateCompagnie() def updateCompagnie(self): companies = np.unique(self.data[:,0]) self.cbCompagnie.addItems(companies) def updateDestinations(self): print("updateDestinations") self.cbDestination.clear() companie = self.cbCompagnie.currentText() filtre1 = self.data[self.data[:,0]==companie] destinations = filtre1[:, 4] self.cbDestination.addItems(np.unique(destinations)) self.updateCourbe() def updateCourbe(self): companie = self.cbCompagnie.currentText() filtre1 = self.data[self.data[:, 0] == companie] destination = self.cbDestination.currentText() filtre2 = filtre1[filtre1[:,4]==destination] tarifs = filtre2[:,1] plt.plot(tarifs) plt.savefig('tutu.png', format='png') self.imgCourbe.setPixmap('tutu.png') plt.clf()
class Code(QWidget): TRIAL_STATUS = ('on', 'off') def __init__(self, callback): super().__init__() self.callback = callback trial_label = QLabel('Trial:') self.trial_box = QSpinBox() self.trial_box.setFixedWidth(64) self.trial_box.setValue(1) #self.trial_box.setFocusPolicy(Qt.NoFocus) trial_status_label = QLabel('Trial Status:') self.trial_status = QComboBox() self.trial_status.addItems(self.TRIAL_STATUS) self.trial_status.setFocusPolicy(Qt.NoFocus) response_label = QLabel('Response:') self.response_box = QComboBox() self.response_box.setFocusPolicy(Qt.NoFocus) self.record_button = QPushButton('Record Event') self.record_button.clicked.connect(self.record_event) self.record_button.setEnabled(False) self.record_button.setFocusPolicy(Qt.NoFocus) layout = QHBoxLayout() layout.addWidget(trial_label) layout.addWidget(self.trial_box) layout.addWidget(trial_status_label) layout.addWidget(self.trial_status) layout.addWidget(response_label) layout.addWidget(self.response_box) layout.addStretch() layout.addWidget(self.record_button) self.setLayout(layout) def set_responses(self, responses): self.response_box.clear() self.response_box.addItems(responses) def record_event(self): event = Event(trial=self.trial_box.value(), status=self.trial_status.currentText() == 'on', response=self.response_box.currentText()) if self.trial_status.currentText() == 'off': self.trial_box.setValue(self.trial_box.value() + 1) self.trial_status.setCurrentText('on') self.callback(event)
class ComboboxTreeItemDelegate(QStyledItemDelegate): def __init__(self, adapter, *args): super().__init__(*args) self.adapter = adapter self.combobox = None ## Create the combobox and fill it with labels def createEditor(self, parent, option, index): self.combobox = QComboBox(parent) for sft in [4, 5, 6]: self.combobox.addItem(mode_labels[1 << sft], 1 << sft) return self.combobox ## Render the editor based on the data in the model def setEditorData(self, editor, index): val = index.model().data(index, role=Qt.UserRole) self.combobox.setCurrentText(mode_labels[val]) ## Write back newly selected items into the model def setModelData(self, editor, model, index): model.setData(index, self.combobox.currentData(), role=Qt.UserRole) model.setData(index, self.combobox.currentText()) self.adapter.update(model.data(index, role=Qt.UserRole + 1), mode=self.combobox.currentData())
def setModelData(self, editor: QtWidgets.QComboBox, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Take the editor, read the given value and set it in the model. """ value = editor.currentText() model.setData(index, value, QtCore.Qt.EditRole)
class LoginWindow(QDialog): def __init__(self, model): super(LoginWindow, self).__init__() self.setWindowTitle("login") self.model = model self.combo_box = QComboBox() self.combo_box.setModel(self.model.accounts_model) self.password_input = QLineEdit() layout = QFormLayout() layout.addRow('username:', self.combo_box) layout.addRow("password:"******"Login", self.login) add_button(layout, "Register", self.register) self.setLayout(layout) def register(self): v = AddAccountDialog(self, self.model) res = v.exec_() if res: self.model.login(v.username_inp.text(), v.password_inp.text()) self.accept() def login(self): username = self.combo_box.currentText() password = self.password_input.text() try: ok = self.model.login(username, password) if ok: self.accept() else: self.reject() except: self.setWindowTitle("password Incorrect!!")
def setModelData(self, editor: QtWidgets.QComboBox, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Read the current text and look up the actual ID of that uncertainty type. """ uc_id = self.choices.get(editor.currentText(), 0) model.setData(index, uc_id, QtCore.Qt.EditRole)
class AssociationItem(MimeTypeItem): def __init__(self, mime_type, apps, main_window, listview): MimeTypeItem.__init__(self, mime_type, listview) self.apps = apps self.main_window = main_window self.selector = QComboBox() self.selector.addItems(self.apps) self.selector.currentTextChanged.connect(self._on_selected) self.hbox.addWidget(self.selector, 2) def _on_selected(self, _): mime = self.mime_type.identifier app = self.selector.currentText() self.main_window.status.showMessage(f'Setting {mime} to {app}...') def run(): success = self.main_window.assocdb.set_app_for_mimetype(mime, app) if success: msg = f'{app} was successfully set to open {mime}.' else: msg = f'Could not set {app} to open {mime}, please check ' \ f'the logs!' self.main_window.status.showMessage(msg) t = Thread(target=run) t.start() def __hash__(self): return hash(self.mime_type)
class QChooseAirbase(QGroupBox): selected_airbase_changed = Signal(str) def __init__(self, game: Game, title=""): super(QChooseAirbase, self).__init__(title) self.game = game self.layout = QHBoxLayout() self.depart_from_label = QLabel("Airbase : ") self.depart_from = QComboBox() for i, cp in enumerate([ b for b in self.game.theater.controlpoints if b.captured and b.id in self.game.planners ]): self.depart_from.addItem(str(cp.name), cp) self.depart_from.setCurrentIndex(0) self.depart_from.currentTextChanged.connect(self._on_airbase_selected) self.layout.addWidget(self.depart_from_label) self.layout.addWidget(self.depart_from) self.setLayout(self.layout) def _on_airbase_selected(self): selected = self.depart_from.currentText() self.selected_airbase_changed.emit(selected)
class EntitySelector(QWidget): def __init__(self, parent): self.parent = parent QWidget.__init__(self) self.initUI() def initUI(self): self.layout = QGridLayout() self.setLayout(self.layout) asksel = QLabel( "Please select the entity information you wish to peruse:") self.layout.addWidget(asksel, 0, 0) self.entityTypes = QComboBox() self.getEntityTypes() self.layout.addWidget(self.entityTypes, 0, 1) self.go = QPushButton("Go") self.go.clicked.connect(self.enterentview) self.layout.addWidget(self.go, 1, 0, 1, 2) def getEntityTypes(self): self.entityTypes.addItems(json_reader.getcomplexdata('entities')) def enterentview(self): self.parent.changeState( EntityViewer(self, self.entityTypes.currentText()))
class JahrAuswahlDialog(QDialog): def __init__(self, jahre: List[int]): QDialog.__init__(self) self.jahr = jahre[0] self.cboJahr = QComboBox() self.cboJahr.setMaximumWidth(85) self.cboJahr.setFont(QFont("Arial", 14, QFont.Bold)) self.cboJahr.addItems([str(j) for j in jahre]) self.okButton = QPushButton("OK") self.okButton.setDefault(True) self.cancelButton = QPushButton("Abbrechen") self.okButton.clicked.connect(self.onAccepted) self.cancelButton.clicked.connect(self.reject) self._layout = QVBoxLayout() self.setLayout(self._layout) self._layout.addWidget(self.cboJahr) hbox = QHBoxLayout() hbox.addWidget(self.okButton) hbox.addWidget(self.cancelButton) self._layout.addLayout(hbox) self.setWindowTitle("Veranlagungsjahr") self.setFixedSize(QSize(200, 100)) def onAccepted(self): self.jahr = int(self.cboJahr.currentText()) self.accept()
class TemplateDialog(QDialog): def __init__(self, *args, **kwargs): super(TemplateDialog, self).__init__(*args, **kwargs) self.initUI() def initUI(self): mainLayout = QGridLayout(self) mainLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop) mainLayout.setColumnStretch(0, 0) mainLayout.setColumnStretch(1, 1) mainLayout.setColumnStretch(2, 1) self.setLayout(mainLayout) line = 0 nameText = QLabel('Name:') nameText.setAlignment(Qt.AlignRight) self.nameIn = QLineEdit() mainLayout.addWidget(nameText, line, 0) mainLayout.addWidget(self.nameIn, line, 1, 1, 2) line += 1 tempText = QLabel('Template:') tempText.setAlignment(Qt.AlignRight) self.tempCombo = QComboBox() self.tempCombo.addItem('[NO TEMPLATE]', 0) self._read_templates() mainLayout.addWidget(tempText, line, 0) mainLayout.addWidget(self.tempCombo, line, 1, 1, 2) line += 1 okBtn = QPushButton("Create") okBtn.clicked.connect(self.accept) cancelBtn = QPushButton("Cancel") cancelBtn.clicked.connect(self.reject) mainLayout.addWidget(okBtn, line, 1, 1, 1) mainLayout.addWidget(cancelBtn, line, 2, 1, 1) self.setWindowTitle("New Picker Interface Information") self.setWindowFlags(Qt.WindowStaysOnTopHint) def _read_templates(self): template_dir = get_PMTemplateDir() if os.path.exists(template_dir): files = os.walk(template_dir).next()[2] for each in files: if each.lower().endswith(".pii"): self.tempCombo.addItem(each, each) def get_raw(self): name = self.nameIn.text() template_dir = get_PMTemplateDir() template = self.tempCombo.currentText() data = {} if template != "[NO TEMPLATE]": path = os.path.join(template_dir, template) with open(path, 'r') as outfile: data = json.load(outfile) return {'name': name, 'data': data} Raw = property(get_raw)
class DialogNewGame(QDialog): def __init__(self, games): super().__init__() self.setWindowTitle('Start New Game') self.setFixedSize(QSize(250, 150)) v_main = QVBoxLayout() v_main.addWidget(QLabel('Select the game you wish to track:')) self.combo = QComboBox() self.combo.addItems(games) self.combo.setCurrentIndex(0) v_main.addWidget(self.combo) h_buttons = QHBoxLayout() b_cancel = QPushButton('Cancel') b_cancel.clicked.connect(self.cancel) h_buttons.addWidget(b_cancel) b_start = QPushButton('Start New Game') b_start.clicked.connect(self.start) b_start.setDefault(True) h_buttons.addWidget(b_start) v_main.addLayout(h_buttons) self.setLayout(v_main) def start(self): self.accept() return self.combo.currentText() def cancel(self): self.reject()
def on_click_open(self, combo: QComboBox): name_file = combo.currentText() if len(name_file) == 0: return # set temporary location where to save name_file out_file = os.path.join(tempfile.gettempdir(), name_file) # SQLite con = sqlite3.connect(self.dbname) cur = con.cursor() cur.execute("SELECT content FROM file WHERE name_file = ?;", [name_file]) out = cur.fetchall() con.close() # save out_file with open(out_file, 'wb') as f: blob = out[0][0] content = bz2.decompress(blob) f.write(content) # open out_file with application if platform.system() == 'Linux': subprocess.Popen(['xdg-open', out_file]) elif platform.system() == 'Darwin': subprocess.Popen(['open', out_file]) else: os.startfile(out_file)
class NetPick(QWidget): def __init__(self): QWidget.__init__(self) self.network_pick_combobox = QComboBox() self.network = "goerli" self.network_pick_combobox.addItem("goerli") self.network_pick_combobox.addItem("mainnet") self.network_pick_combobox.addItem("kovan") self.ok_button = QPushButton("Ok") self.main_layout = QFormLayout() self.main_layout.addRow(QLabel("Network:"), self.network_pick_combobox) self.main_layout.addRow(self.ok_button) self.ok_button.clicked.connect(self.pick_network) self.setLayout(self.main_layout) """ This is local method, which changes network depending on the pick in the ComboBox """ def pick_network(self): self.network = self.network_pick_combobox.currentText() self.close()
class MainWindow(QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.game = GameWidget(self) self.box = QComboBox() maps = [elem for elem in os.listdir() if '.l' in elem] for elem in maps: self.box.addItem(elem) self.buttonRandom = QPushButton('Random') self.buttonRandom.clicked.connect(self.random) self.buttonLoad = QPushButton('Load') self.buttonLoad.clicked.connect(self.load) self.buttonStep = QPushButton("Step") self.buttonStep.clicked.connect(self.game.step) self.buttonRun = QPushButton("Run") self.buttonRun.clicked.connect(self.game.run) self.buttonStop = QPushButton("Stop") self.buttonStop.clicked.connect(self.game.stop) self.child = QWidget(self) childLayout = QHBoxLayout() layout = QVBoxLayout() layout.addWidget(self.game) childLayout.addWidget(self.buttonRun) childLayout.addWidget(self.buttonStop) childLayout.addWidget(self.buttonStep) self.child.setLayout(childLayout) layout.addWidget(self.child) layout.addWidget(self.box) layout.addWidget(self.buttonLoad) layout.addWidget(self.buttonRandom) self.setLayout(layout) self.setWindowTitle('LIFE') self.setFixedSize(1500, 1000) def load(self): item = self.box.currentText() f = open(item, 'r') self.game.load(f) f.close() self.game.drawUniverse() def random(self): self.game.universe.generate_random_map() self.game.drawUniverse() def showEvent(self, event): self.game.drawUniverse()
class MyWidget(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): formlayout = QFormLayout() formlayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) formlayout.setVerticalSpacing(20) explain = QLabel("推送小工具请粘贴微博文章详情页链接,并选择类型,提交。") url = QLabel('微博链接:') data_type = QLabel('选择类型:') self.url_edit = QLineEdit() self.data_type_edit = QComboBox() self.data_type_edit.addItems(['负面', '中性', '正面']) button = QPushButton('提交', self) button.setStyleSheet("background-color: rgb(255, 255, 255);") formlayout.addRow(explain) formlayout.addRow(url, self.url_edit) formlayout.addRow(data_type, self.data_type_edit) hbox = QHBoxLayout() hbox.addStretch(0) hbox.addWidget(button) vbox = QVBoxLayout() vbox.addStretch(0) vbox.addLayout(hbox) formlayout.addRow(vbox) self.setLayout(formlayout) # x y 宽 高 self.setGeometry(500, 200, 600, 400) self.setWindowTitle('推送小工具') self.show() # self.data_type_edit.currentIndexChanged[str].connect(self.print_value) # 条目发生改变,发射信号,传递条目内容 button.clicked.connect(self.but_click) def but_click(self): url = self.url_edit.text() data_type_edit = self.data_type_edit.currentText() if not url: QMessageBox.critical(self, '错误', '请输入微博链接') return False mid = get_mid(url) if not mid: QMessageBox.critical(self, '错误', '请输入符合正确的微博链接') self.url_edit.setText('') return False status = get_response(mid) result = get_context(status) tem = '{}\n'.format(data_type_edit) + result + '{}\n'.format(url) write_context(tem) QMessageBox.information(self, '提示', '已成功写入') self.url_edit.setText('') return True
class ManageData(QWidget): def __init__(self, referenced_table, parent=None): super().__init__(parent) self.table = referenced_table self.search_layout = QHBoxLayout() self.search_text = QLabel() self.search_text.setText("Search Table: ") self.input_field = QLineEdit() self.input_field.setPlaceholderText("Type field value...") self.input_field.textChanged.connect(self.search_table) self.input_field.returnPressed.connect(self.search_table) self.combo_text = QLabel("Search by column: ") self.combo_options = QComboBox() self.combo_options.insertItem(0, "None chosen") self.add_combo_options() self.search_layout.addWidget(self.search_text) self.search_layout.addWidget(self.input_field) self.search_layout.addWidget(self.combo_text) self.search_layout.addWidget(self.combo_options) self.setLayout(self.search_layout) def add_combo_options(self): list_of_columns = self.table.model().metadata["columns"] i = 0 for column in list_of_columns: i += 1 self.combo_options.insertItem(i, column) def search_table(self, line=None): if line == None: if self.input_field.text() == "": return input_line = self.input_field.text() combo_line = self.combo_options.currentText() self.table.model().table_search(input_line, combo_line) else: combo_line = self.combo_options.currentText() self.table.model().table_search(line, combo_line)
class MyWindow(QWidget): def __init__(self): super().__init__() vbox1 = QVBoxLayout() self.my_lineedit = QLineEdit("What type of photo are you looking for?") self.my_lineedit.setMinimumWidth(250) self.my_lineedit.selectAll() self.my_btn = QPushButton("Submit") self.my_lbl = QLabel('') self.my_btn.clicked.connect(self.on_submit) self.my_lineedit.returnPressed.connect(self.on_submit) vbox1.addWidget(self.my_lineedit) vbox1.addWidget(self.my_btn) vbox1.addWidget(self.my_lbl) self.setLayout(vbox1) gbox1 = QGroupBox('Photo Search') gbox1.setLayout(vbox1) self.my_list = [ "Pick a filter", 'None', 'Sepia', 'Negative', 'Grayscale', 'Thumbnail' ] # 0 1 2 3 4 5 self.my_combo_box = QComboBox() self.my_combo_box.addItems(self.my_list) self.my_label = QLabel("") vbox2 = QVBoxLayout() vbox2.addWidget(self.my_combo_box) vbox2.addWidget(self.my_label) self.setLayout(vbox2) self.my_combo_box.currentIndexChanged.connect(self.update_ui) gbox2 = QGroupBox("Filters") gbox2.setLayout(vbox2) mbox = QVBoxLayout() mbox.addWidget(gbox1) mbox.addWidget(gbox2) self.setLayout(mbox) self.setWindowTitle("CST 205 App") @Slot() def on_submit(self): your_photo = self.my_lineedit.text() self.my_lbl.setText(f'Your photo is {your_photo}') @Slot() def update_ui(self): my_text = self.my_combo_box.currentText() my_index = self.my_combo_box.currentIndex() self.my_label.setText(f'You chose {self.my_list[my_index]}.')
class EMMASummaryChart(QDialog): def __init__(self, parent=None, toolbar=False): flags = Qt.Window | Qt.WindowTitleHint | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint super().__init__(parent=parent, f=flags) self.setWindowTitle(self.tr("EMMA Summary Chart")) self.figure = plt.figure(figsize=(4, 3)) self.axes = self.figure.subplots() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.main_layout = QGridLayout(self) self.main_layout.addWidget(self.toolbar, 0, 0, 1, 2) self.main_layout.addWidget(self.canvas, 1, 0, 1, 2) self.supported_distances = ("1-norm", "2-norm", "3-norm", "4-norm", "MSE", "log10MSE", "cosine", "angular") self.distance_label = QLabel(self.tr("Distance")) self.distance_combo_box = QComboBox() self.distance_combo_box.addItems(self.supported_distances) self.distance_combo_box.setCurrentText("log10MSE") self.distance_combo_box.currentIndexChanged.connect(self.update_chart) self.main_layout.addWidget(self.distance_label, 2, 0) self.main_layout.addWidget(self.distance_combo_box, 2, 1) if not toolbar: self.toolbar.hide() self.results = [] @property def distance(self) -> str: return self.distance_combo_box.currentText() def update_chart(self): self.show_distances(self.results) def show_distances(self, results: typing.List[EMMAResult], title=""): self.results = results n_members_list = [result.n_members for result in results] distances = [result.get_distance(self.distance) for result in results] self.axes.clear() self.axes.plot(n_members_list, distances, c="black", linewidth=2.5, marker=".", ms=8, mfc="black", mew=0.0) self.axes.set_xlabel(self.tr("$N_{iterations}$")) self.axes.set_ylabel(self.tr("Distance")) self.axes.set_title(title) self.figure.tight_layout() self.canvas.draw()
class DialogImportCsv(QDialog): def __init__(self, parent, groups: list): """ Displays a Dialog with a file chooser for the .csv to import and a group selection combo. :param parent: MainApplication """ QDialog.__init__(self, parent) self.setWindowTitle(tr("grp_action_import_csv")) # Widgets self.fileDialog = QFileDialog(self) self.fileDialog.setOption(QFileDialog.DontUseNativeDialog) self.fileDialog.setWindowFlags(Qt.Widget) self.fileDialog.setNameFilter("Fichiers excel (*.csv)") self.fileDialog.finished.connect(self.done) self.lab_sep = QLabel() # Separator self.lab_sep.setFixedHeight(3) self.lab_sep.setStyleSheet(get_stylesheet("separator")) self.lab_group = QLabel(tr("add_to_group")) self.combo_group = QComboBox() self.combo_group.addItems(groups) self.combo_group.setFixedWidth(200) # Layout self.__set_layout() def __set_layout(self) -> None: """ Sets this widget's layout """ layout = QGridLayout() layout.addWidget(self.fileDialog, 0, 0, 1, 2) layout.addWidget(self.lab_sep, 1, 0, 1, 2) layout.addWidget(self.lab_group, 2, 0, alignment=Qt.AlignRight) layout.addWidget(self.combo_group, 2, 1, alignment=Qt.AlignLeft) self.setLayout(layout) def selected_group(self) -> str: """ :return: The selected group """ return self.combo_group.currentText() def selected_file(self) -> str: """ :return: Selected file (absolute) path """ return self.fileDialog.selectedFiles()[0]
class NodeOutput(QWidget): def __init__(self, content_widget): super(NodeOutput, self).__init__() self.content_widget = content_widget # create UI # create all layouts self.grid_layout = QGridLayout(self) # move buttons self.up_button = QPushButton(self, '') self.down_button = QPushButton(self, '') # type and label self.type_combo_box = QComboBox(self) self.type_combo_box.addItem('exec') self.type_combo_box.addItem('data') self.label_line_edit = QLineEdit(self) self.label_line_edit.setPlaceholderText('Label') # del button self.del_button = QPushButton(self) self.del_button.setText(' Del ') self.del_button.clicked.connect(self.delete_clicked) # merge layouts self.grid_layout.addWidget(self.up_button, 0, 0) self.grid_layout.addWidget(self.down_button, 1, 0) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.label_line_edit, 1, 1) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.del_button, 0, 2, 2, 1) def get_type(self): return self.type_combo_box.currentText() def get_label(self): return self.label_line_edit.text() def set_type(self, new_type): self.type_combo_box.setCurrentText(new_type) def set_label(self, new_label): self.label_line_edit.setText(new_label) def delete_clicked(self): ret = QMessageBox.warning( self, 'Output', 'Do you really want to delete this input? All changes' 'will be lost.', QMessageBox.Yes, QMessageBox.No) if ret == QMessageBox.Yes: self.content_widget.delete_output(self)
class NodeOutput(QWidget): def __init__(self, content_widget): super(NodeOutput, self).__init__() self.content_widget = content_widget # create UI # create all layouts self.grid_layout = QGridLayout(self) # # move buttons TODO move buttons # self.up_button = QPushButton(self, '') # self.down_button = QPushButton(self, '') # type and label self.type_combo_box = QComboBox(self) self.type_combo_box.addItem('exec') self.type_combo_box.addItem('data') self.label_line_edit = QLineEdit(self) self.label_line_edit.setPlaceholderText('Label') # del button self.del_button = QPushButton(self) self.del_button.setText(' Del ') self.del_button.clicked.connect(self.delete_clicked) # merge layouts # self.grid_layout.addWidget(self.up_button, 0, 0) # self.grid_layout.addWidget(self.down_button, 1, 0) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.label_line_edit, 1, 1) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.del_button, 0, 2, 2, 1) def get_type(self): return self.type_combo_box.currentText() def get_label(self): return self.label_line_edit.text() def set_type(self, new_type): self.type_combo_box.setCurrentText(new_type) def set_label(self, new_label): self.label_line_edit.setText(new_label) def delete_clicked(self): self.content_widget.delete_output(self)
class DataTabel(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.combo_file = QComboBox() label1 = QLabel("Input:") self.data_models = {} self.table_view = QTableView() layout1 = QHBoxLayout() layout1.addWidget(label1) layout1.addWidget(self.combo_file) layout1.setStretch(1, 1) self.layout2 = QVBoxLayout() self.layout2.addLayout(layout1) self.layout2.addWidget(self.table_view) self.setLayout(self.layout2) self.combo_file.currentIndexChanged.connect(self.update_model) def initialize(self, data_sets): self.combo_file.clear() for (file_name, data_frame) in data_sets.items(): self.combo_file.addItem(file_name) model = DataModel(data_frame) self.data_models[file_name] = model if (self.combo_file.count() != 0): self.combo_file.setCurrentIndex(self.combo_file.count() - 1) self.update_model() def update_model(self): if (self.combo_file.currentText() in self.data_models): self.table_view.setModel( self.data_models[self.combo_file.currentText()]) else: self.table_view.setModel(DataModel()) def current_file(self): return self.combo_file.currentText()
class ExportFileDialog(QFileDialog): """ Create a custom Export-File Dialog with options like BOM etc. """ def __init__(self,*args,**kwargs): super(ExportFileDialog,self).__init__(*args,**kwargs) self.mainWindow = self.parent() self.setWindowTitle("Export nodes to CSV") self.setAcceptMode(QFileDialog.AcceptSave) self.setOption(QFileDialog.DontUseNativeDialog) #self.setFilter("CSV Files (*.csv)") self.setDefaultSuffix("csv") self.optionBOM = QCheckBox("Use a BOM",self) self.optionBOM.setCheckState(Qt.CheckState.Checked) self.optionLinebreaks = QCheckBox("Remove line breaks",self) self.optionLinebreaks.setCheckState(Qt.CheckState.Checked) self.optionSeparator = QComboBox(self) self.optionSeparator.insertItems(0, [";","\\t",","]) self.optionSeparator.setEditable(True) #self.optionLinebreaks.setCheckState(Qt.CheckState.Checked) self.optionWide = QCheckBox("Convert to wide format (experimental feature)",self) self.optionWide.setCheckState(Qt.CheckState.Unchecked) # if none or all are selected, export all # if one or more are selected, export selective self.optionAll = QComboBox(self) self.optionAll.insertItems(0, ['All nodes (faster for large datasets, ordered by internal ID)','Selected nodes (ordered like shown in nodes view)']) if self.mainWindow.tree.noneOrAllSelected(): self.optionAll.setCurrentIndex(0) else: self.optionAll.setCurrentIndex(1) layout = self.layout() row = layout.rowCount() layout.addWidget(QLabel('Options'),row,0) options = QHBoxLayout() options.addWidget(self.optionBOM) options.addWidget(self.optionLinebreaks) options.addWidget(QLabel('Separator')) options.addWidget(self.optionSeparator) options.addStretch(1) layout.addLayout(options,row,1,1,2) layout.addWidget(QLabel('Post processing'),row+1,0) layout.addWidget(self.optionWide,row+1,1,1,2) layout.addWidget(QLabel('Export mode'),row+2,0) layout.addWidget(self.optionAll,row+2,1,1,2) self.setLayout(layout) if self.exec_(): if os.path.isfile(self.selectedFiles()[0]): os.remove(self.selectedFiles()[0]) output = open(self.selectedFiles()[0], 'w', newline='', encoding='utf8') if self.optionBOM.isChecked() and not self.optionWide.isChecked(): output.write('\ufeff') try: if self.optionAll.currentIndex() == 0: self.exportAllNodes(output) else: self.exportSelectedNodes(output) finally: output.close() if self.optionWide.isChecked(): self.convertToWideFormat(self.selectedFiles()[0]) def exportSelectedNodes(self,output): progress = ProgressBar("Exporting data...", self.mainWindow) #indexes = self.mainWindow.tree.selectionModel().selectedRows() #if child nodes should be exported as well, uncomment this line an comment the previous one indexes = self.mainWindow.tree.selectedIndexesAndChildren() progress.setMaximum(len(indexes)) try: delimiter = self.optionSeparator.currentText() delimiter = delimiter.encode('utf-8').decode('unicode_escape') writer = csv.writer(output, delimiter=delimiter, quotechar='"', quoting=csv.QUOTE_ALL, doublequote=True, lineterminator='\r\n') #headers row = [str(val) for val in self.mainWindow.tree.treemodel.getRowHeader()] if self.optionLinebreaks.isChecked(): row = [val.replace('\n', ' ').replace('\r',' ') for val in row] writer.writerow(row) #rows for no in range(len(indexes)): if progress.wasCanceled: break row = [str(val) for val in self.mainWindow.tree.treemodel.getRowData(indexes[no])] if self.optionLinebreaks.isChecked(): row = [val.replace('\n', ' ').replace('\r',' ') for val in row] writer.writerow(row) progress.step() finally: progress.close() def exportAllNodes(self,output): progress = ProgressBar("Exporting data...", self.mainWindow) progress.setMaximum(Node.query.count()) try: delimiter = self.optionSeparator.currentText() delimiter = delimiter.encode('utf-8').decode('unicode_escape') writer = csv.writer(output, delimiter=delimiter, quotechar='"', quoting=csv.QUOTE_ALL, doublequote=True, lineterminator='\r\n') #headers row = ["level", "id", "parent_id", "object_id", "object_type", "query_status", "query_time", "query_type"] for key in self.mainWindow.tree.treemodel.customcolumns: row.append(key) if self.optionLinebreaks.isChecked(): row = [val.replace('\n', ' ').replace('\r',' ') for val in row] writer.writerow(row) #rows page = 0 while True: allnodes = Node.query.offset(page * 5000).limit(5000) if allnodes.count() == 0: break for node in allnodes: if progress.wasCanceled: break row = [node.level, node.id, node.parent_id, node.objectid, node.objecttype, node.querystatus, node.querytime, node.querytype] for key in self.mainWindow.tree.treemodel.customcolumns: row.append(node.getResponseValue(key)) if self.optionLinebreaks.isChecked(): row = [str(val).replace('\n', ' ').replace('\r',' ') for val in row] writer.writerow(row) # step the Bar progress.step() if progress.wasCanceled: break else: page += 1 finally: progress.close() def convertToWideFormat(self,filename): progress = ProgressBar("Converting data...", self.mainWindow) try: #Separate levels def flattenTable(fulltable,levelcol,idcol,parentidcol,countchildren,removeempty): fulltable[[levelcol]] = fulltable[[levelcol]].astype(int) levels = dict(list(fulltable.groupby(levelcol))) minlevel = fulltable.level.min() for level, data in sorted(levels.items()): #First level is the starting point for the following merges if level == minlevel: #data = data[[idcol,'object_id','object_type']] data = data.add_prefix('level_{}-'.format(level)) flattable = data else: #Aggregate object types and join them for col_countchildren in countchildren: children = data[parentidcol].groupby([data[parentidcol],data[col_countchildren]]).count() children = children.unstack(col_countchildren) children['total'] = children.sum(axis=1) children = children.add_prefix('level_{}-children-{}-'.format(level-1,col_countchildren)) leftkey = 'level_{}-id'.format(level-1) flattable = merge(flattable,children,how='left',left_on=leftkey,right_index=True) flattable[children.columns.values.tolist()] = flattable[children.columns.values.tolist()].fillna(0).astype(int) #Join data data['childnumber'] = data.groupby(parentidcol).cumcount() leftkey = 'level_{}-{}'.format(level-1,idcol) rightkey = 'level_{}-{}'.format(level,parentidcol) data = data.drop([levelcol],axis=1) data = data.add_prefix('level_{}-'.format(level)) flattable = merge(flattable,data,how="outer",left_on=leftkey,right_on=rightkey) if removeempty: flattable = flattable.dropna(axis=1,how='all') return flattable try: #delimiter delimiter = self.optionSeparator.currentText() delimiter = delimiter.encode('utf-8').decode('unicode_escape') #open data = read_csv(filename, sep=delimiter,encoding='utf-8',dtype=str) #convert newdata = flattenTable(data,'level','id','parent_id',['object_type','query_status','query_type'],False) #save outfile = open(filename, 'w',newline='',encoding='utf8') try: if self.optionBOM.isChecked(): outfile.write('\ufeff') #UTF8 BOM newdata.to_csv(outfile,sep=delimiter,index=False,encoding="utf-8") finally: outfile.close() except Exception as e: self.mainWindow.logmessage(e) finally: progress.close()