Duplicate GtkWidget in C - c

I want to duplicate a GtkWidget loaded through GtkBuilder
My problem is that telling Gtk to pack it into the same vbox it's already in causes an error, and I don't know how to duplicate it. I imagine it involves messing with pointers and references which is probably why I'm missing the point.
static GtkWidget *my_widget(){
GtkBuilder *builder;
builder = gtk_builder_new ();
gtk_builder_add_from_file (builder, "widget.glade", NULL);
return GTK_WIDGET (gtk_builder_get_object (builder, "widget"));
}
int
main (int argc, char *argv[])
{
GtkBuilder *builder;
GtkWidget *window;
GtkWidget *widget;
gtk_init (&argc, &argv);
builder = gtk_builder_new ();
gtk_builder_add_from_file (builder, "userinterface.glade", NULL);
window = GTK_WIDGET (gtk_builder_get_object (builder, "mainwindow"));
gtk_builder_connect_signals (builder, NULL);
// Load widget into box
int i;
for (i=0; i<5; i++){
gtk_box_pack_start( GTK_BOX (gtk_builder_get_object (builder, "widget_vbox")),
my_widget(),
FALSE,
TRUE,
0);
if(i!=4){ // Don't add a seperator at the last loop
widget = gtk_hseparator_new();
gtk_box_pack_start( GTK_BOX (gtk_builder_get_object (builder, "solo_mission_vbox")),
widget,
FALSE,
TRUE,
0);
gtk_widget_show(widget);
}}}
This populates the box with the widget 5 times with seperators in between. The problem lies in that the program is opening and closing the same file 5 times over just to get put it in place.
How can I take the builder output and "Copy" it into 5 completely different instances? It probably involves something with a lot of *s and &s.

You can't "copy" widgets, no matter how many pointers you use. The way you are doing it in your example above is correct. One improvement is that you could move the widget into its own, smaller, builder file. If the widget is small, you might consider making your own widget class and constructing it manually, instead of from a builder file.
PS. If you want to program an application in C, you'd better learn not to be afraid of pointers!

Related

Create and save a file in GTK2 using C

I'm following the instructions of the official Raspberry Pi book called An introduction to C & GUI Programming (link).
It uses GTK2 to create a gui in C.
I encountered some problems trying the code that should save a file. Here the code of the book (same I used):
#include <gtk/gtk.h>
static void save_file (GtkWidget *btn, gpointer ptr)
{
GtkWidget *sch = gtk_file_chooser_dialog_new ("Save file", GTK_WINDOW (ptr), GTK_FILE_CHOOSER_ACTION_SAVE, "Cancel", 0, "OK", 1, NULL);
if (gtk_dialog_run (GTK_DIALOG (sch)) == 1)
{
printf ("%s selected\n", gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (sch)));
}
gtk_widget_destroy (sch);
}
void end_program (GtkWidget *wid, gpointer ptr)
{
gtk_main_quit ();
}
int main (int argc, char * argv[])
{
gtk_init (&argc, &argv);
GtkWidget *win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
GtkWidget *btn = gtk_button_new_with_label ("Close window");
g_signal_connect (btn, "clicked", G_CALLBACK (end_program), NULL);
g_signal_connect (win, "delete_event", G_CALLBACK (end_program), NULL);
GtkWidget *vbox = gtk_vbox_new (FALSE, 5);
gtk_container_add (GTK_CONTAINER (win), box);
GtkWidget *fc_btn = gtk_button_new_with_label ("Save file");
g_signal_connect (fc_btn, "clicked", G_CALLBACK (save_file), win);
gtk_box_pack_start (GTK_BOX (vbox), fc_btn, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (vbox), btn, TRUE, TRUE, 0);
gtk_widget_show_all (win);
gtk_main ();
return 0;
}
The books says that this program should open a window with a button that, if clicked, opens a new window where I can insert the name of the file and with OK I should be able to save it.
The resulting file path is printed correctly inside the terminal.
If I enter inside the path where I saved the file, the file doesn't exist! It's not hidded neither saved with a different name.
Is there something missing in this piece of code?
I left you a comment above. As noted, I reviewed the sample code in the PDF version of the book in your link. The purpose of that code is to present a file chooser dialog widget and confirm the name of the file you either select or type in by printing the full path in the console. The program, as is, has no mechanism for actually writing a file out to your storage medium. So that is why you do not see a file when you view the folder on your system. If you want as a minimum, a file actually written, a little more code needs to be added. Just to give you one really simple example of what that might look like, I made a revision to the "save_file" function in your sample program as noted in the following code snippet.
static void save_file (GtkWidget *btn, gpointer ptr)
{
GtkWidget *sch = gtk_file_chooser_dialog_new ("Save file", GTK_WINDOW (ptr), GTK_FILE_CHOOSER_ACTION_SAVE, "Cancel", 0, "OK", 1, NULL);
if (gtk_dialog_run (GTK_DIALOG (sch)) == 1)
{
printf ("%s selected\n", gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (sch)));
char cmd[1024];
strcpy(cmd, "touch ");
strcat(cmd, gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (sch)));
system(cmd);
}
gtk_widget_destroy (sch);
}
FYI, I built this revised program on a Linux system using the "touch" command which will either update an existing file's timestamp or create a new empty file and the "system" command which allows one to execute a program as though one was using a terminal. You mentioned a Raspberry Pi system, which I believe uses Linux or a Linux like operating system, so these commands should work.
For further examples and tutorials, you might want to check out some videos out on the web. The following link is not a specific recommendation, but it was one of the first videos I found out on the web that walks through the various steps of C coding with GTK including references to the GTK file chooser dialog.
"https://www.youtube.com/watch?v=EdJVkr87LSk&list=PLMkSWKN9VsZH562FmV8sMvMu_sVZsYAt6"
You might want to review those videos to see if they might help you.
I hope that clarifies things for you.
Regards.

