class FileSelector(Selector): def __init__(self, main, *args, **kwargs): super().__init__(*args, **kwargs) self.main = main self.current_path = '' label = QLabel('Виберіть файл ключа', self) label.move(6, 0) self.entry_for_path = QLineEdit(self) self.entry_for_path.setReadOnly(True) self.entry_for_path.move(5, 15) self.entry_for_path.setFixedSize(260, 17) but = QPushButton("...", self) but.setFixedSize(20, 25) but.move(270, 10) but.clicked.connect(lambda x: self.get_data_path()) def get_data_path(self): local_path = str( QFileDialog.getOpenFileName(self, "Select Directory", self.current_path)[0]) if len(local_path) == 0: return self.current_path = local_path self.entry_for_path.setText(local_path) def read_data(self): if self.current_path: self.main.show_key.setText( open(self.current_path, encoding='utf8').read())
class MainWindow(QWidget): # Inherits QWidget def __init__(self): super().__init__() self.label = QLabel(self) self.button = QPushButton('Очистить', self) self.line_edit = QLineEdit(self) self.initializeUI() def initializeUI(self): self.setGeometry(100, 100, 400, 200) self.setWindowTitle('QLineEdit Test') QLabel("Введите login", self).move(100, 10) name_label = QLabel("Login:"******"Очистить" if sender.text() == 'Очистить': self.line_edit.clear() # очищаем текст
def initUI(self): self.label=QLabel(self) lineEdit=QLineEdit(self) lineEdit.move(80,100) self.label.move(80,40) lineEdit.textChanged[str].connect(self.onChanged) self.setGeometry(300,300,280,170) self.setWindowTitle('QlineEdit控件') self.show()
class MyWindow(QMainWindow): def __init__(self): super().__init__() self.resize(640, 480) self.demoWidget() def changed(self, state): #state부분은 다른 이름으로 바꿔도 됨 # print(state) print("Checked" if state == QtCore.Qt.Checked else "Unchecked") #그냥 2로 적는것보단 QtCore의 Qt라는 페키지에 있는 것을 사용하는 것이 더 좋음 def slider(self, state): print(state) self.label.setText(str(state)) def calculation_add(self): num1 = int(self.qle1.text()) num2 = int(self.qle2.text()) self.result.setText(str(num1+num2)) def demoWidget(self): cb = QCheckBox("MyCheckBox", self) cb.move(0, 0) cb.resize(cb.sizeHint()) #가장 최적의 사이즈를 찾아줌 cb.stateChanged.connect(self.changed) #stateChanged는 시그널임. self.changed s = QSlider(QtCore.Qt.Horizontal , self) s.move(30,30) s.setRange(0,100) #범위 지정 s.resize(300,10) s.setSingleStep(2) #최소 단위 설정 s.valueChanged.connect(self.slider) self.label = QLabel(self) self.label.move(0, 100) self.label.setText("Hello <b style='color: red'>QLabel</b>") self.qle1 = QLineEdit(self) self.qle2 = QLineEdit(self) label2 = QLabel(self) self.qle1.move(0,150) label2.move(110,150) label2.setText("+") label2.resize(20,30) self.qle2.move(130,150) self.button = QPushButton("result", self) self.button.move(0,200) self.button.clicked.connect(self.calculation_add) self.result = QLabel(self) self.result.move(0,250) self.result.setFont(QtGui.QFont('SansSerif', 20))
def initUI(self): qle = QLineEdit(self) qle.move(60, 100) qle.textChanged[str].connect(self.onChanged) self.lbl = QLabel(self) self.lbl.move(60, 40) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('QLineEdit') self.show()
def ui_components(self): # fonts font = QFont("Roboto", 15) # 'enter country name' label enter_country_label = QLabel("Enter country name: ", self) enter_country_label.setFont(font) enter_country_label.move(10, 10) enter_country_label.adjustSize() # 'country name' line edit country_name = QLineEdit(self) country_name.setFixedSize(200, 25) country_name.setFont(font) country_name.setPlaceholderText("Ex: Tunisia") country_name.move(10, 40) country_name_submit = QPushButton("Search", self) country_name_submit.setFixedSize(130, 25) country_name_submit.move(220, 40) # Displays worldwide data as default cases_label = QLabel( f"Current cases: {data.CoronaCases('').total_cases}", self) cases_label.setFont(font) cases_label.adjustSize() cases_label.move(10, 85) deaths_label = QLabel( f"Current deaths: {data.CoronaCases('').total_deaths}", self) deaths_label.setFont(font) deaths_label.adjustSize() deaths_label.move(10, 112.8) recovered_label = QLabel( f"Current recovered: {data.CoronaCases('').total_recovered}", self) recovered_label.setFont(font) recovered_label.adjustSize() recovered_label.move(10, 140) # Updates the labels with country specific data. def label_updater(): cases_label.setText( f"Current cases: {data.CoronaCases('country/'+country_name.text().lower()).total_cases}" ) deaths_label.setText( f"Current deaths: {data.CoronaCases('country/'+ country_name.text().lower()).total_deaths}" ) recovered_label.setText( f"Current recovered: {data.CoronaCases('country/'+ country_name.text().lower()).total_recovered}" ) country_name_submit.clicked.connect(label_updater)
def initUI(self): lbl = QLabel( "1. Type some string on the QLineEdit\n2. Drag & Drop the string on to the button", self) lbl.setGeometry(35, 1, 300, 100) qe = QLineEdit('', self) qe.setDragEnabled(True) qe.move(30, 80) button = Button("Button", self) button.move(190, 80) self.setGeometry(300, 300, 300, 150) self.setWindowTitle('Simple Drag and Drop') self.show()
def cria_campos(self): fonte = QFont("fonts/Open_Sans/OpenSans-Regular.ttf") fonte.setPointSize(11) lbl_nome = QLabel("Nome", self) lbl_nome.move(20, 20) lbl_nome.setFont(fonte) campo1 = QLineEdit(self) campo1.move(20, 50) campo1.setFont(fonte) # campo1.setAutoFillBackground(True) # campo1.setStyleSheet("background-color: white;") campo2 = QLineEdit(self) campo2.move(20, 90) campo2.setFont(fonte) campo2.setPlaceholderText("Digite sua senha") campo2.setEchoMode(QLineEdit.EchoMode.Password)
class JDaApp(QWidget): def __init__(self): super().__init__() self.iniciaUI() def iniciaUI(self): """ Inicializa a janela e mostra seu conteuda na tela """ self.setGeometry(100,100, 400, 200) self.setWindowTitle("Login") self.displayWidgets() self.show() def displayWidgets(self): """ Configura os widgets da app """ # Criando um label e um edit para o nome nome_label = QLabel("Nome:",self) nome_label.move(70, 50) # localiza o label na tela self.nome_edit = QLineEdit(self) self.nome_edit.setAlignment(Qt.AlignLeft) # Este é o padrão self.nome_edit.move(130, 50) self.nome_edit.resize(200, 20) # mudando o tamanho da caixa de texto self.limpar_btn = QPushButton('Limpar', self) self.limpar_btn.clicked.connect(self.limparCxTxt) self.limpar_btn.move(160, 110) # localizando o botão na tela def limparCxTxt(self): """ Quando acionado o butão limpa a caixa de texto """ sender = self.sender() if sender.text() == 'Limpar': self.nome_edit.clear()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() self.setGeometry(300, 300, 280, 60) self.setWindowTitle('Input dialog') self.show() def initUI(self): self.btn = QPushButton('ダイアログ', self) self.btn.move(20, 20) self.btn.clicked.connect(self.showDialog) self.le = QLineEdit(self) self.le.move(110, 20) def showDialog(self): text, ok = QInputDialog.getText(self, 'Input Dialog', '氏名の入力:') if ok: self.le.setText(str(text))
class Example(QWidget): def initUI(self): self.btn = QPushButton('Dialog', self) self.btn.move(20, 20) self.btn.clicked.connect(self.showDialog) self.le = QLineEdit(self) self.le.move(130, 24) self.setGeometry(300, 300, 290, 150) self.setWindowTitle('Input dialog') self.show() def showDialog(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') if ok: self.le.setText(str(text)) def __init__(self): super(Example, self).__init__() self.initUI()
def __add_input(self, parent, text, label_pos_x, label_pos_y, input_pos_x, input_pos_y, label_width=100, label_height=24, input_width=50, input_height=20): label = QLabel(text, parent=parent) label.setFont(QFont(primary_font)) label.setStyleSheet(label_style) label.resize(label_width, label_height) label.move(label_pos_x, label_pos_y) input = QLineEdit(parent=parent) input.setFont(QFont(secondary_font)) input.setStyleSheet(input_style) input.resize(input_width, input_height) input.move(input_pos_x, input_pos_y) return label, input
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.btn = QPushButton("Dialog", self) self.btn.move(20, 20) self.btn.clicked.connect(self.showDialog) self.line_edit = QLineEdit(self) self.line_edit.move(130, 22) self.setGeometry(300, 300, 450, 350) self.setWindowTitle("Input dialog") self.show() @S**t() def showDialog(self): text, ok = QInputDialog.getText(self, "Input Dialog", "Enter your name: ") if ok: self.line_edit.setText(str(text))
class SettingsWindow(QMainWindow): def __init__(self): super().__init__() self.set_button("Save", self.save_data, 40, 150) self.textbox1 = QLineEdit(self) self.textbox1.move(40, 30) self.textbox1.resize(200, 20) self.textbox2 = QLineEdit(self) self.textbox2.move(40, 75) self.textbox2.resize(200, 20) self.textbox3 = QLineEdit(self) self.textbox3.move(40, 120) self.textbox3.resize(200, 20) self.read_data() self.init_window() def init_window(self): self.setWindowTitle("Settings") self.setGeometry(300, 200, 300, 300) self.show() def read_data(self): if os.path.exists("./data/settings.txt"): f = open("./data/settings.txt", "r") read = f.readlines() self.textbox1.setText(read[0]) self.textbox2.setText(read[1]) self.textbox3.setText(read[2]) f.close() else: self.textbox1.setText("OAuth Token") self.textbox2.setText("Account name") self.textbox3.setText("Channel") def set_button(self, msg, action, x, y, visibility=True): btn1 = QPushButton(msg, self) btn1.move(x, y) btn1.clicked.connect(action) btn1.setVisible(visibility) return btn1 def save_data(self): f = open("data/settings.txt", "w") f.write(self.textbox1.text() + "\n") f.write(self.textbox2.text() + "\n") f.write(self.textbox3.text() + "\n") f.close() self.close()
class ViewWidget(QWidget): exercise_name_label = None exercise_name_line = None scroll_area = None base_widget = None exercises_widget = None return_button = None add_button = None def __init__(self): QWidget.__init__(self) self.file = "" self.setup_widget() def setup_widget(self): self.exercise_name_label = QLabel("Exercise name:", self) self.exercise_name_label.move(5, 5) self.exercise_name_label.resize(125, 25) self.add_button = QPushButton("Add", self) self.add_button.resize(75, 25) self.add_button.clicked.connect(self.add_line) self.exercise_name_line = QLineEdit(self) self.exercise_name_line.move(135, 5) self.exercise_name_line.resize(125, 25) self.scroll_area = QScrollArea(self) self.base_widget = QWidget(self) self.scroll_area.setWidget(self.base_widget) self.exercises_widget = QVBoxLayout() self.exercises_widget.setAlignment(Qt.AlignTop) self.base_widget.setLayout(self.exercises_widget) self.return_button = QPushButton("Return wo save", self) def resizeEvent(self, event): self.scroll_area.move(5, 35) self.scroll_area.resize(self.width() - 165, self.height() - 40) self.add_button.move(self.width() - 160 - 75, 5) self.return_button.move(self.width() - 155, 5) self.return_button.resize(150, 40) self.base_widget.resize(self.scroll_area.width() - 25, self.exercises_widget.count() * 25) def clear_widget(self): while self.exercises_widget.count() > 0: self.exercises_widget.takeAt(0) def open_exercise_file(self, file: str): self.file = file with open(self.file, "r") as json_file: json_data = json.load(json_file) name = json_data['name'] for data in json_data['exercise']: movement = data['name'] description = data['description'] time = data['time'] widget = PanelWidget() widget.set_data(movement, description, time) widget.remove_signal.connect(self.remove_panel_item) widget.move_down_signal.connect(self.move_widget_down) widget.move_up_signal.connect(self.move_widget_up) self.exercises_widget.addWidget(widget) json_file.close() self.base_widget.resize(self.scroll_area.width() - 25, self.exercises_widget.count() * 25) self.exercise_name_line.setText(name) @Slot() def add_line(self): widget = PanelWidget() self.exercises_widget.addWidget(widget) self.base_widget.resize(self.scroll_area.width() - 25, self.exercises_widget.count() * 25) @Slot(QWidget) def move_widget_down(self, widget: QWidget): ind = self.exercises_widget.indexOf(widget) self.exercises_widget.removeWidget(widget) self.exercises_widget.insertWidget((ind + 1), widget) @Slot(QWidget) def move_widget_up(self, widget: QWidget): ind = self.exercises_widget.indexOf(widget) self.exercises_widget.removeWidget(widget) self.exercises_widget.insertWidget((ind - 1), widget) @Slot(QWidget) def remove_panel_item(self, widget: QWidget): self.exercises_widget.removeWidget(widget) self.base_widget.resize(self.scroll_area.width() - 25, self.exercises_widget.count() * 25)
class JDaApp(QWidget): def __init__(self): super().__init__() self.iniciaUI() def iniciaUI(self): """ Inicializa a janela e mostra seu conteuda na tela """ self.setGeometry(100, 100, 400, 200) self.setWindowTitle("Login") self.displayWidgets() self.show() def displayWidgets(self): """ Configura os widgets da app """ info_lbl = QLabel(self) info_lbl.setText("Lista de Funcionarios") info_lbl.move(20, 20) # localiza o label na tela info_lbl.setFont(QFont('Arial', 20)) quest_lbl = QLabel(self) quest_lbl.setText("Entre o nome do funcionarioa que procura:") quest_lbl.move(40, 60) # localiza o label na tela nome_lbl = QLabel("Nome:", self) nome_lbl.move(50, 90) # localiza o label na tela self.nome_edit = QLineEdit(self) self.nome_edit.setAlignment(Qt.AlignLeft) # Este é o padrão self.nome_edit.move(95, 90) self.nome_edit.resize(240, 20) # mudando o tamanho da caixa de texto self.nome_edit.setPlaceholderText("nome sobrenome") self.pesq_btn = QPushButton('Procurar', self) self.pesq_btn.clicked.connect(self.displayMessageBox) self.pesq_btn.move(125, 130) # localizando o botão na tela self.pesq_btn.resize(150, 40) def displayMessageBox(self): """ Quando o butão for acionado procurar na lista de funcionarios. Se o funcionario for localizado o app mostra uma mensagem de Funcionario localizado. Caso contrario mostra a mensagem Funcionario não localizado """ try: with open("funcionarios.txt", 'r') as f: funcionarios = [line.rstrip('\n') for line in f] except FileNotFoundError: print( "O arquivo com a lista de funcionarios (funcionarios.txt) não foi encontrado." ) # Procurando o funcionario na lista msg_no_encontrado = QMessageBox() if self.nome_edit.text() in funcionarios: QMessageBox().information(self, "Funcionario Localizado", "Funcionario localizado na lista!", QMessageBox.Ok, QMessageBox.Ok) else: msg_no_encontrado = QMessageBox().question( self, "Funcionario Não Localizado", "Funcionario não consta na lista!\nDeseja continuar?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if msg_no_encontrado == QMessageBox.No: print("Closing application.") self.close() else: pass
def ui_components(self): font = QFont("Roboto", 16) title_label = QLabel("Convert currency:", self) title_label.move(7, 27) title_label.setFont(font) title_label.adjustSize() to_be_converted = QLineEdit(self) to_be_converted.setPlaceholderText("Amount") to_be_converted.setFont(font) to_be_converted.move(7, 67) to_be_converted.setFixedWidth(230) valid = QDoubleValidator() to_be_converted.setValidator(valid) converted = QLineEdit(self) converted.setPlaceholderText("Converted Amount") converted.isEnabled = False converted.move(7, 107) converted.setFixedWidth(230) converted.setFont(font) converted.setValidator(valid) currency_list_1 = QComboBox(self) currency_list_1.addItem("USD") currency_list_1.addItem("TND") currency_list_1.addItem("EUR") currency_list_1.move(260, 66) currency_list_2 = QComboBox(self) currency_list_2.addItem("USD") currency_list_2.addItem("TND") currency_list_2.addItem("EUR") currency_list_2.move(260, 100) convert_btn = QPushButton("Convert", self) convert_btn.move(260, 140) menubar = QMenuBar(self) Info = menubar.addMenu("Info") exchange = Info.addAction("Exchange rates") exchange.triggered.connect(self.open_exchange_rates) def convertor(): if str(currency_list_1.currentText()) == "USD" or str( currency_list_2.currentText()) == "USD": # ============== USD AND TND ================== if str(currency_list_2.currentText()) == "TND": rate_usd_tnd = Exchanges().usd_tnd() converted_amount = float( to_be_converted.text()) * float(rate_usd_tnd) if to_be_converted != '': converted.setText(str(converted_amount)) if str(currency_list_1.currentText()) == "TND": rate_usd_tnd = Exchanges().usd_tnd() converted_amount = float(to_be_converted.text()) * float( 1 / rate_usd_tnd) if to_be_converted != '': converted.setText(str(converted_amount)) # =============== EUR AND USD ================= if str(currency_list_2.currentText()) == "EUR": rate_usd_eur = Exchanges().usd_eur() converted_amount = float( to_be_converted.text()) * float(rate_usd_eur) if to_be_converted != '': converted.setText(str(converted_amount)) if str(currency_list_1.currentText()) == "EUR": rate_usd_eur = Exchanges().usd_eur() converted_amount = float(to_be_converted.text()) * float( 1 / rate_usd_eur) if to_be_converted != '': converted.setText(str(converted_amount)) if (currency_list_1.currentText()) == "TND" or ( currency_list_2.currentText()) == "TND": if str(currency_list_2.currentText()) == "EUR": rate_tnd_eur = Exchanges().tnd_eur() converted_amount = float( to_be_converted.text()) * float(rate_tnd_eur) if to_be_converted != '': converted.setText(str(converted_amount)) if str(currency_list_1.currentText()) == "EUR": rate_tnd_eur = Exchanges().tnd_eur() converted_amount = float(to_be_converted.text()) * float( 1 / rate_tnd_eur) if to_be_converted != '': converted.setText(str(converted_amount)) convert_btn.clicked.connect(convertor)
import sys from PySide2.QtWidgets import QApplication, QMainWindow, QLineEdit, QLabel aplicacao = QApplication(sys.argv) janela = QMainWindow() janela.setGeometry(100, 50, 300, 200) janela.setWindowTitle("Primeira Janela") texto_entrada = QLineEdit(janela) texto_entrada.move(50, 30) texto_entrada.resize(200, 30) label = QLabel("Escreva algo e aperte <enter>", janela) label.move(50, 60) label.resize(200, 30) result = QLabel("", janela) result.move(50, 90) result.resize(200, 30) def onReturnPressed(): result.setText(texto_entrada.text()) # quando o usuário pressionar <enter> na caixa de texto texto_entrada.returnPressed.connect(onReturnPressed) janela.show() aplicacao.exec_() sys.exit()
class JDaApp(QWidget): def __init__(self): super().__init__() self.iniciaUI() def iniciaUI(self): """ Inicializa a janela e mostra seu conteuda na tela """ self.setGeometry(100,100, 400, 230) self.setWindowTitle("Login") self.displayWidgets() self.show() def displayWidgets(self): """ Configura os widgets da app """ login_lbl = QLabel(self) login_lbl.setText("login") login_lbl.move(180, 10) # localiza o label na tela login_lbl.setFont(QFont('Arial', 20)) nome_lbl = QLabel("usuário:", self) nome_lbl.move(30, 60) # localiza o label na tela self.nome_edit = QLineEdit(self) self.nome_edit.setAlignment(Qt.AlignLeft) # Este é o padrão self.nome_edit.move(110, 60) self.nome_edit.resize(220, 20) # mudando o tamanho da caixa de texto pwd_lbl = QLabel("senha:", self) pwd_lbl.move(30, 90) # localiza o label na tela self.pwd_edit = QLineEdit(self) self.pwd_edit.setEchoMode(QLineEdit.Password) self.pwd_edit.setAlignment(Qt.AlignLeft) # Este é o padrão self.pwd_edit.move(110, 90) self.pwd_edit.resize(220, 20) # mudando o tamanho da caixa de texto sigin_btn = QPushButton('login', self) sigin_btn.clicked.connect(self.clickLogin) sigin_btn.move(100, 140) # localizando o botão na tela sigin_btn.resize(200, 40) show_pwd_cbx = QCheckBox("Mostrar a senha", self) show_pwd_cbx.move(110, 115) show_pwd_cbx.toggle() show_pwd_cbx.setChecked(False) show_pwd_cbx.stateChanged.connect(self.showPassword) out_lbl = QLabel("não é usuário?", self) out_lbl.move(50, 200) # localiza o label na tela sigup_btn = QPushButton('registrar', self) sigup_btn.clicked.connect(self.criarNovo) sigup_btn.move(160, 190) # localizando o botão na tela def clickLogin(self): """ Quando o usuário acionar o botão de login, verifica se o usuário e o login conferem. Os registros estão no arquivo usuarios.txt. Se existe, apresenta uma mensagem e fecha o app Se não, mostra uma mensagem de erro """ usuarios = {} try: with open("usuarios.txt", 'r') as f: for line in f: campos = line.split(" ") username = campos[0] senha = campos[1].strip('\n') usuarios[username] = senha except FileNotFoundError: print("O arquivo de usuários (usuarios.txt) não foi encontrado.") f = open("usuarios.txt", 'w') username = self.nome_edit.text() senha = self.pwd_edit.text() if (username, senha) in usuarios.items(): QMessageBox.information(self, "Registro Ok", "Login realizado com sicesso", QMessageBox.Ok, QMessageBox.Ok) self.close() else: QMessageBox.warning(self, "Problemas!", "Senha o nome do usuário incorecto", QMessageBox.Close, QMessageBox.Close) def showPassword(self, state): """ Se o checkbox esta ativado,mostra a senha Caso contrario mascara a senha para ocultar """ if state == Qt.Checked: self.pwd_edit.setEchoMode(QLineEdit.Normal) else: self.pwd_edit.setEchoMode(QLineEdit.Password) def criarNovo(self): """ Quando o botão for acionado, abrir nova janela para registrar um novo usuário """ self.criar_novo_usuario = CriarNovoUsr() self.criar_novo_usuario.show() def closeEvent(self, event): """ Exiba um QMessageBox ao perguntar ao usuário se deseja sair do programa. """ quit_msg = QMessageBox.question(self, "Sair da aplicação?", "Você tem certeza que quer sair?", QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes) if quit_msg == QMessageBox.Yes: event.accept() else: event.ignore()
class MapWidget(QQuickWidget): def __init__(self, data, model): super(MapWidget, self).__init__(resizeMode=QQuickWidget.SizeRootObjectToView) self.data = data self.model = model self.attribute_button = QPushButton(self) self.attribute_button.setStyleSheet("color: black") self.menu = QMenu("Pick an attribute", self) # Create Menu Options self.humidity_attribute = QAction("humidity") self.pressure_attribute = QAction("pressure") self.temperature_attribute = QAction("temperature") self.wind_speed_attribute = QAction("wind_speed") # due to frequent access of dates based on index, we store this data separately self.uniqueDates = self.data["datetime"].apply( lambda x: x.split(' ')[0]).unique().tolist() self.aggregation = 1 self.rootContext().setContextProperty("markermodel", model) self.rootContext().setContextProperty("MapWidget", self) qml_path = os.path.join(os.path.dirname(__file__), "map.qml") self.setSource(QUrl.fromLocalFile(qml_path)) positions = self.get_positions(self.data) names = self.get_names(self.data) # get first date of dataset in yy-mm-dd self.currentDate = self.uniqueDates[0] # Set Labels self.date_label = QLabel( "selected date: " + str(self.currentDate).replace("-", "."), self) self.date_label.setStyleSheet("color: black") # Set Previous and Next Buttons self.previous_button = QPushButton("Previous", self) self.next_button = QPushButton("Next", self) self.previous_button.clicked.connect( partial(self.on_button_clicked, "previous")) self.next_button.clicked.connect( partial(self.on_button_clicked, "next")) values = self.get_values(self.data, "humidity") colors = self.get_colors(self.data, "humidity") for i in range(0, len(names)): geo_coordinates = QGeoCoordinate(positions[i][0], positions[i][1]) name = names[i] value = values[i] color = colors[i] model.append_marker({ "position": geo_coordinates, "color": color, "name": name, "value": value, "date": self.currentDate }) self.create_interface() return def add_attribute_to_menu(self, attribute_action, attribute): attribute_action.triggered.connect(lambda: self.clicked(attribute)) self.menu.addAction(attribute_action) def create_date_picker(self, index): tmp_time = self.uniqueDates[index] time_QFormat = tmp_time.split("-") # date is parsed and converted to int to comply with required format of QDate date_picker = QDateTimeEdit( QDate(int(time_QFormat[0]), int(time_QFormat[1]), int(time_QFormat[2])), self) date_picker.setDisplayFormat("yyyy.MM.dd") date_picker.setCalendarPopup(True) date_picker.setCalendarWidget(QCalendarWidget()) date_picker.resize(date_picker.width() + 20, date_picker.height()) return date_picker def set_date_pickers(self, slider): # Set Date Picker for Start of self.slider date_picker_start = self.create_date_picker(0) date_picker_start.setToolTip( "Select the BEGINNING of the time period from which the data is displayed" ) date_picker_start.move( slider.property("x") - date_picker_start.width() - 30, slider.property("y")) # Set Date Picker for End of self.slider date_picker_end = self.create_date_picker(-1) date_picker_end.setToolTip( "Select the END of the time period from which the data is displayed" ) date_picker_end.move( slider.property("x") + slider.property("width") + 30, slider.property("y")) # Set Date Pickers Boundaries Based on First and Last Date in Given Data date_picker_start.setMinimumDate(date_picker_start.date()) date_picker_end.setMinimumDate(date_picker_start.date()) date_picker_start.setMaximumDate(date_picker_end.date()) date_picker_end.setMaximumDate(date_picker_end.date()) return date_picker_start, date_picker_end def create_interface(self): self.attribute_button.move(50, 0) # Create a Menu Option for Each Attribute self.add_attribute_to_menu(self.humidity_attribute, "humidity") self.add_attribute_to_menu(self.pressure_attribute, "pressure") self.add_attribute_to_menu(self.temperature_attribute, "temperature") self.add_attribute_to_menu(self.wind_speed_attribute, "wind_speed") self.attribute_button.setMenu(self.menu) self.attribute_button.resize(self.menu.width() + 50, self.attribute_button.height()) # Get self.slider from QML File self.slider = self.rootObject().findChild(QObject, "slider") # Set Date Pickers self.date_picker_start, self.date_picker_end = self.set_date_pickers( self.slider) self.date_picker_start.dateChanged.connect(lambda: self.change_date( self.slider, self.self.date_picker_start, self.date_picker_end)) self.date_picker_end.dateChanged.connect(lambda: self.change_date( self.slider, self.self.date_picker_start, self.date_picker_end)) # Label Holding the Current Date Selected by User self.date_label.move( self.slider.property("x") + (self.slider.width() / 2) - 100, self.slider.property("y") + 30) self.date_label.adjustSize() # Set Buttons Position self.previous_button.setStyleSheet("color: black") self.previous_button.move(self.slider.property("x"), self.slider.property("y") + 50) self.previous_button.adjustSize() self.next_button.setStyleSheet("color: black") self.next_button.move( self.slider.property("x") + self.slider.width() - 70, self.slider.property("y") + 50) self.next_button.adjustSize() jump_label = QLabel("self.slider jump (in days): ", self) jump_label.setStyleSheet("color: black") jump_label.move(self.date_label.x(), self.date_label.y() + 40) jump_label.adjustSize() self.jump_value = QLineEdit(self) self.jump_value.move(jump_label.x() + jump_label.width(), jump_label.y() - 5) self.jump_value.resize(35, self.jump_value.height()) self.jump_value.editingFinished.connect( lambda: self.slider.setProperty("stepSize", self.jump_value.text() )) agg_label = QLabel(self) agg_label.setStyleSheet("color: black") agg_label.move(self.date_label.x(), self.jump_value.y() + 40) agg_label.setText("mean (in days): ") agg_label.adjustSize() agg_value = QLineEdit(self) agg_value.move(self.jump_value.x(), agg_label.y() - 5) agg_value.resize(35, agg_value.height()) agg_value.editingFinished.connect( lambda: self.set_agg(agg_value.text())) # Initialize Visualization self.humidity_attribute.trigger() self.change_date(self.slider, self.date_picker_start, self.date_picker_end) def on_button_clicked(self, action): jump_value = int(self.jump_value.text()) slider_value = int(self.slider.property("value")) current_date = pandas.to_datetime(self.currentDate) start_date = self.date_picker_start.date().toPython() end_date = self.date_picker_end.date().toPython() if action == "next": if current_date + datetime.timedelta(days=jump_value) <= end_date: self.slider.setProperty("value", slider_value + jump_value) self.update_date(int(self.slider.property("value"))) elif action == "previous": if current_date - datetime.timedelta( days=jump_value) >= start_date: self.slider.setProperty("value", slider_value - jump_value) self.update_date(int(self.slider.property("value"))) @Slot(int) def update_date(self, value): self.currentDate = self.uniqueDates[value - 1] self.date_label.setText("selected date: " + str(self.currentDate).replace("-", ".")) self.clicked(self.attribute_button.text()) # TODO: visualise time series data, not just int created by aggregation # TODO: create setting of visualised time period for user # calculates the difference (in days) between start date and end date and rescales the self.slider def set_agg(self, value): self.aggregation = int(value) self.clicked(self.attribute_button.text()) def change_date(self, slider, date_picker_start, date_picker_end): dif = self.uniqueDates\ .index(date_picker_end.date().toString("yyyy-MM-dd")) - self.uniqueDates.index(date_picker_start.date().toString("yyyy-MM-dd")) slider.setProperty("to", dif + 1) # when button is clicked, changes values in all model items to a different attribute def clicked(self, attribute): self.attribute_button.setText(attribute) values = self.get_values(self.data, attribute) colors = self.get_colors(self.data, attribute) for i in range(0, len(values)): self.model.setData(i, values[i], colors[i], MarkerModel.ValueRole) @staticmethod def get_positions(data): tmp = data.drop_duplicates('city').sort_values(by=['city']) positions = [[x, y] for x, y in zip(tmp['latitude'], tmp['longitude'])] return positions @staticmethod def get_names(data): tmp = data.drop_duplicates('city').sort_values(by=['city']) names = tmp['city'].values.tolist() return names # creates an ordered list of aggregated values of a specified attribute def get_values(self, data, attribute): data['datetime'] = pandas.to_datetime(data['datetime']) start_date = pandas.to_datetime(self.currentDate) end_date = start_date + datetime.timedelta(days=self.aggregation) tmp = data[data['datetime'] >= start_date] tmp = tmp[tmp['datetime'] <= end_date] values = tmp.groupby('city').apply( lambda x: x[attribute].mean()).values.round(2).tolist() return values @staticmethod def get_colors(data, attribute): tmp = data.groupby('city').agg({attribute: 'mean'}) max_value = round(tmp[attribute].max()) min_value = round(tmp[attribute].min()) diff = max_value - min_value step = round(1 / 6 * diff) if attribute == 'pressure': attribute_values = { 0: [255, 255, 255], 1: [204, 229, 255], 2: [102, 178, 255], 3: [0, 128, 255], 4: [0, 0, 255], 5: [0, 0, 102], 6: [0, 0, 51] } elif attribute == 'temperature': attribute_values = { 0: [0, 102, 204], 1: [102, 178, 255], 2: [204, 229, 255], 3: [255, 204, 204], 4: [255, 102, 102], 5: [204, 0, 0], 6: [102, 0, 0] } # TODO: create more suited colors for humidity and wind speed elif attribute == 'humidity': attribute_values = { 0: [0, 102, 204], 1: [102, 178, 255], 2: [204, 229, 255], 3: [255, 204, 204], 4: [255, 102, 102], 5: [204, 0, 0], 6: [102, 0, 0] } elif attribute == 'wind_speed': attribute_values = { 0: [0, 102, 204], 1: [102, 178, 255], 2: [204, 229, 255], 3: [255, 204, 204], 4: [255, 102, 102], 5: [204, 0, 0], 6: [102, 0, 0] } values = numpy.array([ min_value, min_value + 1 * step, min_value + 2 * step, min_value + 3 * step, min_value + 4 * step, min_value + 5 * step, max_value ]) tmp['distances'] = tmp[attribute].apply(lambda x: abs(x - values)) tmp['index'] = tmp['distances'].apply(lambda x: numpy.argmin(x)) tmp['color'] = tmp['index'].apply(lambda x: attribute_values.get(x)) colors = tmp['color'].tolist() colors_list = [] for color_tmp in colors: color = QColor(color_tmp[0], color_tmp[1], color_tmp[2], 255) colors_list.append(color) # returns QJSValue return colors_list def createAction(self, attribute): action = QAction(attribute) action.triggered.connect(self.clicked(attribute)) self.menu.addAction(action) return action
def box_gen(self, x, y, resource=''): group_box = QGroupBox(self.window) group_box.move(x, y) group_box.resize(self.box_width, self.box_height) if resource == '': return [] group_box.setTitle('') group_box.setStyleSheet('QGroupBox { background-color: \ rgb(255, 255, 255); border: 3px solid rgb(122, 255, 100); } \ QGroupBox::title{font: 75 ' + str(100 * self.screen_ratio) + 'pt "宋体"; color: rgb(255, 0, 0)}') label_again = QLabel(group_box) label_again.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"; color: rgb(255, 0, 0)}') label_again.setText(resource) label_again.move(int(self.grid_width * 0.7), 5 * self.screen_ratio) label_again.resize(int(self.grid_width * 3.3), self.init_bias - 5) product_label00 = QLabel(group_box) product_label00.setText('产量') product_label00.move(3, self.init_bias) product_label00.resize(self.grid_width, self.grid_height) product_label00.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product00 = QLineEdit(group_box) product00.setText('0') product00.move(self.grid_width, self.init_bias) product00.resize(self.grid_width, self.grid_height) product00.setEnabled(False) product00.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') product_label10 = QLabel(group_box) product_label10.setText('额外') product_label10.move(3, self.grid_height + self.init_bias) product_label10.resize(self.grid_width, self.grid_height) product_label10.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product10 = QLineEdit(group_box) product10.setText('0') product10.move(self.grid_width, self.grid_height + self.init_bias) product10.resize(self.grid_width, self.grid_height) product10.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') product_label01 = QLabel(group_box) product_label01.setText('机器') product_label01.move(self.grid_width * 2 + self.interval, self.init_bias) product_label01.resize(self.grid_width, self.grid_height) product_label01.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product01 = QLineEdit(group_box) product01.setText('0.0') product01.move(self.grid_width * 3 + self.interval, self.init_bias) product01.resize(self.grid_width, self.grid_height) product01.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') product01.setEnabled(False) product_label11 = QLabel(group_box) product_label11.setText('已有') product_label11.move(self.grid_width * 2 + self.interval, self.grid_height + self.init_bias) product_label11.resize(self.grid_width, self.grid_height) product_label11.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product11 = QLineEdit(group_box) product11.setText('0') product11.move(self.grid_width * 3 + self.interval, self.grid_height + self.init_bias) product11.resize(self.grid_width, self.grid_height) product11.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') if resource in self.supporter: product11.setEnabled(True) else: product11.setEnabled(False) return [product00, product01, product10, product11]
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(400, 250)) self.setWindowTitle("Automate outlook mailing") self.extractAction = QtWidgets.QAction("&Info", self) self.extractAction.setShortcut("Ctrl+I") self.extractAction.setStatusTip('Get Info') self.extractAction.triggered.connect(self.get_info) self.statusBar() self.mainMenu = self.menuBar() self.aboutMenu = self.mainMenu.addMenu('&About') self.aboutMenu.addAction(self.extractAction) self.LabelExcelFile = QLabel(self) self.LabelExcelFile.setText('Excel :') self.LabelExcelFile.move(20, 20) self.line = QLineEdit(self) self.line.move(80, 20) self.line.resize(200, 25) self.searchFileButton = QPushButton("Load", self) self.searchFileButton.clicked.connect(self.searchAndLoadFile) self.searchFileButton.move(300, 20) self.searchFileButton.resize(75, 25) # self.layout.addWidget(self.searchFileButton,2, 1, 1, 1) self.nameLabel = QLabel(self) self.nameLabel.setText('Subject :') self.nameLabel.move(20, 60) self.LineSubject = QLineEdit(self) self.LineSubject.move(80, 60) self.LineSubject.resize(200, 25) self.LabelArea = QLabel(self) self.LabelArea.setText('Body :') self.LabelArea.move(20, 100) self.text_area = QTextEdit(self) self.text_area.resize(200, 80) self.text_area.move(80, 100) self.pybutton = QPushButton('Save', self) self.pybutton.clicked.connect(self.clickMethod) self.pybutton.resize(200,32) self.pybutton.move(80, 200) self.createExample = QPushButton('Example File', self) self.createExample.clicked.connect(myExcel.CreateExample) self.createExample.resize(75,32) self.createExample.move(300, 100) self.autorun = QPushButton('Auto Run Off', self) self.autorun.clicked.connect(self.set_auto_run) self.autorun.resize(75,32) self.autorun.move(300, 150) self.autorun.setCheckable(True) self.start = QPushButton('Run', self) self.start.clicked.connect(self.run_business) self.start.resize(75,32) self.start.move(300, 200) def run_business(self): print("The business program starts") myBusiness.the_aim_of_the_program() pass def set_auto_run(self): """ print("Select Example") #self.button2.click() self.button2.setChecked(True) if self.button4.isChecked(): print("button4 is checked") self.button4.setChecked(False) pass else: print("button4 isnt checked") pass """ if self.autorun.isChecked(): print("autorun button is checked") self.autorun.setChecked(True) self.autorun.setText('Auto Run On') self.save_something('Automate outlook mailing','auto_run', 'True') pass else: self.autorun.setChecked(False) print("autorun button isnt checked") self.autorun.setText('Auto Run Off') self.save_something('Automate outlook mailing','auto_run', 'False') pass print("The business program starts") # myBusiness.the_aim_of_the_program() pass def save_something(self,section,somekey,something): if myConfig.configuration_file_has_been_persisted(): print("The program starts") #print(myConfig.get_saved_data("EXCEL","subject")) else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass myConfig.configuration_file_set_something_to_save(section,somekey,something) pass def clickMethod(self): print('Your name: ' + self.line.text()) if myConfig.configuration_file_has_been_persisted(): print("The program starts") print(myConfig.get_saved_data("EXCEL","subject")) else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass if self.line.text() != "": myConfig.configuration_file_set_something_to_save("EXCEL","file",self.line.text()) pass if self.LineSubject.text() != "": myConfig.configuration_file_set_something_to_save("EMAIL","subject",self.LineSubject.text()) pass if self.text_area.toPlainText() != "": myConfig.configuration_file_set_something_to_save("EMAIL","body",self.text_area.toPlainText()) pass # print(self.text_area.toPlainText()) #print(myConfig.get_mail_data()['subject']) # myConfig.configuration_file_create_persist() pass """ excel_file = "~tempfile.1.xlsx" #myExcel.getDataFromExcel(excel_file) if myConfig.configuration_file_has_been_persisted(): print("The program starts") print(myConfig.check_data("EMAIL",'subject')) # for key in (myConfig.get_mail_data()): print(key) if myConfig.check_data("EMAIL",'subject'): print(myConfig.get_mail_data()['subject']) myConfig.get_mail_data()['subject'] pass else: myConfig.configuration_file_create_persist() pass #myExcel.getDataFromExcel(excel_file,) pass else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass # myConfig.configuration_file_create_persist() pass """ def setFromConfigurationFile(self): #excel_file = "~tempfile.1.xlsx" #myExcel.getDataFromExcel(excel_file) if myConfig.configuration_file_has_been_persisted(): print("The program starts") #print(myConfig.check_data("EMAIL",'subject')) # for key in (myConfig.get_mail_data()): print(key) if myConfig.check_data("EMAIL",'subject'): #print(myConfig.get_mail_data()['subject']) #myConfig.get_mail_data()['subject'] print() print() print() self.line.setText(myConfig.get_saved_data("EXCEL",'file')) # self.line.setText("Hola perro") self.LineSubject.setText(myConfig.get_saved_data("EMAIL",'subject')) self.text_area.setText(myConfig.get_saved_data("EMAIL",'body')) if myConfig.check_data('Automate outlook mailing','auto_run'): if myConfig.get_saved_data('Automate outlook mailing','auto_run') == "True": self.autorun.setChecked(True) self.autorun.setText('Auto Run On') print('Auto Run On') pass else: self.autorun.setChecked(False) self.autorun.setText('Auto Run Off') print('Auto Run Off') pass pass else: print('auto_run not exist') myConfig.configuration_file_create_persist() pass pass else: myConfig.configuration_file_create_persist() pass #myExcel.getDataFromExcel(excel_file,) pass else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass pass def searchAndLoadFile(self): #path_to_file, _ = QFileDialog.getOpenFileName(self, self.tr("Load Image"), self.tr("~/Desktop/"), self.tr("Images (*.jpg)")) current_location = myConfig.getPathExternal("") path_to_file, _ = QFileDialog.getOpenFileName(self, self.tr("Load Excel"), self.tr("~/Desktop/"), self.tr(current_location+" (*.xlsx)")) #self.test(path_to_file) print(path_to_file) #self.testFuncion(path_to_file) # self.filenameLoaded = path_to_file self.line.setText(path_to_file) def close_application(self): choice = QtWidgets.QMessageBox.question(self, 'Extract!', "Get into the chopper?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.Yes: print("Extracting Naaaaaaoooww!!!!") sys.exit() else: pass def close_application_timeout(self): print("Shooting down") """ import time time.sleep(myBusiness.get_after_delay()) sys.exit() """ QtCore.QTimer.singleShot(30000, self.close) pass def get_info(self): # https://stackoverflow.com/questions/15682665/how-to-add-custom-button-to-a-qmessagebox-in-pyqt4 # https://pythonprogramming.net/pop-up-messages-pyqt-tutorial/ """ self.msgBox = QtWidgets.QMessageBox() self.msgBox.setText('What to do?') self.msgBox.addButton(QtWidgets.QPushButton('Accept'), QtWidgets.QMessageBox.YesRole) self.msgBox.addButton(QtWidgets.QPushButton('Reject'), QtWidgets.QMessageBox.NoRole) self.msgBox.addButton(QtWidgets.QPushButton('Cancel'), QtWidgets.QMessageBox.RejectRole) ret = self.msgBox.exec_() self.msgBox.question(self, 'About Developer', "my name is luca if you want to contact me\nmy email is [email protected]", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) #ret = self.msgBox.exec_() """ choice = QtWidgets.QMessageBox.question(self, 'About Developer', "my name is luca, if you want to contact me\nyou can send me an email to\[email protected]\n\nSend email?(yes/no)", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.Yes: print("Redirect to send email") import webbrowser webbrowser.open('mailto:[email protected]?subject=Hi Luca&body=How are you?🧙♂️') # Go to example.com # sys.exit() else: pass
class CriarNovoUsr(QWidget): """ Inicializa a janela e mostra seu conteuda na tela """ def __init__(self): super().__init__() self.iniciaUI() def iniciaUI(self): """ Inicializa a janela e mostra seu conteuda na tela """ self.setGeometry(100,100, 400, 400) self.setWindowTitle("Criar Novo Usuário") self.displayWidgets() self.show() def displayWidgets(self): """ Configura os widgets da janela """ # Criando um label para uma imagem usr_img = "Imagens/pessoa.png" try: with open(usr_img): novo_usr = QLabel(self) pixmap = QPixmap(usr_img) pixmap = pixmap.scaled(100, 100) novo_usr.setPixmap(pixmap) novo_usr.move(150, 60) except FileNotFoundError: print("A imagem não esta disponível!") login_lbl = QLabel(self) login_lbl.setText("criar nova conta") login_lbl.move(110, 20) login_lbl.setFont(QFont('Arial', 20)) # label e caixa de texto para nomes nome_lbl = QLabel("nome de usuário:", self) nome_lbl.move(30, 180) self.nome_edit = QLineEdit(self) self.nome_edit.move(150, 180) self.nome_edit.resize(200, 20) nomeC_usr_lbl = QLabel("nome completo:", self) nomeC_usr_lbl.move(30, 210) self.nomeC_edit = QLineEdit(self) self.nomeC_edit.move(150, 210) self.nomeC_edit.resize(200, 20) pswd_lbl = QLabel("senha:", self) pswd_lbl.move(30, 240) self.pswd_edit = QLineEdit(self) self.pswd_edit.setEchoMode(QLineEdit.Password) self.pswd_edit.move(130, 240) self.pswd_edit.resize(200, 20) conf_lbl = QLabel("confirmar:", self) conf_lbl.move(30, 270) self.conf_edit = QLineEdit(self) self.conf_edit.setEchoMode(QLineEdit.Password) self.conf_edit.move(130, 270) self.conf_edit.resize(200, 20) sigup_btn = QPushButton("Sign up", self) sigup_btn.move(100, 310) sigup_btn.resize(200,40) sigup_btn.clicked.connect(self.confirmarSignUp) def confirmarSignUp(self): """ Quando o usuário preciona sign-up verifica se as senhas batem. Se confirmar então guarda o usuário e a senha no arquivo usuarios.txt """ pswd_text = self.pswd_edit.text() conf_text = self.conf_edit.text() if pswd_text != conf_text: QMessageBox.warning(self, "Mensagem de Erro", "As senhas que vc digitou não estão batendo. Digite novamente!", QMessageBox.Close, QMessageBox.Close) else: with open("usuarios.txt", "a+") as f: f.write(self.nome_edit.text() + " ") f.write(pswd_text + "\n") self.close()
import sys from PySide2.QtWidgets import QApplication, QMainWindow, QLineEdit aplicacao = QApplication(sys.argv) janela = QMainWindow() # setGeometry(esquerda, topo, largura, altura) janela.setGeometry(100, 50, 300, 200) janela.setWindowTitle("Primeira Janela") # cria um campo de entrada de texto na janela texto_entrada = QLineEdit(janela) # posição (esquerda, topo) texto_entrada.move(50, 75) # tamanho (largura, altura) texto_entrada.resize(200, 50) # estilo da caixa de texto texto_entrada.setStyleSheet('QLineEdit \ {font-size: 22px; font-style: italic; padding: 15px}') janela.show() aplicacao.exec_() sys.exit()
class Editor(QPlainTextEdit): keyPressed = Signal(QEvent) class _NumberArea(QWidget): def __init__(self, editor): super().__init__(editor) self.codeEditor = editor def sizeHint(self): return QSize(self.editor.lineNumberAreaWidth(), 0) def paintEvent(self, event): self.codeEditor.lineNumberAreaPaintEvent(event) def __init__(self, **kwargs): parent = kwargs["parent"] if "parent" in kwargs else None super().__init__(parent) self._addSaveAction = kwargs[ "saveAction"] if "saveAction" in kwargs else False self._addSaveAction = kwargs[ "saveAction"] if "saveAction" in kwargs else False if self._addSaveAction: self.saveACT = QAction("Save") self.saveACT.setShortcut(QKeySequence("Ctrl+S")) self.saveACT.triggered.connect( lambda: self._save_file(self.toPlainText())) self.addAction(self.saveACT) self._saveCB = kwargs[ "saveFunction"] if "saveFunction" in kwargs else None self.setFont(QFont("Courier New", 11)) self.lineNumberArea = Editor._NumberArea(self) self.blockCountChanged.connect(self.updateLineNumberAreaWidth) self.updateRequest.connect(self.updateLineNumberArea) self.cursorPositionChanged.connect(self.highlightCurrentLine) self.updateLineNumberAreaWidth(0) self.findHighlightFormat = QTextCharFormat() self.findHighlightFormat.setBackground(QBrush(QColor("red"))) self.searchTxtBx = None def lineNumberAreaWidth(self): digits = 5 max_value = max(1, self.blockCount()) while max_value >= 10: max_value /= 10 digits += 1 space = 3 + self.fontMetrics().width('9') * digits return space def updateLineNumberAreaWidth(self, _): self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0) def updateLineNumberArea(self, rect, dy): if dy: self.lineNumberArea.scroll(0, dy) else: self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height()) if rect.contains(self.viewport().rect()): self.updateLineNumberAreaWidth(0) def resizeEvent(self, event): super().resizeEvent(event) cr = self.contentsRect() self.lineNumberArea.setGeometry( QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height())) def highlightCurrentLine(self): extraSelections = [] if not self.isReadOnly(): selection = QTextEdit.ExtraSelection() lineColor = QColor(229, 248, 255, 255) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.setExtraSelections(extraSelections) def lineNumberAreaPaintEvent(self, event): painter = QPainter(self.lineNumberArea) painter.fillRect(event.rect(), QColor(233, 233, 233, 255)) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = self.blockBoundingGeometry(block).translated( self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() # Just to make sure I use the right font height = self.fontMetrics().height() while block.isValid() and (top <= event.rect().bottom()): if block.isVisible() and (bottom >= event.rect().top()): number = str(blockNumber + 1) fFont = QFont("Courier New", 10) painter.setPen(QColor(130, 130, 130, 255)) painter.setFont(fFont) painter.drawText(0, top, self.lineNumberArea.width(), height, Qt.AlignCenter, number) block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() blockNumber += 1 def contextMenuEvent(self, event): menu = self.createStandardContextMenu() if self._addSaveAction: index = 0 if len(menu.actions()) > 6: index = 5 act_beforeACT = menu.actions()[index] menu.insertAction(act_beforeACT, self.saveACT) action = menu.addAction("Find" + "\t" + "Ctrl+F") action.triggered.connect(self.find_key) menu.popup(event.globalPos()) def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_F and (event.modifiers() & Qt.ControlModifier): self.find_key() if event.key() == Qt.Key_Escape: if self.searchTxtBx is not None: self.searchTxtBx.hide() self.searchTxtBx = None self.clear_format() super(Editor, self).keyPressEvent(event) def find_key(self): if self.searchTxtBx is None: self.searchTxtBx = QLineEdit(self) p = self.geometry().topRight() - self.searchTxtBx.geometry( ).topRight() - QPoint(50, 0) self.searchTxtBx.move(p) self.searchTxtBx.show() self.searchTxtBx.textChanged.connect(self.find_with_pattern) self.searchTxtBx.setFocus() def find_with_pattern(self, pattern): self.setUndoRedoEnabled(False) self.clear_format() if pattern == "": return cursor = self.textCursor() regex = QRegExp(pattern) pos = 0 index = regex.indexIn(self.toPlainText(), pos) while index != -1: cursor.setPosition(index) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor, 1) cursor.mergeCharFormat(self.findHighlightFormat) pos = index + regex.matchedLength() index = regex.indexIn(self.toPlainText(), pos) self.setUndoRedoEnabled(True) def clear_format(self): cursor = self.textCursor() cursor.select(QTextCursor.Document) cursor.setCharFormat(QTextCharFormat()) cursor.clearSelection() self.setTextCursor(cursor) def setSaveCB(self, cb): self._saveCB = cb def _save_file(self, text): if self._saveCB is not None: self._saveCB(text)
class QtOpticalflowInterfaceCloud(QWidget): PREVIEW = [ "no preview", "print fps", "image (default)", "image+fps", "print+image+fps", "print+image" ] MODE = [ "stream", "video", ] ESTIMATION = [ "no computing estimation", "simple estimate", "complete estimation (video mode only)", ] os.chdir("../modules") VISION_MODULES = glob.glob("*.py") os.chdir("../solutions") def __init__(self): QWidget.__init__(self) self.salutation_lbl = QLabel( 'Welcome to Opticalflow utilise Graphic interface', self) self.compute_location_text = QLabel("compute location:", self) self.compute_location = QComboBox(self) self.setMinimumSize(400, 400) self.setWindowTitle('GUI opticalflow utilities') self.ip_text = QLabel("ip:", self) self.ip = QLineEdit(self) self.port_text = QLabel("port:", self) self.port = QLineEdit(self) self.width_text = QLabel("width:", self) self.width = QLineEdit(self) self.height_text = QLabel("height:", self) self.height = QLineEdit(self) self.save_text = QLabel("save:", self) self.save = QCheckBox(self) self.save_extension = QLabel("", self) self.name_save = QLineEdit(self) self.fps_text = QLabel("fps:", self) self.fps = QLineEdit(self) self.preview_text = QLabel("preview:", self) self.preview = QComboBox(self) self.mode_text = QLabel("mode:", self) self.mode = QComboBox(self) self.video_file = QLineEdit(self) self.estimation_text = QLabel("estimation:", self) self.estimation = QComboBox(self) self.module_vision_text = QLabel("vision module:", self) self.module_vision = QComboBox(self) self.validation_button = QPushButton(self) self.set_buttons() def set_buttons(self): self.salutation_lbl.move(50, 5) # offset the first control 5px self.compute_location_text.move(5, 35) self.compute_location.move(120, 30) self.compute_location.addItems(["local", "cloud"]) self.compute_location.currentIndexChanged.connect(self.cloud_ip) self.ip_text.move(5, 70) self.ip.setText("localhost") self.ip.move(110, 70) self.ip.hide() self.ip_text.hide() self.port_text.move(5, 105) self.port.setText("10000") self.port.move(110, 105) self.port.hide() self.port_text.hide() self.width_text.move(5, 140) self.width.setText("320") self.width.move(110, 140) self.height_text.move(5, 175) self.height.setText("240") self.height.move(110, 175) self.save_text.move(5, 205) self.save.move(110, 205) self.save.clicked.connect(self.fps_show) self.name_save.move(130, 200) self.name_save.setText("file") self.name_save.hide() self.save_extension.move(260, 205) self.save_extension.hide() self.fps_text.move(5, 240) self.fps.move(110, 240) self.fps.setText("20") self.fps_text.hide() self.fps.hide() self.preview.addItems(self.PREVIEW) self.preview.move(110, 275) self.preview_text.move(5, 275) self.mode.addItems(self.MODE) self.mode.move(110, 310) self.mode_text.move(5, 310) self.mode.currentIndexChanged.connect(self.video_mode) self.video_file.move(190, 310) self.video_file.setText("videos_to_computed_videos/video_list_example") self.video_file.hide() self.estimation.addItems(self.ESTIMATION) self.estimation.move(110, 345) self.estimation_text.move(5, 345) self.module_vision.addItems(self.VISION_MODULES) self.module_vision.move(110, 375) self.module_vision_text.move(5, 375) self.validation_button.move(5, 400) self.validation_button.setText("clicked") self.validation_button.clicked.connect(self.reset_window) def get_value(self): return self def reset_window(self): copyfile("../modules/" + self.module_vision.currentText(), "./realtime/vision_module.py") if self.compute_location.currentText() == "cloud": self.streaming = Streaming(FieldValue(self)) elif self.mode.currentIndex() == 0: self.streaming = OpticalRealtime(FieldValue(self)) elif self.mode.currentIndex() == 1: self.streaming = VideoList(FieldValue(self)) self.streaming.run() def fps_show(self): if self.save.isChecked(): self.fps_text.show() self.fps.show() self.name_save.show() self.save_extension.show() else: self.fps_text.hide() self.fps.hide() self.name_save.hide() self.save_extension.hide() def cloud_ip(self): if self.compute_location.currentText() == "local": self.ip.hide() self.ip_text.hide() self.port.hide() self.port_text.hide() else: self.ip.show() self.ip_text.show() self.port.show() self.port_text.show() def video_mode(self): if self.mode.currentText() == "video": self.video_file.show() else: self.video_file.hide() def __delete__(self): pass
class mainWindow(QObject): signalRun = Signal(SpiderThread) signalRunApi = Signal(apiTester) def __init__(self): QObject.__init__(self) # must init parent QObject,if you want to use signal self.widget = QWidget() self.ipLabel = QLabel(self.widget) self.thread = QThread() self.worker = Worker() self.worker.moveToThread(self.thread) self.man = SpiderThread() self.api = apiTester() # 1 2:loop 3: time self.testStatus = [False,1,0,"ip","mac"] # advance config self.findCoreStop = True self.cleanCacheSet = False self.useApiTest = False self.showTestProgress = True self.saveTestLog = False self.saveLogPath = "" self.chromePath = "" self.showChrome = False self.coreDumpPath = "" # ui form self.passwordLabel = QLabel(self.widget) self.ipLineEdit = QLineEdit(self.widget) self.passwordLineEdit = QLineEdit(self.widget) self.startBtn = QPushButton(self.widget) self.stopBtn = QPushButton(self.widget) self.messageBox = QTextEdit(self.widget) self.messageBox.setReadOnly(True) self.userLabel = QLabel(self.widget) self.userLineEdit = QLineEdit(self.widget) self.intervalLabel = QLabel(self.widget) self.intervalSpinBox = QSpinBox(self.widget) self.loopLabel = QLabel(self.widget) self.loopSpinBox = QSpinBox(self.widget) self.intervalSpinBox.setRange(0,9999) self.loopSpinBox.setRange(1,9999) self.radioReboot = QRadioButton(self.widget) self.radioProvision = QRadioButton(self.widget) self.radioFactory = QRadioButton(self.widget) # self.apiCheckBox = QCheckBox(self.widget) self.menu = QMenu() self.gxpAction = QAction("Classic UI") self.grp2602Action = QAction("Ant Design UI") self.gxpAction.setCheckable(True) self.grp2602Action.setCheckable(True) self.menu.addAction(self.gxpAction) self.menu.addAction(self.grp2602Action) self.webLabel = QLabel(self.widget) self.webBtn = QPushButton(self.widget) self.webBtn.setMenu(self.menu) self.clearBtn = QPushButton(self.widget) self.messageList = deque() self.timer = QTimer() self.advanceBtn = QPushButton(self.widget) self.infoLabel = QLabel(self.widget) # provision widget self.provWidget = QWidget(self.widget) self.ver1Label = QLabel(self.provWidget) self.ver2Label = QLabel(self.provWidget) self.ver3Label = QLabel(self.provWidget) self.ver1LineEdit = QLineEdit(self.provWidget) self.ver2LineEdit = QLineEdit(self.provWidget) self.ver3LineEdit = QLineEdit(self.provWidget) self.dir1Label = QLabel(self.provWidget) self.dir2Label = QLabel(self.provWidget) self.dir3Label = QLabel(self.provWidget) self.dir1LineEdit = QLineEdit(self.provWidget) self.dir2LineEdit = QLineEdit(self.provWidget) self.dir3LineEdit = QLineEdit(self.provWidget) self.radioHttp = QRadioButton(self.provWidget) self.radioHttps = QRadioButton(self.provWidget) self.radioTftp = QRadioButton(self.provWidget) self.radioFtp = QRadioButton(self.provWidget) self.radioFtps = QRadioButton(self.provWidget) self.radioWindow = QRadioButton(self.provWidget) # advance widget self.advanceWidget = QWidget() self.checkCoreBox = QCheckBox(self.advanceWidget) self.cleanCache = QCheckBox(self.advanceWidget) self.checkSaveLogBox = QCheckBox(self.advanceWidget) self.selectDirBtn = QPushButton(self.advanceWidget) self.saveDirLabel = QLabel(self.advanceWidget) self.saveDirLabel.setStyleSheet("background:white") self.checkProgressBox = QCheckBox(self.advanceWidget) self.advanceOkBtn = QPushButton(self.advanceWidget) self.selectChromeBtn = QPushButton(self.advanceWidget) self.chromePathLabel = QLabel(self.advanceWidget) self.chromePathLabel.setStyleSheet("background:white") self.checkShowChromeBox = QCheckBox(self.advanceWidget) self.chromeLabel = QLabel(self.advanceWidget) self.pcapLabel = QLabel(self.advanceWidget) self.apiCheckBox = QCheckBox(self.advanceWidget) self.corePathLabel = QLabel(self.advanceWidget) self.corePathLabel.setStyleSheet("background:white") self.corePathBtn = QPushButton(self.advanceWidget) self.interfaceMenu = QComboBox(self.advanceWidget) self.interfaceMenu.addItem('Default') self.aiOptionBox= QCheckBox(self.advanceWidget) a = IFACES print(a) for i in a.keys(): print(a[i].description) self.interfaceMenu.addItem(a[i].description) # connect singal and slot self.startBtn.clicked.connect(self.clickedStarBtn) self.radioProvision.clicked.connect(self.clickedProvision) self.radioReboot.clicked.connect(self.clickedOthers) self.radioFactory.clicked.connect(self.clickedOthers) self.stopBtn.clicked.connect(self.clickedStopBtn) self.grp2602Action.triggered.connect(self.clickedGrp2602) self.gxpAction.triggered.connect(self.clickedGxpType) self.timer.timeout.connect(self.updateMessage) self.apiCheckBox.stateChanged.connect(self.apiTestBoxCheck) self.clearBtn.clicked.connect(self.clickedClearBtn) self.advanceBtn.clicked.connect(self.clickedAdvanceBtn) self.advanceOkBtn.clicked.connect(self.clickedAdvanceOkBtn) self.checkSaveLogBox.stateChanged.connect(self.saveLogBoxCheck) self.selectChromeBtn.clicked.connect(self.clickedSelectChromeBtn) self.selectDirBtn.clicked.connect(self.clickedSelectDirBtn) self.corePathBtn.clicked.connect(self.clickedCorePathBtn) self.worker.signalJobEnd.connect(self.slotTestStoped) self.worker.apiTestFinished.connect(self.slotTestStoped) self.signalRun.connect(self.worker.dowork) self.signalRunApi.connect(self.worker.doworkApi) # self.man.signalUpdateMessage.connect(self.pushMessage) def setupUI(self): # set text content /value self.widget.setWindowTitle("自动重启升降级测试工具") self.ipLabel.setText("初始IP:") self.passwordLabel.setText("密码:") self.startBtn.setText("开始测试") self.stopBtn.setText("停止测试") self.userLabel.setText("用户名:") self.intervalLabel.setText("间隔时间:") self.loopLabel.setText("测试次数:") self.intervalSpinBox.setValue(130) self.radioFactory.setText("恢复出厂") self.radioProvision.setText("升降级") self.radioReboot.setText("重启") self.ver1Label.setText("版本 1:") self.ver2Label.setText("版本 2:") self.ver3Label.setText("版本 3:") self.dir1Label.setText("路径 1:") self.dir2Label.setText("路径 2:") self.dir3Label.setText("路径 3:") self.radioHttp.setText("Http") self.radioHttps.setText("Https") self.radioTftp.setText("Tftp") self.radioFtp.setText("Ftp") self.radioFtps.setText("Ftps") self.apiCheckBox.setText("使用API测试,配置CoreDump下载路径") self.webLabel.setText("网页类型:") self.webBtn.setText("请选择UI类型") self.clearBtn.setText("清空输入") self.advanceWidget.setWindowTitle("高级设置") self.advanceBtn.setText("高级设置") self.checkCoreBox.setText("发现Core Dump时停止测试") self.cleanCache.setText("清除页面cache") self.checkSaveLogBox.setText("保存测试日志") self.selectDirBtn.setText("浏览") self.checkProgressBox.setText("显示底部状态条") self.advanceOkBtn.setText("OK") self.checkShowChromeBox.setText("测试时显示Chrome浏览器") self.selectChromeBtn.setText("浏览") self.chromeLabel.setText("Chrome浏览器路径") self.infoLabel.setText("未开始测试") self.pcapLabel.setText("Net Interface") self.corePathBtn.setText("浏览") self.radioWindow.setText("网页拖拽文件") # self.aiOptionBox.setText("AI") #init value self.saveDirLabel.hide() self.selectDirBtn.hide() self.gxpAction.setChecked(True) self.radioReboot.click() self.radioHttp.click() self.stopBtn.setEnabled(False) self.passwordLineEdit.setEchoMode(QLineEdit.PasswordEchoOnEdit) # set position------------------------------- xPos = 20 yPos = 30 colum2 = xPos +200 # line 1 self.ipLabel.move(xPos,yPos) self.intervalLabel.move(colum2,yPos) self.intervalSpinBox.move(colum2+60,yPos-2) self.ipLineEdit.move(xPos+50,yPos-2) # line 2 line2 = yPos +40 self.passwordLabel.move(xPos,line2) self.passwordLineEdit.move(xPos+50,line2-2) self.loopLabel.move(colum2,line2) self.loopSpinBox.move(colum2+60,line2-2) # line3 line3 = yPos +80 self.userLabel.move(xPos,line3) self.userLineEdit.move(xPos+50,line3-2) self.radioReboot.move(colum2,line3) self.radioFactory.move(colum2+60,line3) self.radioProvision.move(colum2,line3+30) self.webLabel.move(xPos,line3+40) self.webBtn.move(xPos+60,line3+35) # provWidget self.provWidget.resize(400,130) self.provWidget.move(xPos,line3+70) spaceY = 30 x = 0 y = 0 cl = 200 self.ver1Label.move(x,y) self.ver1LineEdit.move(x+50,y) self.ver2Label.move(x,y+spaceY) self.ver2LineEdit.move(x+50,y+spaceY) self.ver3Label.move(x,y+spaceY*2) self.ver3LineEdit.move(x+50,y+spaceY*2) self.dir1Label.move(cl,y) self.dir1LineEdit.move(cl+50,y) self.dir2Label.move(cl,y+spaceY) self.dir2LineEdit.move(cl+50,y+spaceY) self.dir3Label.move(cl,y+spaceY*2) self.dir3LineEdit.move(cl+50,y+spaceY*2) self.radioHttp.move(x,y+spaceY*3) self.radioHttps.move(x+50,y+spaceY*3) self.radioTftp.move(x+110,y+spaceY*3) self.radioFtp.move(x+160,y+spaceY*3) self.radioFtps.move(x+210,y+spaceY*3) self.radioWindow.move(x+265,y+spaceY*3) # advance widget self.advanceWidget.resize(300,400) x = 20 y = 20 space = 30 self.checkCoreBox.move(x,y) self.cleanCache.move(x,y+space) self.checkProgressBox.move(x,y+space*2) self.checkShowChromeBox.move(x,y+space*3) self.apiCheckBox.move(x,y+space*4) self.corePathBtn.move(x-2,y+space*5-8) self.corePathLabel.move(x+35,y+space*5-8) y += 40 self.chromeLabel.move(x,y+space*4+10) self.selectChromeBtn.move(x-2,y+space*5) self.chromePathLabel.move(x+35,y+space*5+2) self.checkSaveLogBox.move(x,y+space*6+10) self.selectDirBtn.move(x-2,y+space*7) self.saveDirLabel.move(x+35,y+space*7+2) self.advanceOkBtn.move(x+170,y+space*10+10) self.interfaceMenu.move(x-5,y+space*8+10) self.pcapLabel.move(x,y+space*8-2) # self.aiOptionBox.move(x, y+space*9+8) # set size self.messageBox.resize(373,155) # self.widget.resize(410,400) self.loopSpinBox.resize(60,25) self.intervalSpinBox.resize(60,25) self.webBtn.resize(100,25) self.saveDirLabel.resize(185,22) self.selectDirBtn.resize(32,24) self.selectChromeBtn.resize(32,24) self.chromePathLabel.resize(185,22) self.infoLabel.resize(400, 25) self.corePathBtn.resize(32,24) self.corePathLabel.resize(185,22) # self.provWidget.hide() self.changePosition(True) self.widget.show() self.loadCache() # ----------------end of setupUI --------------------- def changePosition(self,hide): xPos = 20 if hide: buttonLine = 200 self.widget.resize(420,415) else: buttonLine = 310 self.widget.resize(420,524) self.startBtn.move(xPos,buttonLine) self.stopBtn.move(xPos+90,buttonLine) self.clearBtn.move(xPos+180,buttonLine) self.advanceBtn.move(xPos+270,buttonLine) self.messageBox.move(xPos,buttonLine+30) boxH = self.messageBox.height() self.infoLabel.move(xPos,buttonLine+boxH+35) def setItemEnable(self,enable): self.provWidget.setEnabled(enable) self.ipLineEdit.setEnabled(enable) self.passwordLineEdit.setEnabled(enable) self.userLineEdit.setEnabled(enable) self.intervalSpinBox.setEnabled(enable) self.loopSpinBox.setEnabled(enable) self.radioFactory.setEnabled(enable) self.radioReboot.setEnabled(enable) self.radioProvision.setEnabled(enable) self.advanceBtn.setEnabled(enable) self.startBtn.setEnabled(enable) self.clearBtn.setEnabled(enable) if self.useApiTest: self.webBtn.setEnabled(False) else: self.webBtn.setEnabled(enable) self.stopBtn.setEnabled(not enable) def outputError(self,str): appstr = "<span style=\"color:red\">" appstr += str + "</span>" self.messageBox.append(appstr) def outputWarning(self,str): appstr = "<span style=\"color:orange\">" appstr += str + "</span>" self.messageBox.append(appstr) def loadCache(self): file = QFile("cache") if not file.open(QIODevice.ReadOnly | QIODevice.Text): return inStream = QTextStream(file) # ip self.ipLineEdit.setText(inStream.readLine()) # passwordLabel self.passwordLineEdit.setText(inStream.readLine()) # user self.userLineEdit.setText(inStream.readLine()) # ver1 self.ver1LineEdit.setText(inStream.readLine()) self.dir1LineEdit.setText(inStream.readLine()) # ver2 self.ver2LineEdit.setText(inStream.readLine()) self.dir2LineEdit.setText(inStream.readLine()) # ver3 self.ver3LineEdit.setText(inStream.readLine()) self.dir3LineEdit.setText(inStream.readLine()) self.intervalSpinBox.setValue(int(inStream.readLine())) self.loopSpinBox.setValue(int(inStream.readLine())) # web type button webType = inStream.readLine() if webType == "gxpAction": self.grp2602Action.setChecked(False) self.gxpAction.setChecked(True) self.webBtn.setText(self.gxpAction.text()) else: self.grp2602Action.setChecked(True) self.gxpAction.setChecked(False) self.webBtn.setText(self.grp2602Action.text()) testType = inStream.readLine() if testType == "reboot": self.radioReboot.setChecked(True) elif testType == "provision": self.radioProvision.setChecked(True) self.changePosition(False) self.provWidget.show() else: self.radioFactory.setChecked(True) serverType = inStream.readLine() if serverType == "Http": self.radioHttp.setChecked(True) elif serverType == "Https": self.radioHttps.setChecked(True) elif serverType == "Tftp": self.radioTftp.setChecked(True) elif serverType == "Ftp": self.radioFtp.setChecked(True) elif serverType == "Ftps": self.radioFtps.setChecked(True) else: self.radioWindow.setChecked(True) if inStream.readLine() == "True": self.findCoreStop = True else: self.findCoreStop = False if inStream.readLine() == "True": self.cleanCacheSet = True else: self.cleanCacheSet = False if inStream.readLine() == "True": self.useApiTest = True self.webBtn.setEnabled(False) else: self.useApiTest = False self.corePathBtn.hide() self.corePathLabel.hide() if inStream.readLine() == "True": self.showTestProgress = True else: self.showTestProgress = False self.infoLabel.hide() if inStream.readLine() == "True": self.showChrome = True else: self.showChrome = False self.chromePath = inStream.readLine() if inStream.readLine() == "True": self.saveTestLog = True else: self.saveTestLog = False self.saveLogPath = inStream.readLine() self.coreDumpPath = inStream.readLine() file.close() def saveCache(self): file = QFile("cache") if not file.open(QIODevice.WriteOnly): return content = self.ipLineEdit.text() + "\n" content += self.passwordLineEdit.text() + "\n" content += self.userLineEdit.text() + "\n" content += self.ver1LineEdit.text() + "\n" content += self.dir1LineEdit.text() + "\n" content += self.ver2LineEdit.text() + "\n" content += self.dir2LineEdit.text() + "\n" content += self.ver3LineEdit.text() + "\n" content += self.dir3LineEdit.text() + "\n" content += str(self.intervalSpinBox.value()) + "\n" content += str(self.loopSpinBox.value()) + "\n" if self.gxpAction.isChecked(): content += "gxpAction\n" else: content += "grp2602Action\n" if self.radioReboot.isChecked(): content += "reboot\n" elif self.radioProvision.isChecked(): content += "provision\n" else: content += "factory\n" if self.radioHttp.isChecked(): content += "Http\n" elif self.radioHttps.isChecked(): content += "Https\n" elif self.radioTftp.isChecked(): content += "Tftp\n" elif self.radioFtp.isChecked(): content += "Ftp\n" elif self.radioFtps.isChecked(): content += "Ftps\n" else : content += "Window\n" content += str(self.findCoreStop) + "\n" content += str(self.cleanCacheSet) + "\n" content += str(self.useApiTest) + "\n" content += str(self.showTestProgress) + "\n" content += str(self.showChrome) + "\n" content += self.chromePath +"\n" content += str(self.saveTestLog) +"\n" content += self.saveLogPath +"\n" content += self.coreDumpPath +"\n" byteArr = bytes(content,"utf-8") file.write(QByteArray(byteArr)) file.close() def checkBeforeRun(self): containError = False #---------check Ip address-------------- if self.ipLineEdit.text() == "": containError = True self.outputError("IP地址不能为空!") else: pattern = re.compile("^((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){3}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9]))$") if not pattern.search(self.ipLineEdit.text()): containError = True self.outputError("IP地址格式错误,检查是否含有多余空格!(仅支持IPV4)") #------------------------ if self.passwordLineEdit.text() == "": containError = True self.outputError("密码不能为空!") if self.userLineEdit.text() == "": containError = True self.outputError("用户名不能为空!") if self.intervalSpinBox.value() <= 40: self.outputWarning("间隔时间过短,可能对测试造成影响") if not self.radioProvision.isChecked() and not self.radioReboot.isChecked() and \ not self.radioFactory.isChecked(): containError = True self.outputError("必须选择测试方式(重启,升降级,恢复出厂)") # check provision ---------- if self.radioProvision.isChecked(): if self.ver1LineEdit.text() == "" or self.ver2LineEdit.text() == "" or \ self.dir1LineEdit.text() == "" or self.dir2LineEdit.text() == "": containError = True self.outputError("升降级测试至少填上前两个版本及其路径") bin_name = "" if os.path.exists(os.path.abspath("config.ini") ): f = open(os.path.abspath("config.ini") , "r") line = f.readline() while line: option = line.split("=") if option[0] == "firmbinname": if option[1].strip('"') != "": filenamebin = option[1].strip() bin_name = filenamebin.strip('"') pass line = f.readline() f.close() filename = os.path.join(self.dir1LineEdit.text(), bin_name) if not os.path.exists(filename) and self.radioWindow.isChecked(): containError = True self.outputError("firmware1 文件不存在!" + filename) filename = os.path.join(self.dir2LineEdit.text(), bin_name) if not os.path.exists(filename) and self.radioWindow.isChecked(): containError = True self.outputError("firmware2 文件不存在!" + filename) filename = os.path.join(self.dir3LineEdit.text(), bin_name) if self.ver3LineEdit.text() != "" and self.dir3LineEdit.text() == "": containError = True self.outputError("填写了版本3,但对应路径为空!") if self.dir3LineEdit.text() != "" and self.ver3LineEdit.text() == "": containError = True self.outputError("填写了路径3,但对应版本为空!") elif self.dir3LineEdit.text() != "" and self.radioWindow.isChecked() and not os.path.exists(filename): containError = True self.outputError("firmware3 文件不存在!" + filename) if not self.radioFtp.isChecked() and not self.radioFtps.isChecked() and \ not self.radioHttp.isChecked() and not self.radioHttps.isChecked() and \ not self.radioTftp.isChecked() and not self.radioWindow.isChecked(): containError = True self.outputError("升降级测试必须选择服务器类型(Tftp,Ftp,Ftps,Http,Https)") return containError def startTest(self): ip = self.ipLineEdit.text() passwd = self.passwordLineEdit.text() username = self.userLineEdit.text() ptime = self.intervalSpinBox.value() loop = self.loopSpinBox.value() modelType = self.webBtn.text() if self.gxpAction.isChecked(): device_type = "GXP21XX" elif self.grp2602Action.isChecked(): device_type = "GRP260X" if self.radioReboot.isChecked(): task_type = "reboot" elif self.radioProvision.isChecked(): task_type = "provision" text_ver1 = self.ver1LineEdit.text() text_ver2 = self.ver2LineEdit.text() text_ver3 = self.ver3LineEdit.text() text_dir1 = self.dir1LineEdit.text() text_dir2 = self.dir2LineEdit.text() text_dir3 = self.dir3LineEdit.text() prov_dict = {"ver1": text_ver1.strip(), "dir1": text_dir1.strip(), "ver2": text_ver2.strip(), "dir2": text_dir2.strip(), "ver3": text_ver3.strip(), "dir3": text_dir3.strip()} if self.radioHttp.isChecked(): self.man.update_prov_setting("HTTP", prov_dict) elif self.radioHttps.isChecked(): self.man.update_prov_setting("HTTPS", prov_dict) elif self.radioTftp.isChecked(): self.man.update_prov_setting("TFTP", prov_dict) elif self.radioFtp.isChecked(): self.man.update_prov_setting("FTP", prov_dict) elif self.radioFtps.isChecked(): self.man.update_prov_setting("FTPS", prov_dict) elif self.radioWindow.isChecked(): self.man.update_prov_setting("browser", prov_dict) else: task_type = "reset" coredump_stop = True headless_flag = False clean_cache = False if self.checkCoreBox.isChecked() == False: self.messageBox.append("Find core dump will not stop") coredump_stop = False if self.cleanCache.isChecked() == True: clean_cache = True if self.checkShowChromeBox.isChecked() == True or self.radioWindow.isChecked() == True: headless_flag = False else: headless_flag = True # ai_mode = False # if self.aiOptionBox.isChecked() == True: # ai_mode = True browser_path = "" if self.chromePathLabel.text() != "": browser_path = self.chromePathLabel.text() self.testStatus = [True,1,0,"ip",""] print(self.interfaceMenu.currentText()) self.man.setStatus(self.testStatus) self.man.setMessageList(self.messageList) self.man.update_setting(ip.strip(), username.strip(), passwd.strip(), device_type, \ task_type, loop, ptime, coredump_stop, headless_flag, browser_path, \ clean_cache, self.interfaceMenu.currentText(), False) def startApiTest(self): ip = self.ipLineEdit.text() passwd = self.passwordLineEdit.text() username = self.userLineEdit.text() ptime = self.intervalSpinBox.value() loop = self.loopSpinBox.value() testType = "Reboot" if self.radioProvision.isChecked(): testType = "Provision" self.api.setValue(ip,username,passwd,ptime,loop,testType) v1 = self.ver1LineEdit.text() v2 = self.ver2LineEdit.text() v3 = self.ver3LineEdit.text() d1 = self.dir1LineEdit.text() d2 = self.dir2LineEdit.text() d3 = self.dir3LineEdit.text() self.api.setVersion(v1,v2,v3,d1,d2,d3) self.api.setTestStatus(self.testStatus,self.messageList,self.coreDumpPath) if self.radioHttp.isChecked(): self.api.setServerType("http") elif self.radioHttps.isChecked(): self.api.setServerType("https") elif self.radioTftp.isChecked(): self.api.setServerType("tftp") elif self.radioFtp.isChecked(): self.api.setServerType("ftp") else: #self.radioFtps.isChecked() self.api.setServerType("ftps") self.api.setFoundCoreStop(self.findCoreStop) # slot --------------------------------- def apiTestBoxCheck(self,state): if state == 2: self.corePathBtn.show() self.corePathLabel.show() else: self.corePathBtn.hide() self.corePathLabel.hide() def clickedCorePathBtn(self): dir = QFileDialog.getExistingDirectory(self.advanceWidget,"选择Core Dump存放路径","/home") if dir != "": self.corePathLabel.setText(dir) self.coreDumpPath = dir def clickedSelectDirBtn(self): dir = QFileDialog.getExistingDirectory(self.advanceWidget,"选择日志存放路径","/home") if dir != "": self.saveDirLabel.setText(dir) self.saveLogPath = dir def clickedSelectChromeBtn(self): fileName = QFileDialog.getOpenFileName(self.advanceWidget,"选择谷歌浏览器","/home","Chrome (*.exe)") if fileName != "": self.chromePathLabel.setText(fileName[0]) self.chromePath = fileName[0] def saveLogBoxCheck(self,state): if state == 2: # checked self.selectDirBtn.show() self.saveDirLabel.show() else: self.selectDirBtn.hide() self.saveDirLabel.hide() def clickedAdvanceOkBtn(self): self.findCoreStop = self.checkCoreBox.isChecked() self.cleanCacheSet = self.cleanCache.isChecked() self.useApiTest = self.apiCheckBox.isChecked() self.showTestProgress = self.checkProgressBox.isChecked() self.saveTestLog = self.checkSaveLogBox.isChecked() self.saveLogPath = self.saveDirLabel.text() self.showChrome = self.checkShowChromeBox.isChecked() self.chromePath = self.chromePathLabel.text() self.coreDumpPath = self.corePathLabel.text() if self.useApiTest: self.webBtn.setEnabled(False) self.corePathBtn.show() self.corePathLabel.show() else: self.webBtn.setEnabled(True) self.corePathBtn.hide() self.corePathLabel.hide() if self.showTestProgress: self.infoLabel.show() else: self.infoLabel.hide() self.saveCache() self.advanceWidget.hide() def clickedAdvanceBtn(self): self.advanceWidget.hide() self.checkCoreBox.setChecked(self.findCoreStop) self.cleanCache.setChecked(self.cleanCacheSet) self.apiCheckBox.setChecked(self.useApiTest) self.checkProgressBox.setChecked(self.showTestProgress) self.checkSaveLogBox.setChecked(self.saveTestLog) self.saveDirLabel.setText(self.saveLogPath) self.checkShowChromeBox.setChecked(self.showChrome) self.chromePathLabel.setText(self.chromePath) self.corePathLabel.setText(self.coreDumpPath) self.advanceWidget.show() def slotTestStoped(self): self.testStatus[0] = False self.setItemEnable(True) self.timer.stop() self.updateMessage() self.thread.quit() # save Test log if self.saveTestLog: fileName = time.strftime("%Y_%m_%d.%H_%M_%S.",time.localtime()) if self.radioReboot.isChecked(): fileName += "reboot" elif self.radioProvision: fileName += "provision" else: fileName += "factoryReset" fileName += ".htm" if self.saveLogPath == "": self.outputWarning("日志地址没有设置,无法保存") else: fileName = self.saveLogPath + "\\" + fileName print(fileName) file = QFile(fileName) if not file.open(QIODevice.WriteOnly): self.outputError("打开文件错误,保存日志失败") return byteArr = bytes(self.messageBox.toHtml(),"utf-8") file.write(QByteArray(byteArr)) file.close() def clickedClearBtn(self): self.ipLineEdit.setText("") self.passwordLineEdit.setText("") self.userLineEdit.setText("") self.ver1LineEdit.setText("") self.dir1LineEdit.setText("") self.ver2LineEdit.setText("") self.dir2LineEdit.setText("") self.ver3LineEdit.setText("") self.dir3LineEdit.setText("") def clickedStarBtn(self): if self.checkBeforeRun(): return self.messageBox.clear() self.saveCache() self.messageBox.append("Init Setting...") self.setItemEnable(False) self.timer.start(500) self.thread.start() # deside use what to test if self.useApiTest: if self.radioFactory.isChecked(): self.outputWarning("Api not support Factory Reset, will test as Gxp type web driver") self.clickedGxpType() self.startTest() self.signalRun.emit(self.man) else: self.startApiTest() self.signalRunApi.emit(self.api) else: self.startTest() self.signalRun.emit(self.man) def clickedStopBtn(self): self.stopBtn.setEnabled(False) self.testStatus[0] = False self.man.quit() self.outputWarning("正在停止...") def clickedProvision(self): self.provWidget.show() self.changePosition(False) def clickedOthers(self): self.provWidget.hide() self.changePosition(True) def clickedGxpType(self): self.gxpAction.setChecked(True) self.grp2602Action.setChecked(False) self.webBtn.setText(self.gxpAction.text()) def clickedGrp2602(self): self.gxpAction.setChecked(False) self.grp2602Action.setChecked(True) self.webBtn.setText(self.grp2602Action.text()) def updateMessage(self): while len(self.messageList) >0: info = self.messageList.popleft() self.messageBox.append(info) if self.testStatus[0] == False: self.infoLabel.setText("未开始测试") else: info = "第" + str(self.testStatus[1]) + "次测试 " if self.testStatus[2] > 0: info += "等待:{} 秒".format( self.testStatus[2] ) else: info += "运行中" info += " " + self.testStatus[3] info += " " + self.testStatus[4] self.infoLabel.setText(info)
def create_interface(self): self.attribute_button.move(50, 0) # Create a Menu Option for Each Attribute self.add_attribute_to_menu(self.humidity_attribute, "humidity") self.add_attribute_to_menu(self.pressure_attribute, "pressure") self.add_attribute_to_menu(self.temperature_attribute, "temperature") self.add_attribute_to_menu(self.wind_speed_attribute, "wind_speed") self.attribute_button.setMenu(self.menu) self.attribute_button.resize(self.menu.width() + 50, self.attribute_button.height()) # Get self.slider from QML File self.slider = self.rootObject().findChild(QObject, "slider") # Set Date Pickers self.date_picker_start, self.date_picker_end = self.set_date_pickers( self.slider) self.date_picker_start.dateChanged.connect(lambda: self.change_date( self.slider, self.self.date_picker_start, self.date_picker_end)) self.date_picker_end.dateChanged.connect(lambda: self.change_date( self.slider, self.self.date_picker_start, self.date_picker_end)) # Label Holding the Current Date Selected by User self.date_label.move( self.slider.property("x") + (self.slider.width() / 2) - 100, self.slider.property("y") + 30) self.date_label.adjustSize() # Set Buttons Position self.previous_button.setStyleSheet("color: black") self.previous_button.move(self.slider.property("x"), self.slider.property("y") + 50) self.previous_button.adjustSize() self.next_button.setStyleSheet("color: black") self.next_button.move( self.slider.property("x") + self.slider.width() - 70, self.slider.property("y") + 50) self.next_button.adjustSize() jump_label = QLabel("self.slider jump (in days): ", self) jump_label.setStyleSheet("color: black") jump_label.move(self.date_label.x(), self.date_label.y() + 40) jump_label.adjustSize() self.jump_value = QLineEdit(self) self.jump_value.move(jump_label.x() + jump_label.width(), jump_label.y() - 5) self.jump_value.resize(35, self.jump_value.height()) self.jump_value.editingFinished.connect( lambda: self.slider.setProperty("stepSize", self.jump_value.text() )) agg_label = QLabel(self) agg_label.setStyleSheet("color: black") agg_label.move(self.date_label.x(), self.jump_value.y() + 40) agg_label.setText("mean (in days): ") agg_label.adjustSize() agg_value = QLineEdit(self) agg_value.move(self.jump_value.x(), agg_label.y() - 5) agg_value.resize(35, agg_value.height()) agg_value.editingFinished.connect( lambda: self.set_agg(agg_value.text())) # Initialize Visualization self.humidity_attribute.trigger() self.change_date(self.slider, self.date_picker_start, self.date_picker_end)
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(400, 250)) self.setWindowTitle("Automate outlook mailing") self.LabelExcelFile = QLabel(self) self.LabelExcelFile.setText('Excel :') self.LabelExcelFile.move(20, 20) self.line = QLineEdit(self) self.line.move(80, 20) self.line.resize(200, 25) self.searchFileButton = QPushButton("Load", self) self.searchFileButton.clicked.connect(self.searchAndLoadFile) self.searchFileButton.move(300, 20) self.searchFileButton.resize(75, 25) # self.layout.addWidget(self.searchFileButton,2, 1, 1, 1) self.nameLabel = QLabel(self) self.nameLabel.setText('Subject :') self.nameLabel.move(20, 60) self.LineSubject = QLineEdit(self) self.LineSubject.move(80, 60) self.LineSubject.resize(200, 25) self.LabelArea = QLabel(self) self.LabelArea.setText('Body :') self.LabelArea.move(20, 100) self.text_area = QTextEdit(self) self.text_area.resize(200, 80) self.text_area.move(80, 100) self.pybutton = QPushButton('Save', self) self.pybutton.clicked.connect(self.clickMethod) self.pybutton.resize(200,32) self.pybutton.move(80, 200) self.createExample = QPushButton('Example File', self) self.createExample.clicked.connect(myExcel.CreateExample) self.createExample.resize(75,32) self.createExample.move(300, 100) self.autorun = QPushButton('Auto Run Off', self) self.autorun.clicked.connect(self.set_auto_run) self.autorun.resize(75,32) self.autorun.move(300, 150) self.autorun.setCheckable(True) self.start = QPushButton('Run', self) self.start.clicked.connect(self.run_business) self.start.resize(75,32) self.start.move(300, 200) def run_business(self): print("The business program starts") myBusiness.the_aim_of_the_program() pass def set_auto_run(self): """ print("Select Example") #self.button2.click() self.button2.setChecked(True) if self.button4.isChecked(): print("button4 is checked") self.button4.setChecked(False) pass else: print("button4 isnt checked") pass """ if self.autorun.isChecked(): print("autorun button is checked") self.autorun.setChecked(True) self.autorun.setText('Auto Run On') self.save_something('Automate outlook mailing','auto_run', 'True') pass else: self.autorun.setChecked(False) print("autorun button isnt checked") self.autorun.setText('Auto Run Off') self.save_something('Automate outlook mailing','auto_run', 'False') pass print("The business program starts") # myBusiness.the_aim_of_the_program() pass def save_something(self,section,somekey,something): if myConfig.configuration_file_has_been_persisted(): print("The program starts") #print(myConfig.get_saved_data("EXCEL","subject")) else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass myConfig.configuration_file_set_something_to_save(section,somekey,something) pass def clickMethod(self): print('Your name: ' + self.line.text()) if myConfig.configuration_file_has_been_persisted(): print("The program starts") print(myConfig.get_saved_data("EXCEL","subject")) else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass if self.line.text() != "": myConfig.configuration_file_set_something_to_save("EXCEL","file",self.line.text()) pass if self.LineSubject.text() != "": myConfig.configuration_file_set_something_to_save("EMAIL","subject",self.LineSubject.text()) pass if self.text_area.toPlainText() != "": myConfig.configuration_file_set_something_to_save("EMAIL","body",self.text_area.toPlainText()) pass # print(self.text_area.toPlainText()) #print(myConfig.get_mail_data()['subject']) # myConfig.configuration_file_create_persist() pass """ excel_file = "~tempfile.1.xlsx" #myExcel.getDataFromExcel(excel_file) if myConfig.configuration_file_has_been_persisted(): print("The program starts") print(myConfig.check_data("EMAIL",'subject')) # for key in (myConfig.get_mail_data()): print(key) if myConfig.check_data("EMAIL",'subject'): print(myConfig.get_mail_data()['subject']) myConfig.get_mail_data()['subject'] pass else: myConfig.configuration_file_create_persist() pass #myExcel.getDataFromExcel(excel_file,) pass else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass # myConfig.configuration_file_create_persist() pass """ def setFromConfigurationFile(self): #excel_file = "~tempfile.1.xlsx" #myExcel.getDataFromExcel(excel_file) if myConfig.configuration_file_has_been_persisted(): print("The program starts") #print(myConfig.check_data("EMAIL",'subject')) # for key in (myConfig.get_mail_data()): print(key) if myConfig.check_data("EMAIL",'subject'): #print(myConfig.get_mail_data()['subject']) #myConfig.get_mail_data()['subject'] print() print() print() self.line.setText(myConfig.get_saved_data("EXCEL",'file')) # self.line.setText("Hola perro") self.LineSubject.setText(myConfig.get_saved_data("EMAIL",'subject')) self.text_area.setText(myConfig.get_saved_data("EMAIL",'body')) if myConfig.check_data('Automate outlook mailing','auto_run'): if myConfig.get_saved_data('Automate outlook mailing','auto_run') == "True": self.autorun.setChecked(True) self.autorun.setText('Auto Run On') pass else: self.autorun.setChecked(False) self.autorun.setText('Auto Run Off') pass pass else: print('auto_run not exist') myConfig.configuration_file_create_persist() pass pass else: myConfig.configuration_file_create_persist() pass #myExcel.getDataFromExcel(excel_file,) pass else: print("The program needs to be configured") myConfig.configuration_file_create_persist() pass pass def searchAndLoadFile(self): #path_to_file, _ = QFileDialog.getOpenFileName(self, self.tr("Load Image"), self.tr("~/Desktop/"), self.tr("Images (*.jpg)")) path_to_file, _ = QFileDialog.getOpenFileName(self, self.tr("Load Excel"), self.tr("~/Desktop/"), self.tr("/ (*.xlsx)")) #self.test(path_to_file) print(path_to_file) #self.testFuncion(path_to_file) # self.filenameLoaded = path_to_file self.line.setText(path_to_file)
import sys from PySide2.QtWidgets import QApplication, QMainWindow, QLineEdit, QLabel, QPushButton aplicacao = QApplication(sys.argv) janela = QMainWindow() janela.setGeometry( 100, 50, 300, 200 ) janela.setWindowTitle("Primeira Janela") texto_entrada = QLineEdit(janela) texto_entrada.move(50, 10) texto_entrada.resize(200, 30) label = QLabel("Texto Obtido:", janela) label.move(50, 90) label.resize(200,30) resultado = QLabel("", janela) resultado.move(50, 120) resultado.resize(200,30) def onButtonClick(): # atribui o valor da caixa de texto para o label resultado resultado.setText(texto_entrada.text()) # texto_entrada.text() obtém o valor que está na caixa de texto button = QPushButton("Obter texto", janela) button.move(50, 50) button.resize(205,30) # determina a função que sera executada ao clicar no botão button.clicked.connect(onButtonClick)