segunda-feira, 27 de janeiro de 2020

Qt Highlighter - Multiplos em vetor de inteiros

As duas versões anteriores deste programa,
que foram criadas uma no Qt e outra no C++ Builder,
era bastante limitada, o vetor de 100 elementos,
foi adaptado ao tamanho da janela e mesmo assim
foi muito bem aceito nos grupos onde postei.
Nesta versão preenchemos um vetor de inteiros
com 10000 elementos, e adaptamos um scrollArea
para um label, o que não é um procedimento padrão,
um QLabel não possui scrollArea,
mas fizemos isto funcionar com sucesso.





#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QPainter>
#include <QLabel>

MainWindow::MainWindow ( QWidget *parent ) :
    QMainWindow ( parent ),
    ui ( new Ui::MainWindow )
{
    ui -> setupUi ( this );
    Contador ( );
}

MainWindow::~MainWindow ( )
{
    delete ui;
}
//====================================================================
QString str;
QString pesq;
int A [ 10000 ];
void MainWindow :: Contador ( ) {
    //Personaliza os componentes com css
    ui -> groupBox -> setStyleSheet("QGroupBox{"
                        "width:10;"
                        "height:10;"
                        "border-style: solid;"
                        "border-color: #f00 #0f0 #00f #fc0;"
                        "border-width: 15px;};");

    ui -> lineEdit -> setStyleSheet("QLineEdit{"
                                    "border: 2px solid blue;"
                                    "font-family: Arial;"
                                    "font-style: italic;"
                                    "font-size: 12pt;"
                                    "background: skyblue;"
                                    "color: black;"
                                    "font-weight: bold;};");

    ui -> pushButton -> setStyleSheet("QPushButton{"
                                      "font-weight: bold;"
                                      "font-size: 16px;"
                                      "font-family: Arial;"
                                      "font-style: italic;"
                                      "color: black;"
                                      "background-color: pink;"
                                      "border: 2px solid blue;};");

    ui -> pushButton_2 -> setStyleSheet("QPushButton{"
                                        "font-weight: bold;"
                                        "font-size: 16px;"
                                        "font-family: Arial;"
                                        "font-style: italic;"
                                        "color: black;"
                                        "background-color: pink;"
                                        "border: 2px solid blue;};");

    //Cria um label, Posiciona, e fixa um tamanho
    QLabel * l = new QLabel ( this );
    l -> setGeometry ( 40, 30, 600, 30 );
    l -> setStyleSheet("QLabel{"
                   "font-family: Arial;"
                   "font-style: italic;"
                   "font-weight: bold;"
                   "font-size: 16pt;"
                   "color : red;};");
    l -> setText("QT HIGHLIGHTER - MÚLTIPLOS EM VETOR DE INTEIROS");

    //Cria um label, Posiciona, e fixa um tamanho
    QLabel * l_2 = new QLabel ( this );
    l_2 -> setGeometry ( 270, 390, 220, 60 );
    l_2 -> setText ("<font face=\"Arial\">"
                    "<font size=\"5\">"
                    "<font color=\"blue\">"
                    "<i> <b> Por: </i></b>"
                    "<font color=\"red\">"
                    "<i> <b> Samuel Lima </i></b>"
                    "<br /> <font color=\"black\">"
                    "<i> <b> sa_sp10@hotmail.com </i></b>" );

    QVBoxLayout *layout = new QVBoxLayout ( );
    ui -> scrollAreaWidgetContents -> setLayout ( layout );
    ui -> scrollArea -> setGeometry ( QRect ( 50, 50, 560, 300 ) );
    ui -> scrollAreaWidgetContents -> setStyleSheet ("border: 3px solid blue;");

    //Posiciona, e fixa um tamanho para os componentes
    ui -> groupBox -> setGeometry ( 0, 0, 650, 447 );
    ui -> lineEdit -> setGeometry ( 50, 400, 100, 20 );
    ui -> pushButton -> setGeometry ( 170, 400, 40, 20 );
    ui -> pushButton_2 -> setGeometry ( 560, 400, 40, 20 );
    ui -> lineEdit -> setFocus ( );

    int a = 0, i;
    for( i = 0; i < 10000; i++ ) {
        A [ a ] =  i;
        a++;
    }
    int mult = 1000;
    for( a = 0; a < 10000; a++ ) {
            str += "    ";
        if ( a % 10 == 0 )
            str += "<p>";
        if ( a >= 0 && a < 10 && a % mult )
            str += ( "000" );
        if ( a == 0 )
            str += ( "000" );
        if ( a >= 10 && a < 100 )
            str += ( "00" );
        if ( a >= 100 && a < 1000 )
            str += ( "0" );
        str += QString::number (  A [ a ] );
    }

    //Fixa os limites máximos de um label
    ui -> label -> setFixedSize ( 520, 34030 );
    ui -> label -> setAlignment ( Qt::AlignLeft|Qt::AlignTop );
    ui -> label -> setStyleSheet("QLabel { color : black; }");
    ui -> label -> setText (  str  );

    layout -> addWidget ( ui -> label );
}
//============================================================
void MainWindow::on_pushButton_clicked ( ) {
//SINTIU FALTA DE ALGUNS CÓDIGOS
}
//============================================================
void MainWindow::on_pushButton_2_clicked ( ){
    close ( );
}
//====================================================================
 
 
 
 
#ifndef MAINWINDOW_H
#define MAINWINDOW_H


