Código: |
//Suma de dos variables string en lazarus y delphi: A:= 'Hola '; B:= 'mundo'; C:= A+B; //Suma de dos cadenas string en lazarus y delphi: C:= 'Hola' + 'mundo'; //En ambos casos generaría una sola cadena tipos String que contiene la suma de los dos textos: "Hola mundo" |
Mostrando entradas con la etiqueta lazarus. Mostrar todas las entradas
Mostrando entradas con la etiqueta lazarus. Mostrar todas las entradas
domingo, 15 de diciembre de 2013
Lazarus concatenar o unir cadenas tipo String
En lazarus para unir o concatenar varias cadenas tipo String solo tenemos que actuar sobre ellas como si se tratara de una suma comun y corriente:
Lazarus convertir Boolean a String
Hace unos segundos me he visto en la necesidad de convertir un dato Boolean en uno tipo String y como no sabia si lazarus incorporaba o tenia esta función, he hecho una búsqueda en internet y me he encontrado con esta función muy simple y socorrida:
Código: |
function booltostr(n: boolean):string; begin if n = true then result := 'true' else result:='false'; end; |
Supongo que no hace falta explicar que para utilizarla podemos hacer una llamada tipo booltostr():
Código: |
procedure TForm1.CheckDesbloquearSalidasChange(Sender: TObject); begin if (CheckDesbloquearSalidas.Checked = false) then begin ShowMessage('Ahora el estado de las salidas es: '+ booltostr(CheckDesbloquearSalidas.Checked)); end; end; |
Este artículo basado en este post:
miércoles, 23 de octubre de 2013
Lazarus Conectar a una base de datos SQLite 3 + Video
He hecho este mini manual para poder acordarme como conectar con la base de datos sqlite, ya que me ha costado un poco el aprender a conectar mi programa a la base de datos.
Este es el codigo que he utilizado:
Para poder aprender hacer esto la información la he conseguido en:
http://alevel-computing.x10.mx/mw/index.php/Lazarus
Este es el codigo que he utilizado:
Código: |
|
Para poder aprender hacer esto la información la he conseguido en:
http://alevel-computing.x10.mx/mw/index.php/Lazarus
jueves, 3 de octubre de 2013
Lazarus y sqlite
En estos momentos estoy intentando aprender a programar una pequeña base de datos SQLlite con lazarus, para ello estoy utilizando la información de esta web:
http://alevel-computing.x10.mx/mw/index.php/Lazarus
http://www.alevel-computing.x10.mx/TutorialSoftwareRevision2.php
Contents
Top
Code You will find the SQLite3Connection component in the SQLDB component palette. It's invisible when the program runs. The best way is to leave the object inspector alone and set up the connection purely using code, as I have done. The key lines are
Design Screenshot

Executable Screenshot
SourceCode Source code
Top
The DBGrid component makes it easy to see your database.
The DBNavigator makes it easy to maintain your database.
When you 'post' a change it changes the grid but not the actual database on disk. Just click 'COMMIT'to do that. Otherwise, they couldn't be easier to use.
Code
Design Screenshot

Executable Screenshot
SourceCode Source code
Top
The DBEdit component shows the database one entry at a tiem in edit boxes.
Code
Design Screenshot

