4

I'm trying to figure out how can I replace an item_name from an ncurses menu. From the man pages, I can't find any set_item_name or something similar. Any ideas if there's a work-around for this?

e.g., replace "Choice 1" w/ "String 1" on KEY_ENTER

#include <curses.h> 
#include <menu.h>

char *choices[] = {
    "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit",
};

int main() {
    ITEM **my_items, *cur_item;
    int c, i;
    MENU *my_menu;

    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    my_items = (ITEM **) calloc(6, sizeof(ITEM * ));
    for (i = 0; i < 5; ++i)
        my_items[i] = new_item(choices[i], choices[i]);
    my_items[5] = (ITEM*) NULL;

    my_menu = new_menu((ITEM **) my_items);
    post_menu(my_menu);
    refresh();

    while ((c = getch()) != KEY_F(1)) {
        switch (c) {
        case KEY_ENTER:
            // e.g. replace "Choice 1" w/ "String 1"
            break;
        case KEY_DOWN:
            menu_driver(my_menu, REQ_DOWN_ITEM);
            break;
        case KEY_UP:
            menu_driver(my_menu, REQ_UP_ITEM);
            break;
        }
    }
    free_item(my_items[0]);
    free_item(my_items[1]);
    free_menu(my_menu);
    endwin();
}
user1024718
  • 573
  • 6
  • 18

2 Answers2

3

Yes, there is a workaround for the missing set_item_name() you can write set_item_name();

First, look at the include file menu.h, where you can find the structure definition for the ITEM structure. Looking there you see that you can write a function like:

void set_item_name (ITEM *itm, const char* name)
{   int len = strlen(name);
    char* n;    
    if (itm->name.str!=NULL) free((void*)(itm->name).str);
    n=strdup(name);
    itm->name.length=len;
    itm->name.str=n;
}

About the arguments:

  • itm is the pointer to the menu item you want to change

  • name is the string you want to use as menu name.

I used this routine to create a 'checkbox' item in a drop-down menu and it seems to work (tested on a linux debian 6.0 and libncurses5 (5.7)).

Coding Mash
  • 3,338
  • 5
  • 24
  • 45
1

Looks like calling set_menu_items() again is the expected method.

wallyk
  • 56,922
  • 16
  • 83
  • 148