How to align a GtkWidget label in the center of its GtkWidget layout in C with GTK3?

I have the following code, and I'm struggling to align the label in the center
of its parent (layout), but nothing has worked for me:
int main(int argc, char ** argv){
GtkWidget *window;
GtkWidget *layout;
GtkWidget *label;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 1024, 600);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
layout = gtk_layout_new(NULL, NULL);
gtk_container_add(GTK_CONTAINER (window), layout);
label = gtk_label_new(NULL);
gtk_label_set_text(GTK_LABEL(label), "SOME TEXT");
gtk_layout_put(GTK_LAYOUT(layout), label, 0, 0);
// Here I'm trying to align my label to the center,
// but it doesn't work with any of the three functions
gtk_widget_set_halign(label, GTK_ALIGN_CENTER);
//gtk_label_set_xalign(GTK_LABEL(label), GTK_ALIGN_CENTER);
//gtk_misc_set_alignment(GTK_MISC(label), 0.5f, 0.5f);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
I have also tryied some other functions that I could find in the GENOME documentation and other SO questions but they are mostly deprecated, or also doesn't work. At this point, as I'm working with GTK3, the recommended way seems to be with:
gtk_widget_set_halign(label, GTK_ALIGN_CENTER);
But it is not working. The label is still at the position I put it with:
gtk_layout_put(GTK_LAYOUT(layout), label, 512, 300);
The code compiles without any errors or warnings.
GtkLayout, like its relative GtkFixed, is kind of a last-resort container that you use when none of the other containers will work for your purpose. It just puts widgets where you specify them. So, the horizontal alignment APIs will not work. With GtkLayout, you have to calculate the alignment yourself.
I would recommend using GtkGrid or one of the other, more full-featured containers.

GTK in C: Segmentation Fault when using key-release or key-press

