C++ Builder

Easily Pass Values Between Delphi And Python In Your Windows Delphi/C++ Builder Apps

function TForm1.GetProperty(pSelf, Args : PPyObject) : PPyObject; cdecl; var   key : PAnsiChar; begin   with GetPythonEngine do     if PyArg_ParseTuple( args, ‘s:GetProperty’,@key ) > 0 then       begin         if key = ‘Title’ then           Result := VariantAsPyObject(cbTitle.Text)         else if key = ‘Name’ then           Result := VariantAsPyObject(edName.Text)         else if key = ‘Informatician’ then           Result := VariantAsPyObject(cbInformatician.Checked)         else if key = ‘PythonUser’ then           Result := VariantAsPyObject(cbPythonUser.Checked)         else if key = ‘Age’ then           Result := VariantAsPyObject(edAge.Text)         else if key = ‘Sex’ then           Result := VariantAsPyObject(rgSex.ItemIndex)         else           begin             PyErr_SetString (PyExc_AttributeError^, PAnsiChar(Format(‘Unknown property “%s”‘, [key])));             Result := nil;           end;       end     else       Result := nil; end;   function TForm1.SetProperty(pSelf, Args : PPyObject) : PPyObject; cdecl; var   key : PAnsiChar;   value : PPyObject; begin   with GetPythonEngine do     if PyArg_ParseTuple( args, ‘sO:SetProperty’,@key, @value ) > 0 then       begin         if key = ‘Title’ then           begin             cbTitle.Text := PyObjectAsVariant( value );             Result := ReturnNone;           end         else if key = ‘Name’ then           begin             edName.Text := PyObjectAsVariant( value );             Result := ReturnNone;           end         else if key = ‘Informatician’ then           begin             cbInformatician.Checked := PyObjectAsVariant( value );             Result := ReturnNone;           end         else if key = ‘PythonUser’ then           begin             cbPythonUser.Checked := PyObjectAsVariant( value );             Result := ReturnNone;           end         else if key = ‘Age’ then           begin             edAge.Text := PyObjectAsVariant( value );             Result := ReturnNone;           end         else if key = ‘Sex’ then           begin             rgSex.ItemIndex := PyObjectAsVariant( value );             Result := ReturnNone;           end         else           begin             PyErr_SetString (PyExc_AttributeError^, PAnsiChar(Format(‘Unknown property “%s”‘, [key])));             Result := nil;           end;       end     else       Result := nil; end;

Read More

Learn About Using Threads Inside Python For A Windows Delphi App In This Sample

We know Delphi supports Multithreading. Multithreading in Python can be achieved using Python Module Threading. However, In a use case like Delphi Application embedding Python(Python4Delphi) or CPython, the interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access Python objects. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines. Some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O. More Details here. This post will guide you on how to evaluate several python functions concurrently using Python4Delphi TPyDelphiThread. Python4Delphi Demo11 Sample App shows how to achieve concurrency(using more interpreters) inside Python. You can find the Demo11 source on GitHub. Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi. Components used in Python4Delphi Demo11 App: TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a singleton class. TPythonModule: It’s inherited from TMethodsContainer class allows creating modules by providing a name. You can use routines AddMethod, AddMethodWithKW to add a method of type PyCFunction. You can create events using the Events property. TPaintBox provides a canvas that applications can use for rendering an image. TPyDelphiThread: Inherited from TThread has properties like ThreadState( A pointer which stores Python last state), ThreadExecMode(emNewState, emNewInterpreter). Protected functions like ExecuteWithPython, Py_Begin_Allow_Threads, Py_End_Allow_Threads helps to run concurrently without thread conflicts. TMemo: A multiline text editing control, providing text scrolling. The text in the memo control can be edited as a whole or line by line. You can find the Python4Delphi Demo11 sample project from the extracted GitHub repository ..Python4DelphiDemosDemo11.dproj. Open this project in RAD Studio 10.4.1 and run the application. Implementation Details: PythonEngine component provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property. SortModule(TPythonModule) has initialized with 2 Delphi Methods SortModule_GetValue, SortModule_Swap which is imported in python script to perform sorting. 3 arrays are randomized with integer values, later get sorted. Three Sort functions were defined in the script such as BubbleSort, SelectionSort, and QuickSort which is evaluated by PyDelphiThread Instance’s ExecuteWithPython procedure. Note: Don’t override Execute Method, use always ExecuteWithPython. In this Sample, one interpreter Button uses an emNewState(single interpreter with new state and upon execution completion, restores the thread state) ThreadExecMode and three interpreter button use an emNewInterpreter (same as a new state but with new interpreter fully initialized) ThreadExecMode to Execute. procedure TThreadSortForm.InitThreads(ThreadExecMode: TThreadExecMode; script: TStrings); begin RandomizeArrays; ThreadsRunning := 3; with GetPythonEngine do begin OwnThreadState := PyEval_SaveThread; with TSortThread.Create( ThreadExecMode, script, SortModule, ‘SortFunc1’, BubbleSortBox, BubbleSortArray) do OnTerminate := ThreadDone; with TSortThread.Create( ThreadExecMode, script, SortModule, ‘SortFunc2’, SelectionSortBox, SelectionSortArray) do OnTerminate := ThreadDone; with TSortThread.Create( ThreadExecMode, script, SortModule, ‘SortFunc3’, QuickSortBox, QuickSortArray) do OnTerminate := ThreadDone; end; StartBtn.Enabled := False; Start2Btn.Enabled := False; end; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 procedure TThreadSortForm.InitThreads(ThreadExecMode: TThreadExecMode; script: TStrings); begin   RandomizeArrays;   ThreadsRunning := 3;   with GetPythonEngine do   begin […]