Executable Screenshot
SourceCode Source code
Top
The DBMemo lets you see longer comments or even whole books.
The DBImage lets you see all knds of graphics for each entry.
Sound uses the Windows command ShellExecute() which is Windows specific - you need to use TProcess for other operating systems
Code
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
This is useful because you can run queries such as
To create a new procedure you can put it in the 'Public' section of Form1. In its definition, don't froget to rite TForm1 as in
TForm1.InsertIntoDatabase;
There are new procedures for INSERT and SELECT type statements. There are new procedures for using the stringgrid and memo box.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
You will need to get Student2.db by making it from the Student2.txt file of SQL here .
This is now becoming a fully woking relational database
Code The database here is called student2 and the SQL can be used to create it in exactly the same way as before. Don't forget you need 'student2.db' and 'sqlite3.dll' in the same folder as your project.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
There is a lso a 'search function here- very easy to implement.
Code The navigation buttons all involve single line instructions like SQLQuery.next. There is a mixture of DBedits and normal edit boxes. The delete and update (edit) functions are basically the same and share a set of DBEdits. The insert button uses normal edit boxes, because they don't need to be linked to the database.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
Code The code explains how to install the LazReport package. It will take about 15 minutes whenyou do it for the first time. You need to make sure that Printer4Lazarus is also installed - it probably is.
The components you will use are
Executable Screenshot
SourceCode Source code
Top
http://alevel-computing.x10.mx/mw/index.php/Lazarus
http://www.alevel-computing.x10.mx/TutorialSoftwareRevision2.php
Lazarus Database Tutorial
Version 1
Contents
- Connect
- DBGrid and DBNavigator
- DBEdit
- DBMemo and DBImage and sound
- Using SQL
- Several tables
- Buttons instead of DBNavigator
- LazReport
- Summary
Top
Connect
Introduction Connecting to an external database is easy - as long as everything is in place before you try. You'll need sqlite3.dll, sqlite3.exe and the Student database from here. There is even a magnificent SQLite tutorial (which you will undoubtedly want to work through first here. if you are really keen.Code You will find the SQLite3Connection component in the SQLDB component palette. It's invisible when the program runs. The best way is to leave the object inspector alone and set up the connection purely using code, as I have done. The key lines are
SQLite3Connection1.Database:='student.dbDon't forget you need 'student.db' and 'sqlite3.dll' in the same folder as your project.
SQLite3Connection1.Connect:=true;
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
DBGrid and DBNavigator
Introduction You can build this on top of the 'Connect' project.The DBGrid component makes it easy to see your database.
The DBNavigator makes it easy to maintain your database.
When you 'post' a change it changes the grid but not the actual database on disk. Just click 'COMMIT'to do that. Otherwise, they couldn't be easier to use.
Code
- SQLTransaction, SQLQuery (SQLDB palette) --> SQLConnection
- Datasource (DBAccess palette) --> SQLQuery
- DBGrid and DBNavigator (DBControls palette) --> Datasource.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
DBEdit
Introduction You can build this on top of the 'DBNavigator' project.The DBEdit component shows the database one entry at a tiem in edit boxes.
Code
- DBEdit (DBControls palette) --> Datasource.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
DBMemo, DBImage and sound
Introduction Pictures and Sound in a database WOW!The DBMemo lets you see longer comments or even whole books.
The DBImage lets you see all knds of graphics for each entry.
Sound uses the Windows command ShellExecute() which is Windows specific - you need to use TProcess for other operating systems
Code
- ShellExecute needs you to write 'uses shellapi' (see source code)
- ad your own images and sounds. The sound format is mp3, mid or WAV.
- DBMemo and DBImage (DBControls palette) --> Datasource.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
Using SQL
Introduction This uses what you have done so far and adds to it. It displays the data in two other ways - in a stringGrid and in a memo box. Some people feel more comfortable with those. It also lets you execute any SQL statement.This is useful because you can run queries such as
'SELECT * FROM Student WHERE First like "M%"
'INSERT INTO Student VALUES (244, 'Charlie','Chaplin','13We'"which will pick out everyone whose first name begins with 'M' or add the comedian to the database. Code
To create a new procedure you can put it in the 'Public' section of Form1. In its definition, don't froget to rite TForm1 as in
TForm1.InsertIntoDatabase;
There are new procedures for INSERT and SELECT type statements. There are new procedures for using the stringgrid and memo box.
SQLite3Connection1.Database:='student.dbDon't forget you need 'student.db' and 'sqlite3.dll' in the same folder as your project.
SQLite3Connection1.Connect:=true;
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
Multiple tables
Introduction This uses what you have done in the previous tutorial and adds to it. It lets you view and edit any one of the four tables.You will need to get Student2.db by making it from the Student2.txt file of SQL here .
This is now becoming a fully woking relational database
Code The database here is called student2 and the SQL can be used to create it in exactly the same way as before. Don't forget you need 'student2.db' and 'sqlite3.dll' in the same folder as your project.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
Buttons instead of DBNavigator
Introduction Useful as the DBNavigator is, it's also interesting to see how to build a database without it. Here it is.There is a lso a 'search function here- very easy to implement.
Code The navigation buttons all involve single line instructions like SQLQuery.next. There is a mixture of DBedits and normal edit boxes. The delete and update (edit) functions are basically the same and share a set of DBEdits. The insert button uses normal edit boxes, because they don't need to be linked to the database.
Design Screenshot
Executable Screenshot
SourceCode Source code
Top
Using LazReport
Introduction There is a package you can install into Lazarus that lets you view and print the data nicely formatted. It is called LazReport. This package doesn't come ready-installed because not everyone will need it.Code The code explains how to install the LazReport package. It will take about 15 minutes whenyou do it for the first time. You need to make sure that Printer4Lazarus is also installed - it probably is.
The components you will use are
- frDBDataSet (LazReport palette) -- > Datasource
- frReport (LazReport palette) --> Datasource
Executable Screenshot
SourceCode Source code
Top
Tutorial Summary
Tutorial | Uses | Resources | SQL | Purpose |
---|---|---|---|---|
Connect | SQLite3Connection | Student.db | Student.txt | To get a basic connection |
DBGrid and DBNavigator | SQLTransacction, SQLQuery, DataSource, DBGrid, DBNavigator | Student.db | Student.txt | To show DBNavigator working |
DBEdit | DBEdit | Student.db | Student.txt | To show DBEdits in action |
DBMemo | DBMemo, DBImage | Student.db, Sounds folder, Details folder, Pictures folder | Student.txt | Multimedia database |
SQL | StringGrid, Memo | Student.db | Student.txt | Using SELECT and INSERT commands directly |
Multiple tables | Student2.db | Student2.txt | Using 4 related tables in your program | |
Buttons | Locate() | Student.db | Student.txt | How to implemet the database without DBNavigator |
LazReport | Student.db, LazReport package frDBDataSet, frReport | Student.txt | How to make a table look good |
martes, 1 de octubre de 2013
Lazarus ejecutar o usar una función que esta gurdada en otra unidad
Para depurar el codigo fuente mas facilmente y por otros muchos movitivos me gusta guardar todas las funciones juntas en un mismo archivo. Despues de insistir un poco tube que preguntar en el foro y me diero esta solucion:
http://www.clubdelphi.com/foros/showthread.php?t=84272
Mi herror era el no poner el implementation del Unit1 el comando uses Unit2;.
Con eso ya estaria listo y podriamos acceder a Unit2. Otra cosa muy importantes que no s tenemos que olvidar de poner en el implementation del Unit2 es el uses Unit1, ya que lo contrario no podriamos acceder y modificar propiedades de los componentes del form1...
http://www.clubdelphi.com/foros/showthread.php?t=84272
Mi herror era el no poner el implementation del Unit1 el comando uses Unit2;.
Código: |
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses Unit2; procedure TForm1.Button1Click(Sender: TObject); begin Edit1.Text := ReverseString(Edit1.Text); end; end. |
Con eso ya estaria listo y podriamos acceder a Unit2. Otra cosa muy importantes que no s tenemos que olvidar de poner en el implementation del Unit2 es el uses Unit1, ya que lo contrario no podriamos acceder y modificar propiedades de los componentes del form1...
Código: |
unit Unit2; interface // Cabecera de Funciones y Procedimientos de Unit2 visibles en otras unidades implementation uses Unit1; // Referencia a Unit1 // Implementación de Funciones y Procedimientos de Unit2 (Internas y Externas) end. |
Lazarus abrir y cerrar un FORM dede otro FORM
El otro día quise abrir y cerrar forms desde otro form pero a pesar de haber visto otros ejemplos no conseguía que me compilaran. Al final pregunte en el foro me respondierón esto:
http://www.clubdelphi.com/foros/showthread.php?t=83681
http://www.clubdelphi.com/foros/showthread.php?t=83681
Código: |
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} uses Unit2; { TForm1 } procedure TForm1.Button1Click(Sender: TObject); begin TForm2.ShowForm; end; end. |
Código: |
unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TForm2 } TForm2 = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private declarations } public class procedure ShowForm; end; var Form2: TForm2; implementation {$R *.lfm} procedure TForm2.FormCreate(Sender: TObject); begin Timer1.Enabled := False; //Iniciomaos el timer primero lo ponemos a 0 Timer1.Interval := 2000; //los milisegundos a los que saltara el timer Timer1.Enabled := True; //lo iniciamos. end; procedure TForm2.FormDestroy(Sender: TObject); begin Form2 := nil; end; procedure TForm2.Timer1Timer(Sender: TObject); begin close; //Cuando pasa el tiempo estipulado en el timer //ejecuta lo de esta función. end; class procedure TForm2.ShowForm; begin if not Assigned(Form2) then Form2 := TForm2.Create(nil); Form2.Show; // o ShowModal end; end. |
sábado, 7 de septiembre de 2013
Hola, hace un rato me hacia falta encontrar como se tenia que hacer para evitar que lazarus cree un formulario de manera automatica, y me he encontrado con este post en el blog de Mikelats en esta dirección: http://aitoreus.blogspot.com.es
Como en un lenguaje de programación moderno (con extensión para orientación a objetos), en Lazarus - FreePascal tenemos dos formas de abrir formularios:
Abrir formularios en Lazarus-FreePascal
Como en un lenguaje de programación moderno (con extensión para orientación a objetos), en Lazarus - FreePascal tenemos dos formas de abrir formularios:
- De forma estática. Diseñas los formularios. Luego, al iniciar la aplicación se crean todos los formularios, aunque están ocultos. Cuando quieras lo haces visible en tiempo de ejecución.
- De forma dinámica. Cuando abres una aplicación como el Microsoft Word, tú no sabes cuantos formularios "de documento" vas a tener que abrir. El usuario puede abrir 1 documento o 20. Cada vez que haga clic en "Nuevo documento" hay que abrir un formulario.