#include <QMainWindow>
#include <stdlib.h>
namespace Ui {
class MainWindow;
}


class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


private slots:
void Contador ( );


void on_pushButton_clicked();


void on_pushButton_2_clicked();


private:
    Ui::MainWindow *ui;
    int cont = 0;
};


#endif // MAINWINDOW_H

 
 
 
#include "mainwindow.h"
#include <QApplication>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();


    return a.exec();
} 

sexta-feira, 24 de janeiro de 2020

Qt Highlighter - pesquisando string em matriz

Passado muitos dias sem programar,
"Porque não somos de ferro",
abrimos os últimos projetos para revisão,
e logo percebemos a necessidade de alguns ajustes,
mas preferimos criar um novo projeto,
uma versão mais robusta do que já havíamos criado.
O post: "Pesquisando string em matriz bidimensional",
que foi criado no embarcadero, já trazia os resultados
das pesquisas feitas na matriz com um destaque em highlighter,
mas era limitado somente na visão da janela,
e logo me veio a pergunta: -E se eu quisesse pesquisar
num arquivo de texto com umas 10 mil linhas?
isto não estava correto, ou ajustava ou criava  um novo projeto.
Decidimos criar um novo projeto e escolhi o Qt Widgets
depois de algumas tentativas com o Embarcadero.
E o que nos levou a esta escolha foi a integração do Qt
com o css e o html, quem conhece estas linguagens de marcação
sabe o que elas podem fazer e aqui nem preciso comentar.
Eliminamos muitas linhas do programa usando o html,
sendo assim muito bem otimizado em relação a primeira
versão criada no Qt no qual usava dois labels acoplado
num scrollArea e um punhado de códigos.




#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QScrollArea>
#include <cstring>
#include <iostream>

MainWindow::MainWindow ( QWidget *parent ) :
    QMainWindow  ( parent ),
    ui ( new Ui::MainWindow )
{
    ui -> setupUi ( this );
    Pesq_String ( );
}

MainWindow::~MainWindow ( )
{
    delete ui;
}
//====================================================================
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QLabel>
#include <string.h>
#include <QGroupBox>

#define lin  110
#define col 60