Read More

Get A Visually Stunning FireMonkey App Settings Template For Free Via Embarcadero GetIt

In this FireMonkey App Settings template, you can find three different multi-device templates. And you can learn how to create and design FireMonkey user interfaces. Available on C++ Builder and Delphi Moreover, you can learn how to utilize several components together to make meaningful components. And applying different styles and creating frames to make fast and reliable user interfaces with FireMonkey. You can get these complete FireMonkey UI templates from GetIt Package Manager Be sure to check out another industry FireMonkey UI templates: Be sure to check out all the available sample applications here!

Read More

Useful UX Design Guidelines For Modernizing Your Delphi VCL And FireMonkey Applications In Windows 10

Its already late and time to modernize your Delphi/C++ Application with extensive Windows 10 support, as the support for Windows 7 ended on January 14, 2020. Rad Studio offers robust components and visually stunning styles to modernize your existing applications in Windows 10. This post will give overview some of the Windows 10 specific features introduced in RAD Studio. Features Overview: Quickly and Easily update VCL and FMX applications to Windows 10 with the Windows 10 Controls. Address common UI Paradigms on Windows 10. Range of UI controls specifically designed for windows 10. Built in windows 10 styles for both VCL and FireMonkey applications. Select custom styles for VCL and FireMonkey available for download in GetIt. VCL extensions for HI-DPI, 4k monitors Support. Rad Studio 10.3 includes PerMonitorV2, Multi Resolutions Image List support. Expanded WinRT API and Windows store support. Windows 10 uses Segoe as the Standard font. Some font guidelines which can make your application looks windows 10. Header – Segoe UI Light,46 pt. Sub Header – Segoe UI Light,34 pt. Title– Segoe UI Semi Light,24 pt. Subtitle – Segoe UI Normal,20 pt. Base – Segoe UI Semi Bold 15 pt. Body -Segoe UI Normal,15 pt. Caption -Segoe UI Normal,12 pt. Windows 10 VCL Controls : TSplitView : A container for other controls that can be opened and closed similar to the TMultiView in FireMonkey. When opened, TSplitView can be docked to the left or right edge of the form, or displayed on top of the client area of the form (overlayed). When closed, the TSplitView can be completely hidden (CloseStyle = svcCollapse), or a smaller portion of the split view can remain visible (CloseStyle = svcCompact). TRelativePanel : A container control that allows you to position child controls relative to the panel itself or relative to other child controls of this panel. For more information on how to use the relative panel, see Using the Relative Panel. TToggleSwitch : A clickable control that allows a user to toggle between an On state and an Off state. Flexible to change the caption of the state. TDatePicker and TTimePicker : Control to let users specify a date and time from a pop-up scrolling list of values. TCalenderView : Allows you to customize the look-and-feel of the control. It supports the selection of multiple dates and includes the Month, Year, Decade views. TCardpanel : Use the TCardPanel to manage a collection of cards. Each card is a container for other controls and only one card is active/visible at a time. TStackPanel : Use the TStackPanel to apply homogeneous alignment, margin, and padding settings to a series of controls inside a panel container. Windows 10 Styles For VCL and FireMonkey. You can apply styles to your application to have stunning look and feel. Some of the windows 10 specific styles were built in to the RAD studio. You can check by navigating to Project->Options->Application->Appearance->select some the styles and you can preview the styles as well. Alternatively you can get some VCL and FireMonkey Styles from Tools->Getit Package manger-> Under Styles category-> select the styles which you wish to apply to your application. You also have flexibility to create your own custom styles using the Tools-> BitMap Style Designer. Check the Video New UX Design Principles for RAD Studio Developers in Windows for Demonstration below. Check out the High DPI Styles and VCL Styling Per Control feature introduced in […]

Read More

Learn About Using IBM Watson And The Power Of AI In Delphi And C++Builder

Take your Delphi and C++Builder projects to the next level using the IBM Watson REST API, a collaborative environment with AI tools that you can use to deploy machine learning models and training data. In this webinar, you can learn how to use IBM Watson APIs to make AI applications with your Delphi or C++ Builder applications. Overview of this session: Delphi & C++ Builder Integration with Web and REST Services HTTP native client library SOAP clients REST clients BaaS clients Cloud API IBM Watson AI Services Visual Recognition Tone Analysis (Natural Language Classification) Watson Machine Learning What you can do with Watson APIs Speech to Text – Text to Speech NLP Knowledge Studio Visual Recognition Language Translator Language Classifier AI for IT Operations AI for Customer Service and more Infuse AI in your Delphi and C++ Builder applications to make more accurate predictions, automate processes, and decisions. Be sure to watch the whole session to learn the demos in action and learn best practices!

Read More

Learn C++ Event Handling In 5 Minutes

In this short tutorial, C++ Product Manager, David Millington, explains what event handlers are and how to use them in your C++ application development.  Overview The event is that something happens.  Event handler – a method that’s called when something happens or is attached to an event. Technical details: an object-method pointer, referring to both the method and object instance on which to call the method. And it can have any signature. Defining Event Handlers In an event receiver class, you define event handlers, which are methods with signatures for instance: return types, calling conventions, and arguments that match the event that they will handle. Firing Events To fire an event, simply call the method declared as an event in the event source class. If handlers have been hooked to the event, the handlers will be called. Be sure to check out other tutorials on C++ Builder here:

Read More

RAD Studio Roadmap November 2020

Embarcadero’s users understand the scalability and stability of C++ and Delphi, and depend on the decades of innovation those languages bring to development. Ninety of the Fortune 100 and an active community of more than three million users worldwide have relied on Embarcadero’s award-winning products over the past 30 years. Icons by Icons8.com. © 2020 EMBARCADERO INC. ALL RIGHTS RESERVED Legal

Read More

Learn To Build A Python GUI For Working with 2D Graphics And The Matplotlib Library In A Delphi Windows App