1.-FORMA ESTÁTICA DE CREAR FORMULARIOS.
Diseñamos los formularios que necesitemos con Lazarus. Para crear un nuevo formulario vamos al MENÚ ARCHIVO, Opción NUEVO FORMULARIO.
Hay que tener en cuenta que cada formulario gráfico que hemos creado está descrito en una unidad (UNIT). Para verlo seleccionamos el formulario y vamos al MENÚ VER, Opción "EDITOR DE CÓDIGO FUENTE". El nombre de la unidad se encuentra en la primera línea del código fuente del formulario. Por ejemplo:
unit Unit1;
Si desde este form1 que está definido en Unit1, queremos llamar al form2, tenemos que incluir la definición de form2 dentró de la sección uses:
uses:
xxxxx, xxxxxx, xxxxxx, xxxxxx, unit2;
Ahora ya podemos "llamar" al form2 desde form1. Realmente la invocación sólo consiste en hacer visible el formulario. Eso es así porque al arrancar se crean todos los formularios que hemos diseñado.
form2.show;
2.-FORMA DINÁMICA DE CREAR FORMULARIOS.
Tenemos que pensar que cada formulario es un objeto. Nuestro programa puede necesitar abrir varios objetos de ese tipo (formularios de entrada, informes, etc.), aunque cada uno tenga datos diferentes.
Vamos al MENÚ PROYECTO, Opción OPCIONES DEL PROYECTO, y elegimos FORMULARIO. Saldrá esta ventana:
Pasamos los formularios que haya que abrir dinámicamente, de la columna "CREAR FORMULARIOS AUTOMÁTICAMENTE" a la de "FORMULARIOS DISPONIBLES".
En los eventos OnClose de los formularios tenemos que añandir lo siguiente para que libere la memoria:
CloseAction:= caFree;
Lo único que hay que hacer ahora para abrir el form2 desde el form1 es instanciar el objeto form2:
procedure Tform1.Button1Click(Sender: TObject);
var
frmDocumento: Tform2;
begin
frmDocumento:= Tform2.Create(Application);
frmDocumento.Show;
end;
Saludos.
sábado, 13 de julio de 2013
Lazarus Borrar los EDIT y MEMO de golpe
Aun no he tenido tiempo de probar esta función que me paso un conocido por E-mail hace varios años, pero la voy a publicar ya que me parece muy interesante:
Código: |
procedure TForm1.Button1Click(Sender: TObject); procedure VaciaComponentesDeEdicion; var n : integer; begin for n:=0 to Pred(ComponentCount) do begin //Recorremos los componentes de la form y los vaciamos if Components[n] is TEdit then TEdit(Components[n]).Clear else if Components[n] is TMemo then TMemo(Components[n]).Lines.Clear else if Components[n] is TDBEdit then TDBEdit(Components[n]).Clear; end; end; begin VaciaComponentesDeEdicion; end; |
lunes, 8 de julio de 2013
Lazarus detener un bucle for
Para detener un bucle for tenemos que utilizar la sentencia break.
Código: |
for j := longitud_cadena downto 1 do begin Insert (cadena [j],resultado,n); //Inserta los caracteres a la var resultado. n := n + 1; //Contador N. if cadena [j] = ' ' then Break; end; |
Lazarus invertir el orden de una cadena de string
Para dar la vuelta a un string o mejor dicho para invertir su orden podemos utilizar esta instrucción:
Para utilizar esta instrucción hay que poner en el uses un enlace a las StrUtils.
Código: |
ReverseString(string_a_invertir ); |
Para utilizar esta instrucción hay que poner en el uses un enlace a las StrUtils.
Código: |
uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, StrUtils; type { TForm1 } |
sábado, 6 de julio de 2013
Programando en Lazarus, presentación
Hacia tiempo que no programaba en ningún leguaje de programación, ufff por lo menos 10 años... A pesar que durante estos últimos años he estado programando en HTML y PHP se puede decir que que he empezado prácticamente desde 0 con Lazarus.
Hace muchos años aprendi a programar en turbo pascal y luego me pase al delphi, pero lo tuve que dejar por que los estudios me absorbía mucho tiempo (sobretodo el viaje).
He decidido crear este otro bogg para tener mis apuntes siempre a mano en cualquier lugar del mundo, y no los quiero postear en mi otro bogo ya que esta mas orientado hacia la artesanía...
Hace muchos años aprendi a programar en turbo pascal y luego me pase al delphi, pero lo tuve que dejar por que los estudios me absorbía mucho tiempo (sobretodo el viaje).
He decidido crear este otro bogg para tener mis apuntes siempre a mano en cualquier lugar del mundo, y no los quiero postear en mi otro bogo ya que esta mas orientado hacia la artesanía...
Suscribirse a:
Entradas (Atom)