Tree_view in GTK3 not showing the cells output

I am trying to call a window in GTK that lists defined archives in the defined directory. I am using glade and C language to build the program, and i had sucessfully call the window made in Glade, but couldn't make the defined archives appear in the tree_view Widget. My program is as follows:

void listar_cadastro()
{
    //Variaveis do construtor GTK
    GtkBuilder *construtor = NULL;
    GtkWidget *janela_lista_cadastro = NULL;
    GtkWidget *box1_lista_cadastro = NULL;
    GtkWidget *label_lista_cadastro = NULL;
    //Variaveis da montagem da lista
    char nome[30];
    GtkWidget *tree_view;
    GtkListStore *list_store;
    GtkTreeIter iter;
    GtkTreeViewColumn *coluna;

    list_store = gtk_list_store_new(1, G_TYPE_STRING);


    DIR *diretorio;
    struct dirent *lsdiretorio;
    const char ponto[10] = ".cadastro";

    construtor = gtk_builder_new_from_file("lista_cadastro.glade");

    if(construtor==NULL)
    {
        printf("ERRO! Nao foi possivel carregar o arquivo lista_cadastro.glade!!\n");
        return;
    }

    janela_lista_cadastro = GTK_WIDGET(gtk_builder_get_object(construtor, "janela_lista_cadastro"));

    if(janela_lista_cadastro==NULL)
    {
        printf("ERRO! Nao foi possivel criar o widget janela_lista_cadastro!\n");
        return;
    }

    box1_lista_cadastro = GTK_WIDGET(gtk_builder_get_object(construtor, "box1_lista_cadastro"));

    if(box1_lista_cadastro==NULL)
    {
        printf("ERRO! Nao foi possivel criar o widget box1_lista_cadastro!\n");
        return;
    }

    label_lista_cadastro = GTK_WIDGET(gtk_builder_get_object(construtor, "label_lista_cadastro"));

    if(label_lista_cadastro==NULL)
    {
        printf("ERRO! Nao foi possivel criar o widget label_lista_cadastro!\n");
        return;
    }

    tree_view = GTK_WIDGET(gtk_builder_get_object(construtor, "tree_view_lista_cadastro"));

    if(tree_view==NULL)
    {
        printf("ERRO! Nao foi possivel criar o widget tree_view!\n");
        return;
    }

    printf("Listando todos os cadastros...\n");

        //abre o diretório em que se encontra o executável
        if((diretorio = opendir("./Cadastros"))==NULL)
        {
            printf("Erro! Nao foi possivel abrir a pasta dos cadastros!\n");
        }
        //lê todos os nomes de arquivos que se encontram na pasta aberta no diretório
        //este loop passa por todos os arquivos, até encontrar o final
        //o loop funciona da seguinte maneira: o sistema tenta ler o nome do arquivo, caso não consiga, corta o loop
        while ((lsdiretorio = readdir(diretorio)) != NULL)
        {
            //esta função imprime o nome do arquivo escolhido
            //a função strstr compara duas strings, e caso o texto de uma string esteja em outra, retorna um valor
            //neste caso, caso a o if encontre a string .cadastro em algum dos nomes dos arquivos, ele passa o comando para
            //imprimir o nome do arquivo
            if((strstr(lsdiretorio->d_name, ponto)!=NULL))
            {
                printf("----------------------------------------------------------\n");
                printf("%s\n", lsdiretorio->d_name);
                printf("----------------------------------------------------------\n");

                strcpy(nome, lsdiretorio->d_name);

                //Adiciona os cadastros encontrados na lista de visualizacao
                gtk_list_store_set(list_store, &iter, NULL, -1, nome, -1);

            }
        }

        tree_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(list_store));

        coluna = gtk_tree_view_column_new_with_attributes("Nome do Arquivo", gtk_cell_renderer_text_new(), "text", 0, "background", 1, NULL);

        gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), coluna);

        g_object_unref(list_store);

        closedir(diretorio);

        gtk_widget_show_all(janela_lista_cadastro);

    return;
}

Glade .xml code:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.40.0 -->
<interface>
  <requires lib="gtk+" version="3.24"/>
  <object class="GtkWindow" id="janela_lista_cadastro">
    <property name="visible">True</property>
    <property name="can-focus">True</property>
    <property name="has-focus">True</property>
    <property name="can-default">True</property>
    <property name="title" translatable="yes">Lista de Cadastros</property>
    <property name="default-width">400</property>
    <property name="default-height">400</property>
    <property name="urgency-hint">True</property>
    <child>
      <object class="GtkBox" id="box1_lista_cadastro">
        <property name="visible">True</property>
        <property name="can-focus">False</property>
        <property name="orientation">vertical</property>
        <property name="baseline-position">top</property>
        <child>
          <object class="GtkLabel" id="label_lista_cadastro">
            <property name="visible">True</property>
            <property name="can-focus">False</property>
            <property name="label" translatable="yes">Lista de Cadastros</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkTreeView" id="tree_view_lista_cadastro">
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <child internal-child="selection">
              <object class="GtkTreeSelection"/>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

I am trying to do a list_store to make the columns of the tree_view, but i can't find a good example of how it should be structured.

I know the program searchs and finds the correct archives, by the command line output. But i can't make the tree_view Widget work in this program, even thought the window is called right.

Upvotes: 1

Views: 39

Answers (1)

I was able to make the tree view work, with some notes: Afer creating the linked list with the data, set the model of the tree list based on the linked list

Package the column at the start with the text renderer

Set the attibutes of the tree view, declaring each type of object that will be displayed on each column

The code:

void listar_cadastro()
{
//Variaveis do construtor GTK
GtkBuilder *construtor = NULL;
GtkWidget *janela_lista_cadastro = NULL;
GtkWidget *box1_lista_cadastro = NULL;
GtkWidget *label_lista_cadastro = NULL;
//Variaveis da montagem da lista
char nome[30] = "\0";
GtkTreeView *tree_view;
GtkListStore *liststore1;
GtkTreeIter iter;
GtkTreeViewColumn *coluna;
GtkCellRenderer *renderer;
//Variaveis de busca de arquivos
DIR *diretorio;
struct dirent *lsdiretorio;
const char ponto[10] = ".cadastro";


//Bloco de construção do glade - todos os objetos sao carregados do arquivo
{
construtor = gtk_builder_new_from_file("lista_cadastro.glade");

if(construtor==NULL)
{
    printf("ERRO! Nao foi possivel carregar o arquivo lista_cadastro.glade!!\n");
    return;
}

liststore1 = GTK_LIST_STORE(gtk_builder_get_object(construtor, "liststore1"));

if(liststore1==NULL)
{
    printf("ERRO! Nao foi possivel carregar o arquivo lista_cadastro.glade!!\n");
}

liststore1 = gtk_list_store_new(1, G_TYPE_STRING);

coluna = GTK_TREE_VIEW_COLUMN(gtk_builder_get_object(construtor, "tree_view_column"));

if(coluna==NULL)
{
    printf("ERRO! Nao foi possivel carregar o arquivo lista_cadastro.glade!!\n");
}

janela_lista_cadastro = GTK_WIDGET(gtk_builder_get_object(construtor, "janela_lista_cadastro"));

if(janela_lista_cadastro==NULL)
{
    printf("ERRO! Nao foi possivel criar o widget janela_lista_cadastro!\n");
    return;
}

box1_lista_cadastro = GTK_WIDGET(gtk_builder_get_object(construtor, "box1_lista_cadastro"));

if(box1_lista_cadastro==NULL)
{
    printf("ERRO! Nao foi possivel criar o widget box1_lista_cadastro!\n");
    return;
}

label_lista_cadastro = GTK_WIDGET(gtk_builder_get_object(construtor, "label_lista_cadastro"));

if(label_lista_cadastro==NULL)
{
    printf("ERRO! Nao foi possivel criar o widget label_lista_cadastro!\n");
    return;
}

tree_view = GTK_TREE_VIEW(gtk_builder_get_object(construtor, "tree_view_lista_cadastro"));

if(tree_view==NULL)
{
    printf("ERRO! Nao foi possivel criar o widget tree_view!\n");
    return;
}
}

printf("Listando todos os cadastros...\n");

    //abre o diretório em que se encontra o executável
    if((diretorio = opendir("./Cadastros"))==NULL)
    {
        printf("Erro! Nao foi possivel abrir a pasta dos cadastros!\n");
    }
    //lê todos os nomes de arquivos que se encontram na pasta aberta no diretório
    //este loop passa por todos os arquivos, até encontrar o final
    //o loop funciona da seguinte maneira: o sistema tenta ler o nome do arquivo, caso não consiga, corta o loop
    while ((lsdiretorio = readdir(diretorio)) != NULL)
    {
        //esta função imprime o nome do arquivo escolhido
        //a função strstr compara duas strings, e caso o texto de uma string esteja em outra, retorna um valor
        //neste caso, caso a o if encontre a string .cadastro em algum dos nomes dos arquivos, ele passa o comando para
        //imprimir o nome do arquivo
        if((strstr(lsdiretorio->d_name, ponto)!=NULL))
        {
            printf("----------------------------------------------------------\n");
            printf("%s\n", lsdiretorio->d_name);
            printf("----------------------------------------------------------\n");

            //copia o nome do arquivo encontrada para ser repassado depois a lista de visualização
            strncpy(nome,lsdiretorio->d_name,30);

            //Adiciona os cadastros encontrados na lista de visualizacao
            gtk_list_store_append(liststore1, &iter);
            gtk_list_store_set(liststore1, &iter, 0, &nome, -1);
        }
    }

    //bloco de construção da visualização em árvore
    //define o modelo da arvore de acordo com a lista ligada ja pronta
    gtk_tree_view_set_model(GTK_TREE_VIEW(tree_view),GTK_TREE_MODEL(liststore1));

    //render de texto
    renderer = gtk_cell_renderer_text_new();

    //associa o render de texto com a coluna da visualização
    gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(coluna), renderer, TRUE);

    //define os atributos da coluna da visualização
    gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(coluna), renderer, "text", 0, NULL);

    g_object_unref(liststore1);

    closedir(diretorio);

    gtk_widget_show_all(janela_lista_cadastro);

    g_object_unref(janela_lista_cadastro);

