Ejemplo n.º 1
0
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()  # очищаем текст
Ejemplo n.º 2
0
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()
Ejemplo n.º 3
0
    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
Ejemplo n.º 4
0
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()
Ejemplo n.º 5
0
from PySide2.QtCore import QUrl
from PySide2.QtGui import QStandardItemModel, QStandardItem
from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineProfile
from PySide2.QtWidgets import QGridLayout, QLineEdit, QWidget, QHeaderView, QListView
from PySide2.QtWebEngineCore import QWebEngineUrlRequestInterceptor
from PySide2 import QtNetwork

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_frame = QWidget()
    listView = QListView()
    browser = QWebEngineView()
    grid = QGridLayout()
    ledit = QLineEdit()

    ledit.resize(50, 20)
    listView.setFixedWidth(250)
    listView.setWindowTitle('Example List')
    model = QStandardItemModel(listView)

    foods = [
        'Cookie dough',  # Must be store-bought
        'Hummus',  # Must be homemade
        'Spaghetti',  # Must be saucy
        'Dal makhani',  # Must be spicy
        'Chocolate whipped cream'  # Must be plentiful
    ]

    for food in foods:
        # Create an item with a caption
        item = QStandardItem(food)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
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()
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
    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)
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
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()
    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]
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
    def displayWidgets(self):
        """
        Configura os widgets da app
        """

        titl_lbl = QLabel("Formulario de Agendamento de Consulta")
        titl_lbl.setFont(QFont('Arial', 18))
        titl_lbl.setAlignment(Qt.AlignCenter)

        nome_edit = QLineEdit()
        nome_edit.resize(100, 100)
        ende_edit = QLineEdit()
        cel_edit = QLineEdit()
        cel_edit.setInputMask("00-00000-0000;")

        edad_lbl = QLabel("Edade")
        edad_sbx = QSpinBox()
        edad_sbx.setRange(1, 110)

        alt_lbl = QLabel("Altura")
        alt_edit = QLineEdit()
        alt_edit.setPlaceholderText("cm")
        peso_lbl = QLabel("Peso")
        peso_edit = QLineEdit()
        peso_edit.setPlaceholderText("kg")

        gen_cbx = QComboBox()
        gen_cbx.addItems(["Masculino", "Femenino"])

        cirur_edit = QTextEdit()
        cirur_edit.setPlaceholderText("separadas por ','")
        sang_cbx = QComboBox()
        sang_cbx.addItems(["A", "B", "AB", "O"])

        hora_sbx = QSpinBox()
        hora_sbx.setRange(8, 19)
        min_cbx = QComboBox()
        min_cbx.addItems([":00", ":15", ":30", ":45"])

        marc_btn = QPushButton("Marcar Consuta")
        marc_btn.clicked.connect(self.close)

        hbox = QHBoxLayout()
        hbox.addSpacing(10)
        hbox.addWidget(edad_lbl)
        hbox.addWidget(edad_sbx)
        hbox.addWidget(alt_lbl)
        hbox.addWidget(alt_edit)
        hbox.addWidget(peso_lbl)
        hbox.addWidget(peso_edit)

        hora_hbox = QHBoxLayout()
        hora_hbox.addSpacing(10)
        hora_hbox.addWidget(hora_sbx)
        hora_hbox.addWidget(min_cbx)

        app_form = QFormLayout()

        app_form.addRow(titl_lbl)
        app_form.addRow("Nome Completo", nome_edit)
        app_form.addRow("Endereço", ende_edit)
        app_form.addRow("Telefone Celular", cel_edit)
        app_form.addRow(hbox)
        app_form.addRow("Gênero", gen_cbx)
        app_form.addRow("Cirurgias Anteriores ", cirur_edit)
        app_form.addRow("Tipo Sanguineo", sang_cbx)
        app_form.addRow("Horário Desejado", hora_hbox)
        app_form.addRow(marc_btn)

        self.setLayout(app_form)
Ejemplo n.º 16
0
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)