Ejemplo n.º 1
0
 def message_box(self, message: str, buttons: int = 1) -> int:
     '''
     Message box with "Yes/No" or "OK" buttons. Defaults to "OK".\n
         Parameters:\n
             message (str): Message shown inside the message box.
             buttons (int): Amount of buttons, 1 - "OK" button, 2 - "Yes/No" buttons.
         Returns:\n
             choice (int): ID of the clicked button.
     '''
     pixmap = QPixmap(resource_path('icon.ico')).scaledToWidth(
         35, Qt.SmoothTransformation)
     msg_box = QMessageBox()
     msg_box.setFont(ui.font)
     msg_box.setText(message)
     if buttons == 2:
         msg_yes = msg_box.addButton(QMessageBox.Yes)
         msg_no = msg_box.addButton(QMessageBox.No)
         msg_yes.setText(self.dialog_yes)
         msg_no.setText(self.dialog_no)
         msg_yes.setProperty('class', 'button_yes')
         msg_no.setProperty('class', 'button_no')
     msg_box.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint)
     msg_box.setIconPixmap(pixmap)
     with open(resource_path('style.css'), 'r') as file:
         msg_box.setStyleSheet(file.read())
     msg_box.move(ui.frameGeometry().center() -
                  QRect(QPoint(), msg_box.sizeHint()).center())
     choice = msg_box.exec_()
     return choice
    def prompt_calc_dvh(self):
        """
        Windows displays buttons in a different order from Linux. A check for
        platform is performed to ensure consistency of button positioning across
        platforms.
        """
        message = "DVHs not present in RTDOSE or do not correspond to ROIs. "
        message += "Would you like to calculate DVHs? (This may take up to "
        message += "several minutes on some systems.)"
        if platform.system() == "Linux":
            choice = QMessageBox.question(self, "Calculate DVHs?", message,
                                          QMessageBox.Yes | QMessageBox.No)

            if choice == QMessageBox.Yes:
                self.signal_advise_calc_dvh.emit(True)
            else:
                self.signal_advise_calc_dvh.emit(False)
        else:
            stylesheet_path = ""

            # Select appropriate style sheet
            if platform.system() == 'Darwin':
                stylesheet_path = Path.cwd().joinpath('res', 'stylesheet.qss')
            else:
                stylesheet_path = Path.cwd().joinpath(
                    'res', 'stylesheet-win-linux.qss')

            # Create a message box and add attributes
            mb = QMessageBox()
            mb.setIcon(QMessageBox.Question)
            mb.setWindowTitle("Calculate DVHs?")
            mb.setText(message)
            button_no = QtWidgets.QPushButton("No")
            button_yes = QtWidgets.QPushButton("Yes")

            # We want the buttons 'No' & 'Yes' to be displayed in that
            # exact order. QMessageBox displays buttons in respect to
            # their assigned roles. (0 first, then 1 and so on)
            # 'AcceptRole' is 0 and 'RejectRole' is 1 thus by assigning
            # 'No' to 'AcceptRole' and 'Yes' to 'RejectRole' the buttons
            # are positioned as desired.
            mb.addButton(button_no, QtWidgets.QMessageBox.AcceptRole)
            mb.addButton(button_yes, QtWidgets.QMessageBox.RejectRole)

            # Apply stylesheet to the message box and add icon to the window
            mb.setStyleSheet(open(stylesheet_path).read())
            mb.setWindowIcon(
                QtGui.QIcon(
                    resource_path(Path.cwd().joinpath('res', 'images',
                                                      'btn-icons',
                                                      'onkodicom_icon.png'))))
            mb.exec_()

            if mb.clickedButton() == button_yes:
                self.signal_advise_calc_dvh.emit(True)
            else:
                self.signal_advise_calc_dvh.emit(False)
Ejemplo n.º 3
0
 def inicializar_db():
     try:
         init_db()
     except NameError:
         popup = QMessageBox(QMessageBox.Critical, "Erro", "Erro")
         popup.setInformativeText(
             "Arquivo de configuração não foi encontrado")
         popup.addButton(QMessageBox.Ok)
         popup.exec()
         exit(1)
Ejemplo n.º 4
0
 def showContinueSearchDialog(self, searchlimit: int) -> bool:
     messagebox = QMessageBox(self)
     messagebox.setWindowTitle('Unusual search depth')
     messagebox.setText(f'''
         <p>No mod detected after searching through {searchlimit} directories.</p>
         <p>Are you sure this is a valid mod?</p>
         ''')
     messagebox.setTextFormat(Qt.RichText)
     messagebox.setStandardButtons(QMessageBox.Cancel)
     yes: QPushButton = QPushButton(' Yes, continue searching ', messagebox)
     yes.setAutoDefault(True)
     yes.setDefault(True)
     messagebox.addButton(yes, QMessageBox.YesRole)
     messagebox.exec_()
     return messagebox.clickedButton() == yes
