Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. International
  3. Portuguese
  4. Como incrementar e decrementar uma string (ip) com Key_UP e DOWN..
Forum Updated to NodeBB v4.3 + New Features

Como incrementar e decrementar uma string (ip) com Key_UP e DOWN..

Scheduled Pinned Locked Moved Solved Portuguese
11 Posts 2 Posters 2.4k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M MSDiLieto

    (Principiante em c++ e Qt) Galera, boa tarde, estou fazendo um sistema aqui. No caso o meu objetivo, por enquanto, e' conseguir pegar um "ip" pronto, e atraves do Key_UP E DOWN, incrementar ou decrementar o numero que o cursor esta' apontando. Se eu jogar p direita com Key_RIGHT e LEFT, o cursor avanca ou retrocede uma posicao da lista string "ip" e por ai vai.. (tudo isso em C++) desculpem a falta de acentos..

    KillerSmathK Offline
    KillerSmathK Offline
    KillerSmath
    wrote on last edited by
    #2

    Olá @MSDiLieto. Seja bem vindo ao Qt Forum.

    Você está utilizando QLineEdit para editar seu IP ?

    Você pode sobreescrever a função keyPressEvent(QKeyEvent *event) em um QLineEdit customizado, e assim, implementar essa ideia de incremento e decremento no Texto IP.

    @Computer Science Student - Brazil
    Web Developer and Researcher
    “Sometimes it’s the people no one imagines anything of who do the things that no one can imagine.” - Alan Turing

    1 Reply Last reply
    0
    • M Offline
      M Offline
      MSDiLieto
      wrote on last edited by
      #3

      #include <QLabel>
      #include "qlabel.h"
      #include <iostream>
      #include "QStringList"
      #include <qstringlist.h>
      #include <QDebug>

      int old;
      int num = old;
      char ip[] = "000.000.000.000";
      int CursorPosition = 0;
      MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MainWindow)
      {
      ui->setupUi(this);

      ui->lineEdit->setText(ip);
      ui->lineEdit->setCursorPosition(0);
      

      // ui->lineEdit->cursorPositionChanged();
      connect(ui->lineEdit, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(trataMove(int, int)));
      }

      MainWindow::~MainWindow()
      {
      delete ui;
      }

      //QStringList strings;
      //strings << "line one" << "line two";
      //yourTextEdit->setText(strings.join("\n"));

      void MainWindow::trataMove(int old,int novo) {
      // qDebug() << "MEXI!!" << old << novo;
      qDebug() << ip[novo];
      CursorPosition = novo;
      }

      void MainWindow::keyPressEvent(QKeyEvent * event)
      {
      // QStringList ip = "000.000.000.000";
      // int i = 0;
      qDebug() << event->key();
      if(event->key() == Qt::Key_Up){
      char number = ip[CursorPosition];
      int numero = number - '0';
      numero++;
      ip[CursorPosition] = numero + '0';
      ui->lineEdit->setText(ip);
      qDebug() << CursorPosition;
      CursorPosition++;
      ui->lineEdit->setCursorPosition(ip[CursorPosition]);

      }
      
       if(event->key() == Qt::Key_Down){
          char number = ip[CursorPosition];
          int numero = number - '0';
          numero--;
          ip[CursorPosition] = numero + '0';
          ui->lineEdit->setText(ip);
          qDebug() << CursorPosition;
          CursorPosition++;
          ui->lineEdit->setCursorPosition(ip[CursorPosition]);
      
      
      }
      
       if(event->key() == Qt::Key_Right){
           qDebug() << "sdbfjafhaf";
       }
      

      // if(event->key() == Qt::Key_Right){
      // ui->label->setText("000.000.000.000");
      // for (i = 0; i<=15; i++){
      // ui->lineEdit->setText(ip[3]);
      // }
      //}
      }

      1 Reply Last reply
      0
      • M Offline
        M Offline
        MSDiLieto
        wrote on last edited by
        #4
        This post is deleted!
        1 Reply Last reply
        0
        • M Offline
          M Offline
          MSDiLieto
          wrote on last edited by
          #5

          E' o que estou fazendo praticamente, mas estao acontecendo que:

          Quando incremento ou decremento, o cursor volta para a posicao 0..
          esse e' o meu codigo, desculpa a falta de orgnizacao, se entender ou faltar algo p vc entender, pode me pedir..
          agradeco desde ja, a resposta e as boas vindas!! ^^
          
          KillerSmathK 1 Reply Last reply
          0
          • M MSDiLieto

            E' o que estou fazendo praticamente, mas estao acontecendo que:

            Quando incremento ou decremento, o cursor volta para a posicao 0..
            esse e' o meu codigo, desculpa a falta de orgnizacao, se entender ou faltar algo p vc entender, pode me pedir..
            agradeco desde ja, a resposta e as boas vindas!! ^^
            
            KillerSmathK Offline
            KillerSmathK Offline
            KillerSmath
            wrote on last edited by
            #6

            @MSDiLieto

            Você pode salvar a antiga posição do cursor e definir a posição atual, então depois de mudar o texto do LineEdit, só é necessário restaurar a posição.

            Segue abaixo um exemplo de como isso poderia ser implementado (utilizando o seu trecho de código):

            #include <QStringList>
            #include <QString>
            #include <QtMath>
            
            QString ip = "000.000.000.000";
            int CursorPosition = 0;
            
            void MainWindow::keyPressEvent(QKeyEvent * event)
            {
                if(event->key() == Qt::Key_Up || event->key() == Qt::Key_Down){
                    // Se estiver no caracter nulo da String ou estiver em um delimitador, então anule a ação
                    if(CursorPosition == ip.count()) return;
                    if(ip.at(CursorPosition) == '.' ) return;
            
                    // Quebrar IP String em segmentos de strings [0] 000 [1] 000 [2] 000 [3] 000
                    QStringList ipSplitted = ip.split('.');
            
                    // Calculando as Posições
                    const int sectionPos = CursorPosition / 4;
                    const int characterPos = CursorPosition % 4;
            
                    // Selecionar a sentença e converter para Inteiro
                    int ipNumber = ipSplitted.at(sectionPos).toInt();
            
                    // Subtrair ou Somar 10^posição
                    if(event->key() == Qt::Key_Up){
                        ipNumber += pow(10, (2-characterPos));
                        if(ipNumber > 255) ipNumber = 255;
                    }
                    else{
                        ipNumber -= pow(10, (2-characterPos));
                        if(ipNumber < 0) ipNumber = 0;
                    }
            
                    // Inserir Nova Sentença de IP
                    QString ipSentence;
                    ip.replace(sectionPos * 4, 3, ipSentence.sprintf("%03d", ipNumber));
            
                    // Inserir String no LineEdit e restaurando posição do Cursor
                    const int restorePosition = CursorPosition;
                    ui->lineEdit->setText(ip);
                    ui->lineEdit->setCursorPosition(restorePosition);
                }
            }
            

            @Computer Science Student - Brazil
            Web Developer and Researcher
            “Sometimes it’s the people no one imagines anything of who do the things that no one can imagine.” - Alan Turing

            1 Reply Last reply
            0
            • M Offline
              M Offline
              MSDiLieto
              wrote on last edited by
              #7

              Muito obrigado mesmo meu amigo! A unica coisa q adicionei para dar certo foi:

              void MainWindow::keyPressEvent(QKeyEvent * event)
              {
                  **CursorPosition = ui->lineEdit->cursorPosition();**
                  if(event->key() == Qt::Key_Up || event->key() == Qt::Key_Down){
                      // Se estiver no caracter nulo da String ou estiver em um delimitador, então anule a ação
                      if(CursorPosition == ip.count()) return;
                      if(ip.at(CursorPosition) == '.' ) return;
              
              1 Reply Last reply
              0
              • M Offline
                M Offline
                MSDiLieto
                wrote on last edited by
                #8

                @KillerSmath
                E se for uma string "numerica", q incremente no mesmo esquema, tipo:

                numeric = 000000
                000001, 000002, 000009, 000010...

                KillerSmathK 1 Reply Last reply
                0
                • M MSDiLieto

                  @KillerSmath
                  E se for uma string "numerica", q incremente no mesmo esquema, tipo:

                  numeric = 000000
                  000001, 000002, 000009, 000010...

                  KillerSmathK Offline
                  KillerSmathK Offline
                  KillerSmath
                  wrote on last edited by KillerSmath
                  #9

                  @MSDiLieto
                  QSpinBox implementa essa ideia de incrementar e decrementar valores utilizando os teclas de Key_UP e Key_Down.
                  Porém como você pretende exibir uma string do tipo 0000001 ao invés de 1 então é necessário sobrecarregar o método textFromValue

                  https://stackoverflow.com/questions/26537473/qdoublespinbox-with-leading-zeros-always-4-digits/26538572#26538572

                  Por fim, promova a sua nova classe para uma QSpinBox normal, dessa forma ao invés da sua interface utilizar um QSpinBox comum, ela passará a utilizar sua classe.

                  https://forum.qt.io/topic/102343/how-to-get-promoted-widget-to-show/2

                  @Computer Science Student - Brazil
                  Web Developer and Researcher
                  “Sometimes it’s the people no one imagines anything of who do the things that no one can imagine.” - Alan Turing

                  M 1 Reply Last reply
                  0
                  • KillerSmathK KillerSmath

                    @MSDiLieto
                    QSpinBox implementa essa ideia de incrementar e decrementar valores utilizando os teclas de Key_UP e Key_Down.
                    Porém como você pretende exibir uma string do tipo 0000001 ao invés de 1 então é necessário sobrecarregar o método textFromValue

                    https://stackoverflow.com/questions/26537473/qdoublespinbox-with-leading-zeros-always-4-digits/26538572#26538572

                    Por fim, promova a sua nova classe para uma QSpinBox normal, dessa forma ao invés da sua interface utilizar um QSpinBox comum, ela passará a utilizar sua classe.

                    https://forum.qt.io/topic/102343/how-to-get-promoted-widget-to-show/2

                    M Offline
                    M Offline
                    MSDiLieto
                    wrote on last edited by
                    #10

                    @KillerSmath
                    Nossa cara, me ajudou mt, tava dando certo aqui, mas quem esta' pedindo, quer no mesmo formato do QLineEdit.. tem como?

                    KillerSmathK 1 Reply Last reply
                    0
                    • M MSDiLieto

                      @KillerSmath
                      Nossa cara, me ajudou mt, tava dando certo aqui, mas quem esta' pedindo, quer no mesmo formato do QLineEdit.. tem como?

                      KillerSmathK Offline
                      KillerSmathK Offline
                      KillerSmath
                      wrote on last edited by
                      #11

                      @MSDiLieto
                      Sim, você pode incorporar o comportamento que quiser desde que a função seja virtual. Faça isso diretamente em um QLineEdit ou simplemente rescreva essa ideia com base no QSpinBox.

                      @Computer Science Student - Brazil
                      Web Developer and Researcher
                      “Sometimes it’s the people no one imagines anything of who do the things that no one can imagine.” - Alan Turing

                      1 Reply Last reply
                      0

                      • Login

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved