Linux создание графических оболочек

How do you make linux GUI’s?

My main experience is with C && C++, so I’d prefer to remain with them. I don’t want to use anything like QT, GTK, or wxWidgets or any tool kits. I’d like to learn native programming and this sort of defeats the purpose. With that in mind I’d also like to avoid Java. I understand gnome and xfce and KDE and such are all Desktop Environments for Linux, and the base installed typically is X (Xorg). When coding for Linux, do you code for X, or for the desktop environment? Is there a standard Linux header for this (like win32 has windows.h) for Linux? or is it different coding methods for every desktop environment? any help is greatly appreciated.

I am so disappointed by these answers (I guess that’s expected here). Some people want to learn and experiment. People are gatekeeping obsessively because they «know better.» A couple of years ago I developed a GUI in C in a 32-bit MCU for use with a small resistive touch screen through a basic SPI enabled display driver. It had register calls to draw primitives — lines, rectangles, ovals, and I built an entire functional menu based GUI with some basic graphics on top of it. Don’t let these «experts» stop you from learning.

11 Answers 11

X is a hideous layer to program for and, despite your intent to avoid Java, QT or any of the excellent UI abstraction layers, you’ll be doing yourself a disservice by coding to that level. I’ve done it (a long time ago when Motif was in its infancy on the platform we were using) and I would not do it again if there was an easier way.

Your use of the phrase «native programming» confuses me a little. If you want to learn native programming, it’s to the APIs that you choose to call. Using similar reasoning, you shouldn’t be coding in C either, instead opting for assembler (or direct machine code) since C provides an abstraction to the hardware.

If you want to learn X programming, that’s fine. You’ll end up with a lot more control over your interface but almost everyone else will be out-performing you in terms of delivery of software. Myself, I’d prefer to code to a higher-level API that I can use on many platforms — it gives me both faster delivery times and more market potential.

You don’t build a house out of atoms, you build it out of bricks. My suggestion is to use the tools, that’s what they’re there for.

I’ve had to use motif directly (only because the wm we are using is developed in house) and it’s not easy. I’d rather use one of the freely available UI abstraction layers

Writing a UI in Xlib isn’t like writing a UI in plain Win32, it’s more like writing a UI in DirectDraw; it’s much more low-level than Win32

If you’re not willing to go through half a dozen abstraction layers, Linux development is not for you. 😉

Читайте также:  Install linux from flash

I don’t want to use anything like QT, GTK, or wxWidgets or any tool kits. I’d like to learn native programming and this sort of defeats the purpose.

No you don’t. Back in an early version of X11, like R1 or R2, I coded a complete «Hello, world» program in Xlib alone.

You don’t want to go there.

-1. Typical nonsense found in Q&A sites — whenever someone asks «how to do ABC?», someones replies «why do you want to do ABC?». Unless you understand how to code using Xlib, you will never be in a position to write Xlib yourself — potentially for a new OS kernel that has not been invented. Of course, if you are delivering software professionally under timelines, you will go with a well supported high level abstraction. But if you blindly trust modern day programmers, you will never ever learn how to build the primitives when the need arises.

Typical pedantic nonsense. He’s clearly new at this. If he wants to learn the internals, he can, but — again, having done this when there wasn’t much beyond Xlib — only a fool tries to do that just to learn how to write an X GUI.

@victor here it is gist.github.com/whosaysni/5733660 it’s not as ugly as it was 40 years ago, I think due to the Xutils.h

I guess you could write C code directly against Xlib, but you’d end up recreating all the functionality that GTK+ or QT provide that X doesn’t alone.

I understand that linux itself was originally just the console, and GUI’s are added by third party programs. But It feels weird using all these toolkits in Linux, it feels like to get a GUI you need to use «hacks» or beat around the bush so to speak.

@Mike, do you feel the «hacks» when you play DirectX games using NVidia’s drivers? They’re third-party software.

@Mike: in unix philosophy there is one tool for each job. Xlib is at a lower level than you expect, it enables you to display things. Buttons & stuff are in toolkits, so you have to choose one.

Unix (and by extension, Linux) doesn’t actually define anything to do with GUIs. X, which is commonly used, doesn’t define anything to do with widgets or styles or anything of that nature — it’s concerned mostly with drawing primitives and event handling. Essentially, if you wanted to write in pure X, you’d be defining the shape and behaviour of every element on screen. If you were crazy enough to abandon X, you’d be working at the graphics framebuffer level.

You’re better off using some toolkit — if you’re looking for light-weight, why not try FLTK?

GTK, QT and wx are toolkits that build on X to provide a friendlier API.

If you don’t use an existing toolkit you’ll need to write things at a very low level — directly handling mouse and keyboard events. If you want a button or a textbox you’ll have to write it yourself using the low level xlib primitives.

Читайте также:  How to check all users in linux

Before trying this you’re probably better off picking the toolkit of your preferred desktop environment and starting with that.

There is simply no such thing as «native» in this case. Windows and OS X just have an official option, while X does not.

The «native» interface for Linux & most other Unix-like OSs is Xlib, the lowest-level C API for X11.