Ejemplo n.º 5
0
 def show_choice(text="",
                 confirm_text="确认",
                 deny_text="取消",
                 confirm_cb=None,
                 deny_cb=None):
     box = QMessageBox()
     box.setWindowTitle(Message.LEVEL_NAMES[Level.Info.value])
     box.setWindowIcon(QIcon(GResource.icon_window))
     box.setText(text)
     box.addButton(confirm_text, QMessageBox.AcceptRole)
     box.addButton(deny_text, QMessageBox.RejectRole)
     reply = box.exec_()
     if reply == QMessageBox.AcceptRole:
         Globals.call(confirm_cb)
     elif reply == QMessageBox.RejectRole:
         Globals.call(deny_cb)
Ejemplo n.º 6
0
def choiceDialog(parent: Optional[QWidget],
                 message: str,
                 labels: Iterable[str],
                 choices: Iterable[T],
                 show_cancel_button=True) -> T:
    buttons_to_choices = {}
    message_box = QMessageBox(QMessageBox.Question, QApplication.applicationName(), message, QMessageBox.NoButton, parent)

    for label, choice in zip(labels, choices):
        button = message_box.addButton(label, QMessageBox.ActionRole)
        buttons_to_choices[button] = choice

    if show_cancel_button:
        button = message_box.addButton(QMessageBox.Cancel)
        buttons_to_choices[button] = None

    message_box.exec()
    return buttons_to_choices[message_box.clickedButton()]
Ejemplo n.º 7
0
 def salvar_cliente(self):
     nome = self.entry_nome.text()
     cpf = self.entry_cpf.text()
     numero = self.entry_numero.text()
     endereco = self.entry_endereco.toPlainText()
     data = {
         'nome': nome,
         'cpf': cpf,
         'numero': numero,
         'endereco': endereco
     }
     try:
         self.db.novo_cliente(data)
         self.status_signal.emit("Salvo")
         self.limpar()
     except ValueError as e:
         popup = QMessageBox(QMessageBox.Critical, "Erro", "Campo Inválido")
         popup.setInformativeText(str(e))
         popup.addButton(QMessageBox.Ok)
         popup.exec()
Ejemplo n.º 8
0
def data_filter(master, df, headerdict):
    '''Recebe um dataframe de strings e filtra as colunas.'''

    # Filtra no primeiro dataframe as colunas correspondentes a: datas, precipitacao observada/registrada.
    # se estas colunas nao existirem, provoca um erro e avisa ao usuario.

    # filtra coluna correspondente a precipitação observada.
    try:
        observados = df[df.columns[headerdict["Prec. Observada"]]].str.replace(
            ',', '.')

    except:
        x = QMessageBox(QMessageBox.Warning,
                        "Erro de Seleçao",
                        'A coluna "Prec. Observada" não foi selecionada.',
                        parent=master)
        x.addButton(QMessageBox.Ok)
        x.setInformativeText(
            "Por favor, verifique a tabela e selecione a coluna correta.")
        x.exec()
        raise KeyError

    # filtra a(s) coluna(s) correspondente(s) a data/hora.
    if "Data" in headerdict.keys():
        try:
            datetime = df[df.columns[headerdict["Data"]]] + ' ' + df[
                df.columns[headerdict["Hora"]]]

        except:
            x = QMessageBox(
                QMessageBox.Warning,
                "Erro de Seleçao",
                'A coluna correspondente a "Hora" não foi selecionada',
                parent=master)
            x.addButton(QMessageBox.Ok)
            x.setInformativeText(
                "Por favor, verifique a tabela e selecione a coluna correta.")
            x.exec()
            raise KeyError

    elif "Data & Hora" in headerdict.keys():
        datetime = df[df.columns[headerdict["Data & Hora"]]]

    else:
        x = QMessageBox(
            QMessageBox.Warning,
            "Erro de Seleçao",
            'A coluna correspondente a "Data" ou "Hora" não foi selecionada',
            parent=master)
        x.addButton(QMessageBox.Ok)
        x.setInformativeText(
            "Por favor, verifique a tabela e selecione a coluna correta.")
        x.exec()
        raise KeyError

    new_df = pd.DataFrame(observados.to_numpy(),
                          datetime.to_numpy(),
                          columns=["Observado"])

    return new_df
