1
General discussions / Problem with Setting fillColor from a Member Function
« on: December 08, 2023, 01:50:20 pm »
I have this Button class, which is just a text inside a rectange:
Button::Button(
std::string string ,
float x ,
float y ,
float width ,
float hight ,
sf::Color idleColor ,
sf::Color hoverColor )
{
width = width;
x = x;
y = y;
idleColor = idleColor;
hoverColor = hoverColor;
string = string;
//initializing font
//initializing size
//initializing position ...etc
}
//If button contains mouse, set fillColor to hoverColor. Else, set it to idleColor
void Button::update(sf::RenderWindow* window) {
if (rect.getGlobalBounds().contains(
sf::Mouse::getPosition(*window).x, sf::Mouse::getPosition(*window).y))
{
rect.setFillColor(hoverColor);
}
else
rect.setFillColor(idleColor);
}
And in main:
The problem is that the fill color doesn't appear. I just get black buttons.
class Button {
private:
sf::RectangleShape rect;
sf::Font font;
sf::Text text;
float width;
float hight;
float x;
float y;
sf::Color idleColor;
sf::Color hoverColor;
public:
Button(
std::string string ,
float x = 0 ,
float y = 0 ,
float width = 100.f ,
float hight = 100.f ,
sf::Color idleColor = sf::Color::Green ,
sf::Color hoverColor = sf::Color::Red );
private:
sf::RectangleShape rect;
sf::Font font;
sf::Text text;
float width;
float hight;
float x;
float y;
sf::Color idleColor;
sf::Color hoverColor;
public:
Button(
std::string string ,
float x = 0 ,
float y = 0 ,
float width = 100.f ,
float hight = 100.f ,
sf::Color idleColor = sf::Color::Green ,
sf::Color hoverColor = sf::Color::Red );
Button::Button(
std::string string ,
float x ,
float y ,
float width ,
float hight ,
sf::Color idleColor ,
sf::Color hoverColor )
{
width = width;
x = x;
y = y;
idleColor = idleColor;
hoverColor = hoverColor;
string = string;
//initializing font
//initializing size
//initializing position ...etc
}
//If button contains mouse, set fillColor to hoverColor. Else, set it to idleColor
void Button::update(sf::RenderWindow* window) {
if (rect.getGlobalBounds().contains(
sf::Mouse::getPosition(*window).x, sf::Mouse::getPosition(*window).y))
{
rect.setFillColor(hoverColor);
}
else
rect.setFillColor(idleColor);
}
And in main:
std::unordered_map<std::string, Button*> Buttons;
Buttons["start"] = new Button("Start" );
Buttons["settings"] = new Button("Settings", 0.f, 100.f);
Buttons["quit"] = new Button("Quit", 0.f, 200.f);
for (auto& it:Buttons) {
it.second->update(&window);
it.second->draw(&window);
}
Buttons["start"] = new Button("Start" );
Buttons["settings"] = new Button("Settings", 0.f, 100.f);
Buttons["quit"] = new Button("Quit", 0.f, 200.f);
for (auto& it:Buttons) {
it.second->update(&window);
it.second->draw(&window);
}
The problem is that the fill color doesn't appear. I just get black buttons.