For context, I'm trying to make a program that changes stylized label text in response to some physical inputs on a beaglebone black (eg. get a signal, if high/low, show this text). In lieu of those inputs, which I don't have access to right now, I decided to use key-release as a substitute.
I've been basing my code off of this combo-box tutorial, which changes label text based on the text of a combo-box selection. I've modified that code to use stylized text as in the code below.
#include <gtk/gtk.h>
void combo_selected(GtkWidget *widget, gpointer window) {
gchar *text = g_strjoin(NULL,"<span font='48' weight='bold' color='#DDDDDD'>",gtk_combo_box_get_active_text(GTK_COMBO_BOX(widget)),"</span>",NULL); //label text, uses pango markup
gtk_label_set_markup(GTK_LABEL(window), text);
g_free(text);
}
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *hbox;
GtkWidget *vbox;
GtkWidget *combo;
GtkWidget *label;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "GtkComboBox");
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_container_set_border_width(GTK_CONTAINER(window), 15);
gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
hbox = gtk_hbox_new(FALSE, 0);
vbox = gtk_vbox_new(FALSE, 15);
combo = gtk_combo_box_new_text();
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Ubuntu");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Arch");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Fedora");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Mint");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Gentoo");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Debian");
gtk_box_pack_start(GTK_BOX(vbox), combo, FALSE, FALSE, 0);
gchar *str = "<span font='48' weight='bold' color='#DDDDDD'>Not Initialized</span>"; //label text, uses pango markup
label = gtk_label_new(NULL);
gtk_label_set_markup(GTK_LABEL(label), str); //add pango str to label
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), vbox, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(window), hbox);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
g_signal_connect(G_OBJECT(combo), "changed",
G_CALLBACK(combo_selected), (gpointer) label);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
That works, however when attempting to use a key-release or key-press instead of the combo box options, I get a segmentation fault. Below is the further-modified code (with some things commented out).
#include <gtk/gtk.h>
#include <unistd.h>
#include <stdio.h>
void fpcheck(GtkWidget *window, gpointer lbl) {
gchar *text = "<span font='48' weight='bold' color='#DDDDDD'>Press index finger firmly on sensor.</span>";
gtk_label_set_markup(GTK_LABEL(lbl), text);
//sleep(2); //placeholder -> fp detection
//text = "<span font='48' weight='bold' color='#DDDDDD'>Fingerprint recognized!</span>";
//gtk_label_set_markup(GTK_LABEL(lbl), text);
g_free(text);
}
int main(int argc, char *argv[]) {
GtkWidget *window; //main window
GtkWidget *align; //alignment settings
GtkWidget *lbl; //text
GdkColor color = {0, 0x0, 0x0, 0x0}; //window color
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL); //init window
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); //window pos on screen
gtk_window_set_default_size(GTK_WINDOW(window), 800, 480); //window size
//gtk_window_set_resizable(GTK_WINDOW(window), FALSE); //user cant resize
gtk_window_set_title(GTK_WINDOW(window),"User Display"); //window title
gtk_widget_modify_bg(window, GTK_STATE_NORMAL, &color); //set color to window
align = gtk_alignment_new(.5,.5,0,0); //x,y alignment
lbl = gtk_label_new(NULL); //label init
gchar *str = "<span font='48' weight='bold' color='#DDDDDD'>Not Initialized</span>"; //label text, uses pango markup
gtk_container_add(GTK_CONTAINER(align), lbl); //add label to alignment
gtk_container_add(GTK_CONTAINER(window), align); //add label to window
gtk_label_set_markup(GTK_LABEL(lbl), str); //add pango str to label
g_signal_connect(G_OBJECT(window), "key-release-event", G_CALLBACK(fpcheck), (gpointer) lbl); //calls fpcheck to change label
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all(window); //build the window all at once
gtk_main();
return 0;
}
If I comment out the gtk_label_set_markup line and g_free(text) line in fpcheck, there's no error but it doesn't do anything, of course. From looking at other online resources, I think this error is being cause by trying to access the GTK_LABEL(lbl) because of the first argument in fpcheck being incorrect, but thats just a guess and I don't know what I'd put there instead. In the example, it's just "Widget," referring to the combo-box, I think, since it gets the text from the selected option.
On that note, I tried removing that argument, and now instead of a segmentation error, I get the following error without even pressing/releasing.
(test:6698): GLib-GObject-WARNING **: invalid cast from 'GtkWindow' to 'GtkLabel'
(test:6698): Gtk-CRITICAL **: IA__gtk_label_set_markup: assertion 'GTK_IS_LABEL (label)' failed
I did a few gdb backtraces, but none of them seem to be particularly helpful. If anyone wants 'em, I can post them.
Any ideas on the problems I'm having?
Thanks.
key-release-event handler has this signature
gboolean
user_function (GtkWidget *widget,
GdkEvent *event,
gpointer user_data)
Your fpcheck() needs to look like that.
It's easier to find problems like this early if you learn the habit of doing e.g. g_assert (GTK_IS_LABEL (user_data)) as the first thing in every handler where the userdata definitely always has to be a label.

Auto scrolling GtkScrolledWindow with GtkTextView wrapped in GtkBox