char texto [ lin ] [ col ] =  {
    "Hillsong United - Grace To Grace",
    "                                                        ",
    "If love endured that ancient cross                      ",
    "How precious is my Savior's blood                       ",
    "The beauty of heaven wrapped in my shame                ",
    "The image of love upon death's frame                    ",
    "If having my heart was worth the pain                   ",
    "What joy could you see beyond the grave                 ",
    "If love found my soul worth dying for                   ",
    "                                                        ",
    "How wonderful                                           ",
    "How glorious                                            ",
    "My Savior's scars victorious                            ",
    "My chains are gone                                      ",
    "My debt is paid                                         ",
    "From death to life                                      ",
    "And grace to grace                                      ",
    "                                                        ",
    "If heaven now owns that vacant tomb                     ",
    "How great is the hope that lives in You                 ",
    "The passion that tore through hell like a rose          ",
    "The promise that rolled back death and its stone        ",
    "If freedom is worth the life You raised                 ",
    "Where is my sin? Where is my shame?                     ",
    "If love paid it all to have my heart                    ",
    "                                                        ",
    "How wonderful                                           ",
    "How glorious                                            ",
    "My Savior's scars victorious                            ",
    "My chains are gone                                      ",
    "My debt is paid                                         ",
    "From death to life                                      ",
    "And grace to grace                                      ",
    "                                                        ",
    "When I see that cross, I see freedom                    ",
    "When I see that grave, I'll see Jesus                   ",
    "And from death to life, I will sing Your praise         ",
    "In the wonder of Your grace                             ",
    "When I see that cross, I see freedom                    ",
    "When I see that grave, I'll see Jesus                   ",
    "And from death to life, I will sing Your praise         ",
    "In the wonder of Your grace                             ",
    "How my soul will sing Your praise                       ",
    "In the wonder of Your grace                             ",
    "How my soul will sing Your praise                       ",
    "                                                        ",
    "How wonderful                                           ",
    "How glorious                                            ",
    "My Savior's scars victorious                            ",
    "My chains are gone                                      ",
    "My debt is paid                                         ",
    "From death to life                                      ",
    "And grace to grace                                      ",
    "                                                        ",
    "Hillsong United - Grace to Grace - tradução em PTBR     ",
    "Graça Em Graça                                          ",
    "                                                        ",
    "Se o amor suportou a antiga cruz                        ",
    "Quão precioso é o meu sangue do Salvador                ",
    "A beleza do céu envolto em minha vergonha               ",
    "A imagem do amor sobre o quadro de morte                ",
    "Se ter o meu coração fez valer a pena a dor             ",
    "Que alegria você poderia ver além da sepultura          ",
    "Se o amor achou que valia a pena morrer pela minha alma ",
    "                                                        ",
    "Quão maravilhosa                                        ",
    "Quão gloriosa                                           ",
    "As cicatrizes do meu Salvador vitorioso                 ",
    "Minhas correntes se foram                               ",
    "Minha dívida está paga                                  ",
    "Da morte para a vida                                    ",
    "E de graça em graça                                     ",
    "                                                        ",
    "Se agora o céu é o dono da tumba vazia                  ",
    "Como é grande a esperança que vive em Ti                ",
    "A paixão que atravessou o inferno como uma rosa         ",
    "A promessa de que rolou a morte e sua pedra             ",
    "Se a liberdade vale a vida que você ergueu              ",
    "Onde está o meu pecado? Onde está minha vergonha?       ",
    "Se o amor pagou tudo para ter meu coração               ",
    "                                                        ",
    "Quão maravilhosa                                        ",
    "Quão gloriosa                                           ",
    "As cicatrizes do meu Salvador vitorioso                 ",
    "Minhas correntes se foram                               ",
    "Minha dívida está paga                                  ",
    "Da morte para a vida                                    ",
    "E de graça em graça                                     ",
    "                                                        ",
    "Quando vejo aquela cruz, vejo liberdade                 ",
    "Quando vejo aquela sepultura, verei Jesus               ",
    "E da morte à vida, cantarei Seu louvor                  ",
    "Na maravilha da Tua graça                               ",
    "Quando vejo aquela cruz, vejo liberdade                 ",
    "Quando vejo aquela sepultura, verei Jesus               ",
    "E da morte à vida, cantarei Seu louvor                  ",
    "Na maravilha da Tua graça                               ",
    "Como minha alma vai cantar seu louvor                   ",
    "Na maravilha da Tua graça                               ",
    "Como minha alma vai cantar seu louvor                   ",
    "                                                        ",
    "Quão maravilhosa                                        ",
    "Quão gloriosa                                           ",
    "As cicatrizes do meu Salvador vitorioso                 ",
    "Minhas correntes se foram                               ",
    "Minha dívida está paga                                  ",
    "Da morte para a vida                                    ",
    "E de graça em graça                                     ",
    "                                                        "};

