[英]Creating a 2D GtkWidget array
我想創建一個GtkWidget類型的10x20數組。 我想使它們每個都成為一個GtkEventBox,在其中貼上標簽。
我應該如何創建和使用2D GtkWidget *數組?
到目前為止,這是我嘗試過的:
//global variable:
GtkWidget *labelPlate[ROWS][COLUMNS];
...
...
inside the function that creates the table and attaches the event boxes to it
//my table, where the EventBoxes will be attached to
GtkWidget *finalPlateTable = gtk_table_new (10, 20, TRUE);
int i, j;
for(i = 0; i<ROWS; i++){
for(j=0 ; j<COLUMNS; j++){
//Make a char with the current float and create a label with it.
char finalString[14];
sprintf(finalString, "%.2f", plate[i][j]);
GtkWidget *label = gtk_label_new(finalString);;
//Labels cannot have bg color, so attach each label to an event box
/*HERE I GET SEG FAULT*/
labelPlate[i][j]=gtk_event_box_new();
//adding the label to my eventbox
gtk_container_add(GTK_CONTAINER(labelPlate[i][j]), label);
//Add the corresponding bg color to each event box
GdkColor color;
switch(scalePlate[i][j]){
...
...
break;
}
//coloring the event box with the corresponding background
gtk_widget_modify_bg ( GTK_WIDGET(labelPlate[i][j]), GTK_STATE_NORMAL, &color);
//attach the event box to the appropriate location of my table
gtk_table_attach_defaults (GTK_TABLE (finalPlateTable), labelPlate[i][j], j, j+1, i, i+1);
//show them!
gtk_widget_show(label);
gtk_widget_realize(labelPlate[i][j]);
}
}
//adding the table to my vertical box, and show both of them
gtk_box_pack_start(GTK_BOX (verticalBox), finalPlateTable, TRUE, TRUE, 10);
gtk_widget_show (finalPlateTable);
gtk_widget_show (verticalBox);
我想指出的是,我對C還是很陌生,我不知道如何使用malloc
(但是我懷疑現在應該使用它)。
我找到了解決方案:
將數組初始化為:
GtkWidget **myarray;
myarray = g_new(GtkWidget *, ROWS*COLUMNS);
然后使用函數訪問特定的行和列:
int returnPosAt(int row, int column){
return row*COLUMNS+column;
}
因此,您可以致電
myarray[returnPosAt(i, j)]=gtk_event_box_new();
因此,實際上您有一個1D數組,通過調用該函數,您可以獲得2D位置(i,j)的對應1D pos。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.