return;
}

The new glade .XML

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.40.0 -->
<interface>
  <requires lib="gtk+" version="3.24"/>
  <object class="GtkListStore" id="liststore1"/>
  <object class="GtkWindow" id="janela_lista_cadastro">
    <property name="visible">True</property>
    <property name="can-focus">True</property>
    <property name="has-focus">True</property>
    <property name="can-default">True</property>
    <property name="title" translatable="yes">Lista de Cadastros</property>
    <property name="default-width">400</property>
    <property name="default-height">400</property>
    <property name="destroy-with-parent">True</property>
    <property name="urgency-hint">True</property>
    <child>
      <object class="GtkBox" id="box1_lista_cadastro">
        <property name="visible">True</property>
        <property name="can-focus">False</property>
        <property name="orientation">vertical</property>
        <property name="baseline-position">top</property>
        <child>
          <object class="GtkLabel" id="label_lista_cadastro">
            <property name="visible">True</property>
            <property name="can-focus">False</property>
            <property name="label" translatable="yes">Lista de             Cadastros</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkTreeView" id="tree_view_lista_cadastro">
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="margin-start">2</property>
            <property name="margin-end">2</property>
            <property name="margin-top">2</property>
            <property name="margin-bottom">2</property>
            <property name="model">liststore1</property>
            <property name="expander-column">tree_view_column</property>
            <property name="enable-grid-lines">vertical</property>
            <property name="enable-tree-lines">True</property>
            <child internal-child="selection">
              <object class="GtkTreeSelection"/>
            </child>
            <child>
              <object class="GtkTreeViewColumn" id="tree_view_column">
                <property name="title"     
 translatable="yes">Arquivos</property>
                <property name="expand">True</property>
              </object>
            </child>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
    </interface>

Upvotes: 0

Related Questions