Ejemplo n.º 9
0
def convert_dtype(master, df):
    ''' Recebe o dataframe e converte os tipos de suas colunas.'''
    dataformat = master.linkdata[master.FormatoData.currentText()]
    timeformat = master.linktime[master.FormatoTime.currentText()]
    datetimeformat = dataformat + ' ' + timeformat

    try:
        df.index = pd.to_datetime(df.index, format=datetimeformat)

    except ValueError:
        x = QMessageBox(QMessageBox.Critical,
                        "Erro de Formatação",
                        "O formato especificado para Data ou Hora é inválido.",
                        parent=master)
        x.addButton(QMessageBox.Ok)
        x.setInformativeText(
            "Por favor, verifique o formato da data ou o conteúdo da coluna.")
        x.exec()
        raise ValueError

    try:
        df['Observado'] = pd.to_numeric(df['Observado'], errors="coerce")

    except ValueError:
        x = QMessageBox(QMessageBox.Critical,
                        "Erro de Formatação",
                        "Não foi possível identificar o valor registrado",
                        parent=master)
        x.addButton(QMessageBox.Ok)
        x.setInformativeText(
            'Por favor, verifique o conteúdo da coluna associada a precipitação registrada.'
        )
        x.exec()
        raise ValueError

    return df
Ejemplo n.º 10
0
class Principal(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.inicializar_db()
        self.setWindowTitle("Tião Automecânica - Clientes")
        self.widget = QWidget()

        # Janelas
        w1, w2 = Buscador(), NovoCliente()
        w1.status_signal.connect(self.atualizar_status)
        w2.status_signal.connect(self.atualizar_status)

        # Leiaute
        self.line = QFrame()
        self.line.setFrameShape(QFrame.VLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setLineWidth(0)
        self.line.setMidLineWidth(1)
        self.layout = QGridLayout()
        self.layout.addWidget(w1, 0, 0, 1, 1)
        self.layout.addWidget(self.line, 0, 1, 1, 1)
        self.layout.addWidget(w2, 0, 1, 1, 2)
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)

        # Menu
        self.menu = QMenuBar()
        self.setMenuBar(self.menu)
        self.sobre = QAction("Sobre", self)
        self.sobre.setShortcut("F1")
        self.menu.addAction(self.sobre)
        self.sobre.triggered.connect(self.info)

        # Status
        self.status = QStatusBar()
        self.setStatusBar(self.status)
        self.status_label = QLabel("Pronto")
        self.status.addWidget(self.status_label)

    @Slot()
    def info(self):
        self.popup = QMessageBox(QMessageBox.Information, "Sobre",
                                 "Informações")
        self.popup.setInformativeText("""Clientes \nVersão 0.5
        \nFeito com S2 por Zero \nMIT License""")
        self.popup.addButton(QMessageBox.Ok)
        self.popup.exec()

    @Slot()
    def atualizar_status(self, msg: str):
        self.status_label.setText(msg)

    @staticmethod
    def inicializar_db():
        try:
            init_db()
        except NameError:
            popup = QMessageBox(QMessageBox.Critical, "Erro", "Erro")
            popup.setInformativeText(
                "Arquivo de configuração não foi encontrado")
            popup.addButton(QMessageBox.Ok)
            popup.exec()
            exit(1)
Ejemplo n.º 11
0
def run():
    initialization_result = initialize()

    conf = config()
    window_config = conf['window']

    WIDTH = window_config['width']
    HEIGHT = window_config['height']

    app = QApplication(sys.argv)

    app.setStyleSheet(style)

    geometry = app.screens()[0].size()
    clipboard = app.clipboard()

    widget = MainWidget(clipboard)
    widget.setWindowOpacity(window_config['opacity'])
    widget.resize(WIDTH, HEIGHT)
    widget.move(0, geometry.height() - HEIGHT - 280)

    widget.setWindowTitle('Albion Online Stats')
    widget.setWindowIcon(QtGui.QIcon(path('albion-stats-icon.png')))

    if window_config['always_on_top']:
        widget.setWindowFlag(Qt.WindowStaysOnTopHint)
    if window_config['frameless']:
        widget.setWindowFlag(Qt.FramelessWindowHint)

    widget.show()

    current_version, latest_version = (get_current_version(),
                                       get_latest_version())

    if latest_version and current_version != latest_version:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowTitle("Update available!")
        msg.setText("Another version of app is avaliable.")
        msg.setInformativeText(
            "You are using app in version {}, latest version is {}".format(
                current_version, latest_version))
        msg.setStandardButtons(QMessageBox.Ok)
        msg.show()

    if initialization_result == InitializationResult.NetworkInterfaceListMissing:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setWindowTitle("Unable to track network traffic data!")
        msg.setText(
            "On windows make sure that WinPcap is installed in your system.")
        msg.setInformativeText(
            "WinPcap can be installed from <a href='{}'>here</a> <br>\
            <b>Make sure to install with the \"Install Npcap in WinPcap API-compatible Mode\"<b> option<br><br>\
            In case where npcap is installed try to fix npcap and restart the app"
            .format('https://nmap.org/npcap/dist/npcap-0.9990.exe'))
        msg.setStandardButtons(QMessageBox.Ok)
        button = QPushButton("Fix npcap")

        button.clicked.connect(fix_npcap)
        msg.addButton(button, QMessageBox.NoRole)
        msg.show()

    sys.exit(app.exec_())