//====================================================================
void MainWindow :: Pesq_String ( ) {
    QString str;
    int i,  j = 0;

    for ( i = 0; i < lin; i++ ) {
        str += ("<br />");
        for ( j = 0; j < col; j++ ) {
            str += texto [ i ] [ j ];
        }
    }
    //Cria um label, Posiciona, e fixa um tamanho
    QLabel * l = new QLabel ( this );
    l -> setGeometry ( 20, 30, 600, 30 );
    l -> setStyleSheet("QLabel{"
                   "font-family: Arial;"
                   "font-style: italic;"
                   "font-weight: bold;"
                   "font-size: 16pt;"
                   "color : red;};");
    l -> setText("QT HIGHLIGHTER - PESQUISANDO STRING EM MATRIZ");

    //Cria um label, Posiciona, e fixa um tamanho
    QLabel * l_2 = new QLabel ( this );

    l_2 -> setGeometry ( 270, 370, 220, 60 );
    l_2 -> setText ("<font face=\"Arial\">"
                    "<font size=\"5\">"
                    "<font color=\"blue\">"
                    "<i> <b> Por: </i></b>"
                    "<font color=\"red\">"
                    "<i> <b> Samuel Lima </i></b>"
                    "<br /> <font color=\"black\">"
                    "<i> <b> sa_sp10@hotmail.com </i></b>" );

   //Posiciona, e fixa um tamanho para os componentes
   ui -> groupBox -> setGeometry ( 0, 0, 600, 435 );
   ui -> textEdit -> setGeometry ( 50, 50, 500, 280 );
   ui -> lineEdit -> setGeometry ( 50, 385, 100, 20 );
   ui -> pushButton -> setGeometry ( 170, 385, 40, 20 );
   ui -> pushButton_2 -> setGeometry ( 510, 385, 40, 20 );

   //Personaliza os componentes com css
   ui -> groupBox -> setStyleSheet("QGroupBox{"
                       "width:10;"
                       "height:10;"
                       "border-style: solid;"
                       "border-color: #f00 #0f0 #00f #fc0;"
                       "border-width: 15px;};");

    ui -> textEdit -> setStyleSheet("QTextEdit{"
                   "border: 5px solid blue;"
                   "font-family: Arial;"
                   "font-style: italic;"
                   "font-size: 14pt;"
                   "background-color: white;"
                   "color: black;"
                   "font-weight: bold;};");

    ui -> lineEdit -> setStyleSheet("QLineEdit{"
                   "border: 2px solid blue;"
                   "font-family: Arial;"
                   "font-style: italic;"
                   "font-size: 12pt;"
                   "background: rgb(127,255,0);"
                   "color: black;"
                   "font-weight: bold;};");

    ui -> pushButton -> setStyleSheet("QPushButton{"
                                      "font-size: 16px;"
                                      "font-family: Arial;"
                                      "font-style: italic;"
                                      "border-width: 50px 50px 50px;"
                                      "border: 2px solid blue;"
                                      //"border-radius: 20px;"
                                      "background-color: yellow;"
                                      "color: black;};");

    ui -> pushButton_2 -> setStyleSheet("QPushButton{"
                                      "font-size: 16px;"
                                      "font-family: Arial;"
                                      "font-style: italic;"
                                      "border-width: 50px 50px 50px;"
                                      "border: 2px solid blue;"
                                      "border-radius: 20px;"
                                      "background-color: yellow;"
                                      "color: black;};");

    ui -> textEdit -> setText (  str  );
    ui -> lineEdit -> setFocus ( );
   }
//============================================================
//ESTÁ FALTANDO ALGUNS CÓDIGOS??????????
//============================================================
void MainWindow::on_pushButton_2_clicked ( ){
    close ( );
}

//============================================================


#ifndef MAINWINDOW_H
#define MAINWINDOW_H


#include <QMainWindow>
#include <stdlib.h>
namespace Ui {
class MainWindow;
}


class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


private slots:
void on_pushButton_clicked ( );
void on_pushButton_2_clicked ( );
void Pesq_String ( );


private:
    Ui::MainWindow *ui;
int cont = 0;
};


#endif // MAINWINDOW_H 


#include "mainwindow.h"

#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    w.show ( );
    return a.exec();
}