Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to make Grid 'cell' editable #51

Closed
wellitecho opened this issue Apr 20, 2022 · 2 comments
Closed

how to make Grid 'cell' editable #51

wellitecho opened this issue Apr 20, 2022 · 2 comments

Comments

@wellitecho
Copy link

wellitecho commented Apr 20, 2022

I was trying to use grid feature to create a table-like widget, whose cells are editable.
My cell type is defined like:

#[derive(Debug, Clone)]
pub struct MyCell {
    row: usize,
    col: usize,
    value: String,
    state: text_input::State,
}

and my grid struct is like:

struct GridExample {
    cells: Vec<MyCell>,
    button_state: button::State,
    scrollable_state: scrollable::State,
}

However, whenever I tried to grid.insert() a TextInput into the grid in a for loop, the compiler complains that self.cells cannot be mutably borrowed more than once, since iced TextInput::new() method takes a mutable state, and that state arg originates from &mut self.cells.

So, what is the correct way to make the 'cell' editable?

Thanks in advance.

@Kaiden42
Copy link
Collaborator

Hello, based on the problem you are describing I'm assuming you are using a for loop like for i in range to then access your cells like cells.get_mut(i)? If you call get_mut on a vector you are borrowing the whole vec mutable as long as the mutable borrowing of the element lives. Therefore you cant borrow your vector twice using this approach. You will have to mutable borrow the vector once for the whole iteration like for element in cells.iter_mut(). Using iter_mut() you will get an iterator over mutable references on each element in the vector. If you need to know the index of your element, you can just enumerate it like for (i, element) in cells.iter_mut().enumerate().

@wellitecho
Copy link
Author

Thank you for your detailed answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants