Problems while using gtk+3 and Css - css

I am using C language to create a GUI with GTK+3 and I want to make the style of the app with CSS. The problem is that the widget doesn't accept the style that I gave to them, unless I use the * selector in my CSS file. At first time I try to make a single CSS file for all the app using gtk_style_context_add_provider_for_screen() but that didn't work. So I tried to set the style widget by widget using a function :
void SetStyleWidget (GtkCssProvider *CssProvider, char *Path, GtkWidget *Widget)
{
gtk_css_provider_load_from_path (CssProvider, Path, NULL);
gtk_style_context_add_provider (gtk_widget_get_style_context(Widget), GTK_STYLE_PROVIDER(CssProvider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
gtk_style_context_save (gtk_widget_get_style_context(Widget));
}
This don't work either. I also see that it could be a priority problem but no matter what priority I add it doesn't work. Do someone got an answer to my problem?
Here's my c file and my css :
#include <stdlib.h>
#include <gtk/gtk.h>
#include <gmodule.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "RandFuncGTK.h"
int main(int argc, char **argv)
{
GtkWidget *pWindow;
GtkWidget *pBoxLevel0;
GtkWidget *pTitreImg;
GtkWidget *pBoiteTitreImage;
GtkWidget *pLabTest;
GtkCssProvider *CssProvider;
gtk_init(&argc, &argv);
CssProvider = gtk_css_provider_new ();
pWindow = CreateWindow(pWindow, "Test", 1000, 1000);
pBoxLevel0 = gtk_box_new(GTK_ORIENTATION_VERTICAL, 100);
gtk_container_add(GTK_CONTAINER(pWindow), pBoxLevel0);
pLabTest = gtk_label_new("Test");
SetStyleWidget(CssProvider, "css/labstyle.css", pLabTest);
gtk_container_add(GTK_CONTAINER(pBoxLevel0), pLabTest);
gtk_widget_show_all(pWindow);
g_signal_connect(G_OBJECT(pWindow), "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_main();
return EXIT_SUCCESS;
}
Here's my css file
GtkLabel {
color: blue;
}

GTK stopped using widget type names as CSS node names in version 3.18 or so, and from then on, you have to check the C class documentation to see what node names, classes, and so on are available to theme. In this case, it would be
label { [...] }
I also recommend loading the StyleContext to the Display, not individual widgets. So, basically, use a modern version of GTK (ideally latest point 3.24.x, but at least 3.22) and the documented CSS selectors, and you're good to go.
Once doing that, if you only want to affect individual widgets, then just add CSS classes to them and select on those classes:
gtk_style_context_add_class(my_label_style_context, "the-precious");
and then select in CSS on
label.the-precious { [...] }
or just
.the-precious { [...] }
A fuller example is available in this other answer.
That is better than adding StyleContexts to individual widgets because doing that tends not to work how users expect (in terms of inheritance and such).
You can also set CSS IDs on widgets (like #the-precious), but that is less often used and IMO not really needed in GTK and more of a faff to set up IMO.
Note that the default GTK theme, Adwaita, was refreshed during 3.24 - so if you want to theme your application against that, it's best to do so from the latest available version of 3.24 - and hope it doesn't change again in 3.x...

Related

Would that be possible to build a particular customized QPushButton?

I was trying to understand if there is a way to build a particular customized QPushButton?
What I am trying to achieve is the following layout and appearance:
The button is shown below, notice the red line (which meas that the button is not clicked). I am not sure how to achieve the red line. I think it could be widget? or a QProgressbar, that when is clicked goes/loads up to green..I am not sure because I don't have enough experience and have been trying to build it. However this seems to be a bit tough:
And below how it should look like right after the click happened (note the green line):
Despite my efforts, I found some useful sources that I could use to get me started: for example this source was great to understand how to start. I studied the fact that in order to achieve that, the button need to be subclassed, and that is great because it lays some sort of route.
Below the code I used:
custombutton.h
#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H
#include <QPushButton>
class CustomButton : public QPushButton
{
public:
CustomButton( const QString& text, QWidget* parent = 0 );
void writeText();
};
#endif // CUSTOMBUTTON_H
custombutton.cpp
#include "CustomButton.h"
#include "algorithm"
CustomButton::CustomButton( const QString& text, QWidget* parent )
: QPushButton( text, parent )
{
}
void CustomButton::writeText()
{
QString buttonText = text();
setText( buttonText );
}
main
#include <QApplication>
#include "CustomButton.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomButton w( "MyButton" );
w.show();
w.writeText();
a.exec();
return 0;
}
Another useful source I found is this one which also was useful.
The official documentation points to use the styles, but I am trying not to do that because I would like to solve the problem understanding what is the potential of subclassing with Qt.
Unless going in the style direction is the only possible way to solve this problem?
I would like to thank anyone in advance for sharing or pointing to a potential solution on how to do that.
You can set your button as checkable and then set a different icon for the 2 states.
In your case you'd have to set the red icon for the Normal mode and the green one for the Selected mode
Here's an example:
https://www.dropbox.com/s/x40byuyu2ph8m1y/CheckableButton.zip?dl=0
Here someone asked the same thing:
https://forum.qt.io/topic/72363/change-icon-of-pushbutton
Here you can read abouth the modes:
https://doc.qt.io/qt-5/qicon.html#Mode-enum
PS: Of course overriding QAbstractButton::paintEvent(QPaintEvent *event) is a viable option too

Increase QTabWidget tab size while using custom palette

My app uses a QTabWidget. I want the tabs to fill the entire length of the tab bar.
My app also uses a palette to set the colors of all widgets, forms, etc.
I found that I can set the tab size as intended like so:
ui->tabWidget->setStyleSheet(QString("QTabBar::tab { width: %1px; }").arg(ui->tabWidget->size().width()/ui->tabWidget->count()));
But this causes the tab widget and all of its children to ignore my palette.
How can I use my palette and also increase the tab size?
I tried to reproduce your described behavior, but I was not able to do so. I'm using Qt 5.13.0, maybe it is in older version. At first I also thought, that I reproduced your behavior, but then I recognized, that I just didn't fully understood the options in QPalette, which really has a lot of ColorGroups and ColorRoles with different meanings.
Try the following simple test runner in order to verify it with your Qt Version.
#include <QApplication>
#include <QTabWidget>
#include <QFrame>
#include <QHBoxLayout>
#include <QPushButton>
int main(int argc, char** args) {
QApplication app(argc, args);
auto p=app.palette();
p.setColor(QPalette::ColorGroup::Active, QPalette::ColorRole::Background, QColor("red"));
p.setColor(QPalette::ColorGroup::Active, QPalette::ColorRole::Foreground, QColor("blue"));
p.setColor(QPalette::ColorGroup::Active, QPalette::ColorRole::ButtonText, QColor("magenta"));
app.setPalette(p);
auto w= new QTabWidget;
auto f=new QFrame;
f->setLayout(new QHBoxLayout);
f->layout()->addWidget(new QPushButton("Test"));
w->addTab(f,"Tab1");
w->setStyleSheet(QString("QTabBar::tab { width: %1px; height: %1px }").arg(100));
w->show();
app.exec();
}

Styled top-level QPushButton widget does not render properly

I've successfully made a QPushButton the top-level widget/window of an application and am attempting to style the button like so:
#include <QPushButton>
#include <QApplication>
class MyButton : public QPushButton
{
public:
MyButton() : QPushButton( "Button" )
{
setFixedSize( 250 , 65 );
setStyleSheet( "border-radius: 10px;" ); // style
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyButton b;
b.setWindowFlags( Qt::FramelessWindowHint | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint );
b.setAttribute(Qt::WA_TranslucentBackground); // Fixes opaque BG
b.show();
return a.exec();
}
Unfortunately, as the following image shows, the button is no longer rendered properly when the style is applied. I'd appreciate help getting the button to render the style properly.
Edit
Following Kuber Obas answer, I'd appreciate help styling the edges of the widget, i.e. those that are outside the rounded corner, to transparent as shown below
In most native styles, the border is drawn with the rest of the button using native functionality and its elements cannot be replaced one-by-one. Once you introduce your own styling, the monolithic native styling is gone. So, you'll need to replace all of the functionality provided by the native style, including the border, the background gradient, etc. You will need to tweak it to "match" native style if you so need.
Here, you need to redefine the border completely: at the minimum provide the pen (border:). The radius only makes sense with the pen. You also need to redefine the background, if you care for one, redefine all of the button's state selectors, etc. You start with an unstyled button!
The screenshot below demonstrates it well. On the left you have a Mac-styled native button, on the right you have a button with just its border defined anew. It's obvious that the default state background should also be adjusted to match that of the platform in this case, and some margin needs to be added.
Qt doesn't really re-do modern native styles entirely from scratch, that's why you can't tweak their individual elements. It'd be too much work and a constantly moving target. It used to be done for the old Windows-95/NT style. Starting with the XP style, it was decided to let the platform APIs provide the visual style bitmaps. Similar thing presumably happens on OS X. That's also the reason why you can't use the fancier XP/Aqua/Mac Qt styles outside of their native platform: the relevant native APIs are not present and thus the style is disabled.
// https://github.com/KubaO/stackoverflown/tree/master/questions/styledbutton-20642553
#include <QPushButton>
#include <QHBoxLayout>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a{argc, argv};
QWidget w;
QHBoxLayout layout{&w};
QPushButton button1{"Default"};
button1.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
layout.addWidget(&button1);
QPushButton button2{"Styled"};
button2.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
button2.setStyleSheet(
"* { border: 2px solid #8f8f91; border-radius: 12px; background-color: #d02020; }"
"*:pressed { background-color: #f6f7fa; }");
layout.addWidget(&button2);
auto pal = w.palette();
pal.setBrush(QPalette::Background, Qt::darkBlue);
w.setPalette(pal);
w.show();
return a.exec();
}

QTextBrowser - how to identify image from mouse click position

I'm using a QTextBrowser to display rich text including a number of images, each of them specified with a HTML <img> tag and added as resources using QTextDocument::addResource().
What I'd like to be able to do is, in a context menu handler (i.e. with a mouse click position available), identify the image that the click was over. It's possible to tell whether the click is over an image, because cursorForPosition(event->pos()).block().text() returns a string starting with Unicode 0xFFFC. Unfortunately the same string is returned for every image in the view.
It's possible to get all of the formats in use with QTextDocument::allFormats(), identify which of those are image formats, and get their image resource name. Unfortunately there seems to be no way to get their actual display position or bounding rectangle.
From the documentation:
Inline images are represented by an object replacement character (0xFFFC in Unicode) which has an associated QTextImageFormat. The image format specifies a name with setName() that is used to locate the image.
You can use charFormat().toImageFormat().name() on the cursor to extract the image's URL. Below is a self-contained example. There are two noteworthy details:
The cursor will sometimes point one character prior to the image. Thus the workaround; it seems necessary for both Qt 4.8.5 and 5.1.1.
The pop-up menus should be shown asynchronously so as not to block the rest of the application. The example code provided in the documentation is a source of bad user experience and should be considered an evil abomination. All widgets can automatically delete themselves when they get closed, so the menus won't leak. A QPointer is used only to demonstrate this fact. It tracks the menu's lifetime and nulls itself when the menu deletes itself.
#include <QApplication>
#include <QTextBrowser>
#include <QImage>
#include <QPainter>
#include <QMenu>
#include <QContextMenuEvent>
#include <QTextBlock>
#include <QPointer>
#include <QDebug>
class Browser : public QTextBrowser
{
QPointer<QMenu> m_menu;
protected:
void contextMenuEvent(QContextMenuEvent *ev) {
Q_ASSERT(m_menu.isNull()); // make sure the menus aren't leaking
m_menu = createStandardContextMenu();
QTextCursor cur = cursorForPosition(ev->pos());
QTextCharFormat fmt = cur.charFormat();
qDebug() << "position in block" << cur.positionInBlock()
<< "object type" << cur.charFormat().objectType();
if (fmt.objectType() == QTextFormat::NoObject) {
// workaround, sometimes the cursor will point one object to the left of the image
cur.movePosition(QTextCursor::NextCharacter);
fmt = cur.charFormat();
}
if (fmt.isImageFormat()) {
QTextImageFormat ifmt = fmt.toImageFormat();
m_menu->addAction(QString("Image URL: %1").arg(ifmt.name()));
}
m_menu->move(ev->globalPos());
m_menu->setAttribute(Qt::WA_DeleteOnClose); // the menu won't leak
m_menu->show(); // show the menu asynchronously so as not to block the application
}
};
void addImage(QTextDocument * doc, const QString & url) {
QImage img(100, 100, QImage::Format_ARGB32_Premultiplied);
img.fill(Qt::white);
QPainter p(&img);
p.drawRect(0, 0, 99, 99);
p.drawText(img.rect(), url);
doc->addResource(QTextDocument::ImageResource, QUrl(url), img);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextDocument doc;
Browser browser;
doc.setHtml("<img src=\"data://image1\"/><br/><img src=\"data://image2\"/>");
addImage(&doc, "data://image1");
addImage(&doc, "data://image2");
browser.show();
browser.setDocument(&doc);
return a.exec();
}

How to find global position of text cursor?

I would like to execute a QMenu object at the position of text cursor in a QPlainTextEdit. My problem is that QTextCursor is only define by its position in the Text (index of the character).
How can I find global position of the QTextCursor? Should I use an other object than QTextCursor in order to find the position of the text cursor where I want to open my QMenu?
Thank you by advance.
I've never tried myself, but doesn't QPlainTextEdit::cursorRect() work? It should give you position of the cursor in viewport coordinates. You can then get the viewport using viewport() and map the local position to global using viewport()->mapToGlobal().
I have found similar query to your in some online forum and here's someone suggested the output as
Note: Reference from http://www.unix.com/unix-linux-applications/81388-read-position-mouse-cursor.html, Author of below posting is daggilli, registered user of UNIX online forums. Credit of below posting in its complete form goes to daggilli.
This is the complete code for a Qt application I threw together in about ten minutes (called crosshair) which displays the current mouse coordinates in a window. You might be able to pull enough out of it to be useful. This is Qt 3.1, but Qt 4 is not a great deal different. You will need the Qt development libraries, not just the runtimes. The code comprises two files, crosshair.h and crosshair.cpp.
crosshair.h:
Code:
#ifndef CROSSHAIR_H
#define CROSSHAIR_H
#include <qwidget.h>
#include <qstring.h>
#include <qlabel.h>
#include <qevent.h>
class Crosshair : public QLabel
{
Q_OBJECT
public:
Crosshair(QWidget *parent=0);
protected:
void mousePressEvent(QMouseEvent *);
private:
QTimer *timer;
private slots:
void timerfire();
};
#endif
crosshair.cpp:
Code:
#include <qapplication.h>
#include <qpushbutton.h>
#include <qtimer.h>
#include <qcursor.h>
#include <iostream>
#include "crosshair.h"
using namespace std;
int main(int argc,char **argv)
{
QApplication a(argc,argv);
Crosshair mousepos;
a.setMainWidget(&mousepos);
mousepos.show();
return a.exec();
}
Crosshair::Crosshair(QWidget *parent) : QLabel(parent)
{
setIndent(20);
resize(100,30);
move(1200,200);
setText("0,0");
timer=new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(timerfire()));
timer->start(50,false);
}
void Crosshair::mousePressEvent(QMouseEvent *)
{
qApp->quit();
}
void Crosshair::timerfire()
{
QPoint p=QCursor::pos();
this->setText(QString().sprintf("%d,%d",p.x(),p.y()));
}
To build this, put both files in a directory called crosshair. cd to that directory and type
Code:
qmake -project
qmake
make
This does nothing more complex than inherit from a QLabel, set a timer to run 20x a second, grab the current cursor coordinates and write them into the label's text. Clicking in the window closes it. I use it for fixing up alignment bugs in JavaScript when I'm laying out objects.
You could open a file in the Crosshair class's constructor to store your data, and use gettimeofday(2) to get a timestamp. Nothing says Qt has to run in GUI mode (you can tell it explicitly not to in the QApplication constructor).
Qt from Trolltech: http://doc.trolltech.com

Resources