Skip to main content
Ezgi
Associate III
March 12, 2021
Question

Accessing a class object from outside

  • March 12, 2021
  • 3 replies
  • 963 views

I created a basic project on the TouchGFX Designer and wrote a function in my own cpp file using touchgfx library. I want that when the button is clicked ,the function is called to ScreenView.cpp or ScreenViewBase.cpp from my own cpp file and change the color of the box.

This is my cpp file.

#include <touchgfx/Color.hpp>
#include <touchgfx/widgets/Box.hpp>
#include <gui/screen1_screen/Screen1View.hpp>
#include <gui/screen1_screen/Screen1Presenter.hpp>
 
ChangeColor::ChangeColor()
{
 Screen1View::box1;
 box1.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 168, 35));
 box1.invalidate();
}

This is the Screen1View.cpp where I want to call my function.

#include<gui/ChangeColor.hpp>
#include <touchgfx/Color.hpp>
 
Screen1View::Screen1View():
 buttonCallback(this, &Screen1View::buttonCallbackHandler)
{
 
}
 
void Screen1View::setupScreen()
{
 Screen1ViewBase::setupScreen();
 button1.setAction(buttonCallback);
 
}
 
void Screen1View::tearDownScreen()
{
 Screen1ViewBase::tearDownScreen();
}
void Screen1View::buttonCallbackHandler(const touchgfx::AbstractButton& src)
{
 if (&src == &button1)
 {
 //Interaction1
 //When button1 clicked execute C++ code
 //Execute C++ code
 
 ChangeColor();
 
 }
}

I can't access the box. I think that I need to access the Screen1Presenter. How can I access?

This topic has been closed for replies.

3 replies

Michael K
Senior III
March 12, 2021

Well, there's a few things wrong here:

  • You can't access the box because it is not a static member. Non-static members and functions need a object reference (e.g. myDog.bark() acts on myDog. Dog::bark() makes no sense because you aren't specifying which dog should bark.)
  • Your ChangeColor() has no return type? It's written like a constructor, which can't be invoked like a method. Does this code actually compile?

If you want to make this function in an external cpp file, something like this would probably work.

// changecolor.hpp
 
#include <touchgfx/widgets/Box.hpp>
 
class ChangeColor{
public:
 static void changeColor(touchgfx::Box& b);
};
 
// changecolor.cpp
#include "changecolor.hpp"
#include "touchgfx/Color.hpp"
 
void ChangeColor::changeColor(touchgfx::Box& b){
 b.setColor(...);
 b.invalidate();
}
 
// in Screen1View.cpp
  if (&src == &button1)
 {
 ChangeColor::changeColor(box1);
 }

Embedded UI/UX Consulting: cadenza.design
Ezgi
EzgiAuthor
Associate III
March 15, 2021

Thank you. It worked.

Michael K
Senior III
March 12, 2021

Also, this seems a bit like an XY problem - why do you want to call code in another file? Why not write it in the Screen1View.cpp file? What are you trying to accomplish?

Embedded UI/UX Consulting: cadenza.design