Drawing graphics programmatically is a very popular task these days. You can easily solve it using Matplotlib library with Python4Delphi (P4D). P4D is a free set of instruments that allows you to work with Python scripts, modules and types in Delphi. In this post, we will look at how to run Matplotlib library using Python for Delphi. With Delphi and C++Builder and Python4Delphi, you can build Python GUI apps for Windows using various Python libraries. Open project Demo1 to run the Python script in Python for Delphi. Use Memo1 for Python script and Memo2 for results. Click Execute button for running the script. Download Demo1 source from GitHub. If you run into a floating point division error when executing the code run MaskFPUExceptions(True); before you call ExecStrings. procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; Python Matplotlib library provides various tools for working with 2D graphics. With this library, you can create graphics, customize legends, style sheets, color schemes, and manipulate images. There are examples of code from the Matplotlib below. Draw a plot You can draw very simple plots with Mathplotlib. Or, if you want, you can change the shape and color of the points in the graphic in different ways. In the following example, we will draw the green triangular points using the argument ‘g^’  in function plot(). import matplotlib.pyplot as plt import numpy as np t = np.arange(0., 5., 0.2) plt.plot(t, ‘g^’) plt.show() import matplotlib.pyplot as plt import numpy as np t = np.arange(0., 5., 0.2) plt.plot(t, ‘g^’) plt.show() Stacked bar chart In this example, we show how to draw a stacked bar plot. We will use the function bar() twice. We need to pass to this function such parameters as labels, values of various categories that need to be displayed, names of labels. Finally, we will set such graphic parameters as title, y-label. import matplotlib.pyplot as plt labels = [1, 2, 3, 4, 5] cat1_means = [14, 39, 30, 19, 54] cat2_means = [43, 62, 52, 51, 29] width = 0.35 fig, ax = plt.subplots() ax.bar(labels, cat1_means, width, label=’Cat1′) ax.bar(labels, cat2_means, width, bottom=cat1_means, label=’Cat2′) ax.set_ylabel(‘Scores’) ax.set_title(‘Scores by product cutegories’) ax.legend() plt.show() import matplotlib.pyplot as plt labels = [1, 2, 3, 4, 5] cat1_means = [14, 39, 30, 19, 54] cat2_means = [43, 62, 52, 51, 29] width = 0.35 fig, ax = plt.subplots() ax.bar(labels, cat1_means, width, label=‘Cat1’) ax.bar(labels, cat2_means, width, bottom=cat1_means, label=‘Cat2’) ax.set_ylabel(‘Scores’) ax.set_title(‘Scores by product cutegories’) ax.legend() plt.show() Draw curves and fill the area In this example, we use the function plot() again to build a graphic of cos(x). Then we fill the area in green color between two curves using function fill_between(). Pass parameters x, y1 and y2 to determine the curve and exclude some horizontal regions from being filled using parameter where. import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.arange(0, 7 * np.pi, 0.1) y = np.cos(x) ax.plot(x, y, color=’black’) ax.fill_between(x, 0, 1, where=y > 0.75, color=’green’, alpha=0.5, transform=ax.get_xaxis_transform()) plt.show() import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.arange(0, 7 * np.pi, 0.1) y = np.cos(x) ax.plot(x, y, color=‘black’)   ax.fill_between(x, 0, 1, where=y > 0.75,                 color=‘green’, alpha=0.5, transform=ax.get_xaxis_transform()) plt.show() We got acquainted with some of the Matplotlib library’s features. Go here, […]

Read More

Learn To Build A Python GUI For Processing Images With Pillow Library In A Delphi Windows App