When I have GtkTextView in GtkScrolledWindow, it scrolls automatically when user appends new line at the bottom of the widget. When I put GtkTextView in GtkBox and then in GtkScrolledWindow I doesn't work. I need to put box between GtkTextView and scrollbar and I can't do that without placing whole thing in another box. Is there any way to preserve autoscrolling behaviour when using GtkBox inside GtkScrolledWindow?
There is code that ilustrates my problem:
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window),
gdk_screen_width()*0.5, gdk_screen_height()*0.5);
GtkWidget *main = gtk_box_new(0, 0);
gtk_container_add(GTK_CONTAINER(window), main);
/*/////////////////////////////////////////////////*/
/* IMPORTANT PART */
/* FIRST CASE (this one works correctly) */
GtkWidget *scrolled_window_first = gtk_scrolled_window_new(NULL, NULL);
GtkWidget *text_view_first = gtk_text_view_new();
gtk_container_add(GTK_CONTAINER(scrolled_window_first), text_view_first);
gtk_box_pack_start(GTK_BOX(main), scrolled_window_first, 1, 1, 0);
/* SECOND CASE (there is no auto scroll which I need) */
GtkWidget *scrolled_window_second = gtk_scrolled_window_new(NULL, NULL);
GtkWidget *text_view_second = gtk_text_view_new();
GtkWidget *box_from_second_example = gtk_box_new(0, 0);
GtkWidget *example_box_before_scroller = gtk_box_new(0,0);
GtkWidget *example_label = gtk_label_new("I need this box badly!");
gtk_box_pack_start(GTK_BOX(box_from_second_example), text_view_second, 1, 1, 0);
gtk_container_add(GTK_CONTAINER(scrolled_window_second), box_from_second_example);
gtk_container_add(GTK_CONTAINER(box_from_second_example), example_box_before_scroller);
gtk_box_pack_start(GTK_BOX(main), scrolled_window_second, 1, 1, 0);
/* END IMPORTANT PART */
/*/////////////////////////////////////////////////*/
gtk_container_add(GTK_CONTAINER(example_box_before_scroller), example_label);
g_signal_connect(GTK_WINDOW(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all(window);
gtk_main ();
return 0;
}
The problem is GtkTextView implements GtkScrollable but GtkBox does not. This is not a minor issue: if you want to go the GtkBox way you should put it inside a GtkViewport and add the scrollability stuff... quite some code that involves deep understanding of how the whole thing scrolls.
Anyway if you are lazy enough you could also note GtkTextview is a GtkContainer. In other words you could add widgets around the GtkTextview without the need to incomodate GtkBox. Not exactly what you were looking for but maybe good enough for your purposes:
#include <gtk/gtk.h>
gint main(gint argc, gchar **argv)
{
GtkWidget *window, *scrolled_window, *text_view, *label;
gtk_init(&argc, &argv);
text_view = gtk_text_view_new();
gtk_text_buffer_set_text(gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view)),
"1\n\n\n2\n\n\n3\n\n\n4\n\n\n5\n\n\n6\n\n\n7\n\n\n8", -1);
/* Use this to set the size you want to reserve on the right */
gtk_text_view_set_border_window_size(GTK_TEXT_VIEW(text_view),
GTK_TEXT_WINDOW_RIGHT,
130);
/* Add whatever you want instead of a GtkLabel */
gtk_text_view_add_child_in_window(GTK_TEXT_VIEW(text_view),
gtk_label_new("You badly need this"),
GTK_TEXT_WINDOW_RIGHT,
0, 0);
scrolled_window = gtk_scrolled_window_new(NULL, NULL);
gtk_container_add(GTK_CONTAINER(scrolled_window), text_view);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 320, 240);
gtk_container_add(GTK_CONTAINER(window), scrolled_window);
gtk_widget_show_all(window);
gtk_main ();
return 0;
}
Did you try to modify the GtkAdjustments the textview creates by default (GtkScrolledWindow implements the GtkScrollable afaik).
GtkAdjustment * gtk_scrollable_get_hadjustment (GtkScrollable *scrollable);
I think the best approach would be to detect insertions to the GtkTextBuffer (get the views buffer via
GtkTextBuffer * gtk_text_view_get_buffer (GtkTextView *text_view);
and hook a callback (which tests for \n) to its insert-text g_signal and use
void gtk_adjustment_set_value (GtkAdjustment *adjustment,
gdouble value);
to modify the scrolling height.
Note that this is untested and a simpler method might be around the corner.

Gtk change multiple labels on button click

How can i change multible label values on single button click.Normally on a button click signal connect we can give only one user data.
Example code
void show_loop(GtkWidget *widget, gpointer user_data)
{
char buf[5];
int no = TxBuf.plBuf[7];
sprintf(buf, "%d",no);
gtk_label_set_text(GTK_LABEL(user_data), buf);
}
ID_label=GTK_WIDGET (gtk_builder_get_object (builder, "label24"));
DLC_label=GTK_WIDGET (gtk_builder_get_object (builder, "label25"));
check = GTK_WIDGET (gtk_builder_get_object (builder, "button3"));
g_signal_connect (check, "clicked", G_CALLBACK (show_loop), DLC_label);
I want to change both the labels on single button click.
Typically you would define, allocate and fill a struct that contains all the widgets that may have to be changed dynamically in your initialization code:
typedef struct AppData {
GtkWidget *id_label;
GtkWidget *dlc_label;
} AppData;
...
AppData *app_data = g_new0 (AppData, 1);
app_data->id_label = GTK_WIDGET (gtk_builder_get_object (builder, "label24"));
app_data->dlc_label = GTK_WIDGET (gtk_builder_get_object (builder, "label25"));
The you use the app_data as userdata parameter and can access the widgets inside the signal handler as e.g. app_data->id_label.

Resources