GTK, Qt & others are all (so far as I know) implemented in terms of Xlib at their core. As others have said, Xlib gives you maximal control but you’ll have to work for it (and others may run circles around you in terms of delivering a product).

As a point of reference, I personally implemented a fairly feature-rich & modern (i.e. flowable) cross-platform (Win32 + X11) GUI library in C++. Total count is about 29 KLOC of C++, of which about 2500 lines each was required for the X11 & Win32 shimming. The rest is for platform-neutral Widget implementations. Unless you’re prepared to make a commitment like that, I strongly recommend going with one of the higher level libraries (Qt would probably be my choice, though I can’t stand the preprocessor approach).

BTW, a big plus for Xlib is its raw portability—any Unix box with a screen will have it, and it can be made to work on Windows & OS X as well.

I feel it necessary to counterpoint the unanimity of the other answers here. X11 is indeed low level. But to «truly» understand what’s going on, you should have some familiarity with how X11 works. Since all the toolkits work on top of X, you’re using it whether you like it or not. There is nice tutorial online somewhere that I’m too lazy to search for. It guides you through building a simple Hello World. To do it, you’ll have to learn how to create a window, request events, map the window, and process events in a loop. You could even go so far as to order some used books on Amazon. The O’Reilly vols 1 and 2 (for now get the cheapest editions, but nothing earlier than X11R4) are essential for reference and to get the full story of how the pieces work together. For learning, however, the best book is X Window Applications Programming by Eric Johnson and Kevin Reichard.

At some point along this journey, as everyone else says, you will find you’ve had enough. Two pages of code just to select a visual, and then you still have to populate a colormap before you can paint your custom bitmap. And then two days of rewriting and debugging to realize that it all does work; you just forgot to XFlush() !

The struggle is important, because you’ll appreciate the toolkits more once you find the one you like.

I would suggest lesstif/motif as well. It also builds on top of X and the learning curve is, in my opinion, isn’t as steep as GTK or Qt. The UI’s you build with it aren’t going to be as sophisticated as ones you could build with GTK or Qt though. More information can be found here.

Читайте также:  HTML E-mail

As others have mentioned you probably don’t want to X it’s a pain.

Why not choose one among, say, Qt, wxWidgets and GTK and learn its internals, rather than its API? I do not mean just for the sake of it, but with the aim of contributing to the parts you find most appealing. In this way you’d fulfill your goal and get to do something useful, for you and also for others. I think this would be more rewarding than assigning yourself the rather artificial task of building an application with what amount to the wrong tools.

oh yeah, there is such «native» things:

FBUI, svgalib, directfb, exa(kdrive), SDL, Allegro..+Wayland, although not mainstream.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.12.43529

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Создаем приложение используя GTK в Линуксе

Разрабатывать приложения в Линуксе можно с помощью фреймворка GTK. Эта библиотека предназначенная для построения графического интерфейса пользователя. GTK — это свободное программное обеспечение, которое распространяется по лицензии GNU LGPL, что позволяет создавать как бесплатные так и коммерческие приложения.

С документациею и описанием библиотеки, Вы можете ознакомиться по следующей ссылке: https://www.gtk.org

Перед написанием приложения необходимо подготовить среду разработки. Для этих целей буду использовать ОС Ubuntu 22.04. Так как приложение будет разрабатываться на языке программирования Си необходимо установить необходимые пакеты и компилятор.

Откройте терминал от имени пользователя root и введите следующую команду:

sudo apt-get install build-essential

Также нам необходимо установить пакеты GTK для разработки приложения. Вводим следующую команду в терминале:

sudo apt-get install -y libgtk-3-dev

Теперь все готово для написания первого приложения. Открываем любой текстовый редактор и пишем следующий код:

#include int main (int argc, char *argv[])

Этот код создает окно. Но прежде чем выполнить приложение, давайте разберемся немного с кодом.
#include — здесь мы подключаем библиотеку gtk. Без этой библиотеки не будет работать графическое окно и мы не сможем запустить приложение;
GtkWidget *window; — задаем имя/метку окна;
window = gtk_window_new(GTK_WINDOW_TOPLEVEL); — эта строка создает стандартное окно с рамкой;
gtk_widget_show(window); — отображаем окно на дисплее.

Теперь давайте запустим приложение. Я сохранил код приложения в файле ex1.c в домашней папки.
Открывает терминал и вводим следующие команды:

gcc ex1.c -o ex1 `pkg-config —cflags —libs gtk+-3.0

Теперь давайте улучшим код и создадим текстовую метку.

#include int main (int argc, char *argv[])

GtkWidget *label1; — задаем имя текстовой метки;
label1 = gtk_label_new(«Hello! My first Program»); — создаем текстовую метку;
gtk_container_add(GTK_CONTAINER(window), label1); — эта строка кода добавляет метку в контейнер;
gtk_widget_show(label1); — отображаем метку в окне.

Надеюсь эта публикация была полезная. Так как фреймворк GTK имеет очень много полезных и интересных функций, что не дает возможности объяснить все в одной публикации.

Источник

Оцените статью
Adblock
detector