Are you looking for a simple way to process images programmatically? You can do it with Python for Delphi using Pillow library. Python for Delphi (P4D) is a free tool that allows you to execute Python scripts, create new Python modules and types in Delphi. This post will guide you on how to run Pillow library code using Python for Delphi. You can easily build Python GUI apps using your favorite Python libraries for Windows using Delphi and C++Builder and Python4Delphi. In order to run the Python script in Python for Delphi, open and run project Demo1. Then insert the script into lower Memo, click Execute button, and get the result in upper Memo. You can find the Demo1 source on GitHub. procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; procedure TForm1.Button1Click(Sender: TObject); begin   PythonEngine1.ExecStrings( Memo1.Lines ); end; With Pillow library, you can perform geometric and color transformations. It also allows to cut, copy part of the image and merge several images into one. Let’s take a look at some examples. Open, show, and get image properties First, open the image using function open(). You can get image properties such as format, size, type. from __future__ import print_function from PIL import Image im = Image.open(“test.jpg”) print(im.format, im.size, im.mode) im.show() from __future__ import print_function from PIL import Image im = Image.open(“test.jpg”) print(im.format, im.size, im.mode) im.show() Create thumbnails thumbnail() function allows you to create an image thumbnail. The input parameters of this function are the size of the image that you want to get in pixels. Use save() function to save the image in a specified directory. from __future__ import print_function from PIL import Image import os path = “test.JPG” im = Image.open(path) size = (250, 250) outfile = os.path.splitext(path)[0] + “.thumbnail” im.thumbnail(size) im.save(outfile, “JPG”) from __future__ import print_function from PIL import Image import os   path = “test.JPG” im = Image.open(path) size = (250, 250) outfile = os.path.splitext(path)[0] + “.thumbnail”   im.thumbnail(size) im.save(outfile, “JPG”) Geometrical transformations Function transpose() allows you to perform different geometrical transformations with the image. For example, you can rotate the image by a given angle or flip it horizontally and vertically. from __future__ import print_function from PIL import Image im = Image.open(“test.jpg”) box = (0, 0, 320, 426) region = im.crop(box) region = region.transpose(Image.ROTATE_180) region = region.transpose(Image.FLIP_LEFT_RIGHT) im.paste(region, box) im = im.rotate(45) im.save(“test2.jpg”) from __future__ import print_function from PIL import Image im = Image.open(“test.jpg”) box = (0, 0, 320, 426) region = im.crop(box) region = region.transpose(Image.ROTATE_180) region = region.transpose(Image.FLIP_LEFT_RIGHT) im.paste(region, box) im = im.rotate(45) im.save(“test2.jpg”) Change images colors Now let’s look at how to change image color. Function split() allows you to decompose the image into separate colors and work with each color separately. In the following example first, we split the image into separate parts by color. Then select the area where the green value is less than 150. At the next step, we increase the blue value by 0.5. In the end, we merge everything into a new image. source = im.split() R, G, B = 0, 1, 2 mask = source[G].point(lambda i: i source = im.split() R, G, B = 0, 1, 2 mask = source[G].point(lambda i: i 150 and 255) out = source[B].point(lambda i: i * 0.5) source[R].paste(out, None, mask) source[B].paste(out, None, mask) im = Image.merge(im.mode, source) Now you can make various modifications […]

Read More

Quickly Migrate and Modernize Your Delphi/C++ Apps Using FastReport With Windows High DPI Setup

Display panel manufacturers have packed an increasing number of pixels into each unit of physical space on their panels resulted in the dots per inch (DPI) of modern display panels. In the past, most displays had 96 pixels per linear inch of physical space (96 DPI); in 2017, displays with nearly 300 DPI or higher are readily available. Variety of monitors like SD, Full HD, 4K Ultra HD, 8K Ultra HD in the market. We have laptops, desktops with small screens, and without display scale factor/DPI changes it’s very hard to use it and this can be even more complicated when talking about Full HD, 4K Ultra HD, 8K Ultra HD. Our application should be able to handle them. You cannot be sure what every user prefers. Some common scenarios where the display scale factor/DPI changes are: Multiple-monitor setups where each display has a different scale factor and the application is moved from one display to another (such as a 4K and a 1080p display) Docking and undocking a high DPI laptop with a low-DPI external display (or vice versa) Connecting via Remote Desktop from a high DPI laptop/tablet to a low-DPI device (or vice versa) Making display-scale-factor settings change while applications are running Desktop applications must tell Windows if they support DPI scaling. By default, the system considers desktop applications DPI unaware and bitmap-stretches their windows. By setting one of the Unaware, System, Per-Monitor, and Per-MonitorV2. available DPI awareness modes, applications can explicitly tell Windows how they wish to handle DPI scaling. When updating a System DPI-aware application to become Per-MonitorV2 aware, the code which handles UI layout needs to be updated such that it is performed not only during application initialization but also whenever a DPI change notification (WM_DPICHANGED in the case of Win32) is received. Things to know on migrating your Delphi Application to High DPI ? Set the DPI awareness Mode in Project->Options->Application->Manifest-DPI Awareness and Select Per-MonitorV2. Use Sceen.PixelsPerInch-primaryDispaly DPI Use TVirtualImageList instead of TImageList. Check all custom draw for absolute positions Use Control.CurrentPPI to get Current PPI of Control Mixed Mode for dialogs(SetThreadDPIAwarenesscontext) Use Form events OnBeforeMonitorDPIChanged/OnAfterMonitorDPIChanged. Note: Ensure backward compatibility for your platform and Delphi version of your application. Some of the Delphi And FastReport High DPI Controls: TControl: procedure such as ScaleforPPI, ChangScale, ScaleControlsForPPI helps for High DPI change. TFrxBAseForm: procedure such as UpdateResources, UpdateFormPPI, ProcessPreferences, and Message WM_DPICHANGED helps for FastReport form DPI change. TFrxDPIAwareCustomControl: procedure such as DoPPIChanged, GetScale, and Message WM_DPICHANGED_AFTERPARENT helps for FastReport custom control DPI change. Check out the Video Fast Migration to Windows 10 High DPI, below for Demonstration. Check the latest RAD Studio 10.4.1 Features which includes VCL Style Changes for High DPI.

Read More