I'm working on a Qt application (in C++). Without appyling any styles, my menu looks like this:
I'd like it to look like this:
How do I achieve this? Either using qss, or programmatically?
I already tried this, without success:
menu->addAction(tr("Add"), this, SLOT(CreateNewWaypoint()))->setIconVisibleInMenu(false);
Answers for both Qt4.8 and Qt5 are needed to get the full bounty!
One way to solve the problem is to use QProxyStyle:
customstyle.h
#ifndef CUSTOMSTYLE_H
#define CUSTOMSTYLE_H
#include <QProxyStyle>
#include <QStyleOptionMenuItem>
class CustomStyle : public QProxyStyle{
public:
using QProxyStyle::QProxyStyle;
void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *w) const override
{
if(element == QStyle::CE_MenuItem){
QStyleOptionMenuItem myMenuOption;
const QStyleOptionMenuItem *menuOption =
qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
if (menuOption) {
const int width = pixelMetric(PM_SmallIconSize)+6;
myMenuOption = *menuOption;
QRect r(myMenuOption.rect);
r.setLeft(-width);
myMenuOption.rect = r;
}
QProxyStyle::drawControl(element, &myMenuOption, p, w);
return;
}
QProxyStyle::drawControl(element, opt, p, w);
}
};
#endif // CUSTOMSTYLE_H
then you install it in the QApplication:
QApplication a(argc, argv);
QApplication::setStyle(new CustomStyle);
You can influence on how your menu appears by playing with its style sheet. With you example code you can do the following:
menu.setStyleSheet("QMenu::item {"
"padding: 2px 5px 2px 2px;"
"}"
"QMenu::item:selected {"
"background-color: rgb(0, 85, 127);"
"color: rgb(255, 255, 255);"
"}");
Note the padding property, which sets the offsets of your menu item rectangles.
I wanted to get rid of the icons in the standard context menu for a QPlainTextEdit.
Just using setIconVisibleInMenu(false) for all the actions in the QMenu still left the icon space as shown in the question.
I was only able to get rid of the icon space when I set the icon for the menu actions to a null icon.
Full example:
void CustomPlainTextEdit::contextMenuEvent(QContextMenuEvent *event)
{
QMenu *menu = createStandardContextMenu();
foreach (QAction *action, menu->actions()) {
action->setIcon(QIcon());
}
menu->exec(event->globalPos());
delete menu;
}
Related
In my program I am displaying a dialog window to provide information to the user. I am using the QT Label element to do this and I would like to make the text look more "organic" or carved in, like the title text of a window than simple black on gray. Does anyone have any suggestions? I am using QT Creator and coding in c++ for Linux.
here is an image of what I am trying to acomplish
I prepared an MCVE to demonstrate the options I suggested in my comments.
Changing style of QLabel is rather simple and straight forward.
Using the QStylePainter doesn't quite match what I actually expected. I left in the sample code what I got so far. (May be, somebody could leave a helpful hint.) I will investigate in this topic later and edit this answer as soon as I got some satisfying progress on this topic.
The sample code:
#include <QtWidgets>
class TitleBar: public QWidget {
private:
QStyleOptionTitleBar _option;
//QString _text;
public:
explicit TitleBar(
const QString &text = QString(), QWidget *pQParent = nullptr);
protected:
virtual QSize sizeHint() const;
virtual void resizeEvent(QResizeEvent *pQEvent);
virtual void paintEvent(QPaintEvent *pQEvent);
};
int main(int argc, char **argv)
{
qDebug() << "Qt Version: " << QT_VERSION_STR;
// main application
#undef qApp // undef macro qApp out of the way
QApplication qApp(argc, argv);
// setup of GUI
QWidget qWin;
QVBoxLayout qBox;
// a boring label
QLabel qLbl1(QString::fromUtf8("Rather boring"));
qLbl1.setAlignment(Qt::AlignCenter);
qBox.addWidget(&qLbl1);
// a label with frame
QLabel qLbl2(QString::fromUtf8("Label with Frame"));
qLbl2.setFrameStyle(QLabel::Panel | QLabel::Raised);
qLbl2.setLineWidth(2);
qLbl2.setAlignment(Qt::AlignCenter);
qBox.addWidget(&qLbl2);
// a label with rich-text
QLabel qLbl3(
QString::fromUtf8(
"<body bgcolor='#28f'>" // doesn't have the effect
"<font size='+2' color='#f8e' face='Old English Text MT'>"
"Label <i>with</i> <b>Rich-Text</b>"
"</font>"
"</body>")); // background is set by style-sheet instead
qLbl3.setTextFormat(Qt::RichText); // might be auto-detected...
qLbl3.setStyleSheet("QLabel { background-color: #28f; }");
qLbl3.setAlignment(Qt::AlignCenter);
qLbl3.show();
qBox.addWidget(&qLbl3);
// a home-brew title bar
TitleBar qTitle("A Home-Brew Title Bar");
qBox.addWidget(&qTitle);
// finish setup of GUI
qWin.setLayout(&qBox);
qWin.show();
// run application
return qApp.exec();
}
TitleBar::TitleBar(const QString &text, QWidget *pQParent):
QWidget(pQParent)
{
_option.initFrom(this);
_option.titleBarFlags = Qt::Window;
_option.text = text;
}
QSize TitleBar::sizeHint() const
{
#if 0 // does not provide the expected result
return _option.rect.size();
#elif 0 // does not provide the expected result
return style()->proxy()->subControlRect(QStyle::CC_TitleBar,
&_option, QStyle::SC_TitleBarLabel).size();
#else
return QSize(0,
style()->proxy()->pixelMetric(QStyle::PM_TitleBarHeight,
&_option, this));
#endif // 0
}
void TitleBar::resizeEvent(QResizeEvent *pQEvent)
{
_option.rect = QRect(_option.rect.topLeft(), pQEvent->size());
}
void TitleBar::paintEvent(QPaintEvent *pQEvent)
{
QPainter qPainter(this);
style()->proxy()->drawComplexControl(QStyle::CC_TitleBar,
&_option, &qPainter, this);
}
I compiled and tested it in VS2013 on Windows 10 (64 bit). Below a snapshot:
I am trying to create a QPushButton in my project such that the text shows on top of the custom button image or icon.
I tried the below methods:
imagePath = path;
QPixmap pixmap(imagePath);
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
button->setGeometry(0,0,height,width);
button->setStyleSheet(
"background-color: gray;"
"border: 1px solid black;"
"border-radius: "+QString::number(radius)+"px;"
"color: lightGray; "
"font-size: 25px;"
);
When I try to use the setText here, it shows the icon first and text on its right. I want the text to appear on top of the icon.
I also tried the below method I found online:
imagePath = path;
button->setGeometry(0,0,height,width);
button->setStyleSheet("background-image: url(:/images/images/2adjacentTracksButton.png));"
"background-position: center center");
This one is not accepting my url path, hence is not displaying the image I need on the button.
How can I solve this?
When it comes to manipulate button, you may want to do your own class, which will implement QAbstractButton. Something like this:
class MyButton : public QAbstractButton
{
Q_OBJECT
public:
static MyButton* createButton(QIcon icon, QWidget *parent);
~MyButton();
void setText(QString);
void setIcon(eIcon);
void setOrientation(Qt::Orientation);
protected :
MyButton(QWidget *parent);
// here, you can reimplement event like mousePressEvent or paintEvent
private :
QBoxLayout* m_ButtonLayout;
QLabel* m_IconLabel;
QIcon m_Icon;
QLabel* m_TextLabel;
}
In the .cpp :
MyButton::MyButton(QWidget *parent)
: QAbstractButton(parent)
{
m_ButtonLayout = new QBoxLayout(QBoxLayout::LeftToRight, this);
m_ButtonLayout->setAlignment(Qt::AlignCenter);
m_ButtonLayout->setContentsMargins(0, 0, 0, 0);
m_ButtonLayout->setSpacing(1);
m_IconLabel = new QLabel(this);
m_IconLabel->setAlignment(Qt::AlignCenter);
m_ButtonLayout->addWidget(m_IconLabel);
m_TextLabel = new QLabel(this);
m_TextLabel->setAlignment(Qt::AlignCenter);
m_ButtonLayout->addWidget(m_TextLabel);
//m_TextLabel->hide();
}
MyButton* MyButton::createButton(QIcon icon, QWidget *parent)
{
MyButton* pButton = new MyButton(parent);
pButton->setIcon(icon);
return pButton;
}
void MyButton::setText(QString text)
{
m_TextLabel->setVisible(!text.isEmpty());
m_TextLabel->setText(text);
QAbstractButton::setText(text);
}
void MyButton::setIcon(QIcon icon)
{
m_Icon = icon;
m_IconLabel->setVisible(true);
}
void MyButton::setOrientation(Qt::Orientation orientation)
{
if (orientation == Qt::Horizontal)
m_ButtonLayout->setDirection(QBoxLayout::LeftToRight);
else
m_ButtonLayout->setDirection(QBoxLayout::TopToBottom);
}
And now you can create your button with your icon by calling the static method:
MyButton* button = MyButton::createButton(myButtonIcon, this);
It is just a basic example I gave you, and I am not sure it will work (this is a thing I did some time ago) but you can give it a shot. Hope that helps !
In QtCreater I added a table to my project. in my code I am generating some data to output into the table. I want to add a QCheckbox into each row to allow the row to be selected. All the content of the table is aligned left, how do I make only these checkboxes in the first column of every row align to the center?
I'm adding the QCheckbox using:
ui->data_table->setCellWidget(rowCount,0, new QCheckBox);
Two thumbs up for Barry Mavin! You don't even have to subclass.
one line...
pCheckBox->setStyleSheet("margin-left:50%; margin-right:50%;");
done!!
I usually use a layout and a container widget for this. It is an ugly solution, but it works:
QWidget * w = new QWidget();
QHBoxLayout *l = new QHBoxLayout();
l->setAlignment( Qt::AlignCenter );
l->addWidget( <add your checkbox here> );
w->setLayout( l );
ui->data_table->setCellWidget(rowCount,0, w);
So basically you will have:
Table Cell -> Widget -> Layout -> Checkbox
you'll have to consider it if you will need to access the checkbox through the table.
This is an old post but in fact there is a much easier and lighter way of achieving this, just subclass QCheckBox and set the stylesheet to
margin-left:50%;
margin-right:50%;
It works for me, but my checkbox is not completely displayed.
To have a complete view of the widget, remove margins in layout :
l->setContentsMargins(0,0,0,0);
As stated in similar question around Stack Overflow, it's currently an open BUG:
https://bugreports.qt-project.org/browse/QTBUG-5368
can be center like this too using layout if want to add more customization
// Create a widget that will contain a checkbox
QWidget *checkBoxWidget = new QWidget();
QCheckBox *checkBox = new QCheckBox(); // We declare and initialize the checkbox
QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget
layoutCheckBox->addWidget(checkBox); // Set the checkbox in the layer
layoutCheckBox->setAlignment(Qt::AlignCenter); // Center the checkbox
layoutCheckBox->setContentsMargins(0,0,0,0); // Set the zero padding
ui->my_table_view->setCellWidget(row_number,column_number, checkBoxWidget); // set cell widget
OR simply add left right margins
checkBox->setStyleSheet("margin-left:50%; margin-right:50%;");
#if QT_VERSION < 0x046000
#include <QCommonStyle>
class MyStyle : public QCommonStyle {
public:
QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const {
switch(subElement) {
case QStyle::SE_CheckBoxIndicator: {
QRect r = QCommonStyle::subElementRect(subElement, option, widget);
r.setRect( (widget->width() - r.width())/2, r.top(), r.width(), r.height());
return QRect(r);
}
default: return QCommonStyle::subElementRect(subElement, option, widget);
}
}
};
#else
#include <QProxyStyle>
#include <QStyleFactory>
class MyStyle: public QProxyStyle {
public:
MyStyle():QProxyStyle(QStyleFactory::create("Fusion")) {}
QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const {
switch(subElement) {
case QStyle::SE_CheckBoxIndicator: {
QRect r = QProxyStyle::subElementRect(subElement, option, widget);
r.setRect( (widget->width() - r.width())/2, r.top(), r.width(), r.height());
return QRect(r);
}
default: return QProxyStyle::subElementRect(subElement, option, widget);
}
}
};
#endif
QCheckBox *box = new QCheckBox();
box->setStyle(new MyStyle());
With the following code I tried to render a red push button using QStyle.drawControl():
#include <QtCore/QtCore>
#include <QtGui/QtGui>
class Widget : public QWidget
{
virtual void paintEvent(QPaintEvent* event)
{
QStyleOptionButton opt;
opt.palette = QPalette(Qt::red);
opt.state = QStyle::State_Active | QStyle::State_Enabled;
opt.rect = QRect(50, 25, 100, 50);
QPainter painter(this);
style()->drawControl(QStyle::CE_PushButton, &opt, &painter);
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
Widget w;
w.resize(200, 100);
w.show();
return app.exec();
}
However I get the following result:
How do I render a red push button using QStyle.drawControl()?
I'm using Qt 4.8.1 and Visal Studio 2010 on Windows XP.
The buttons are drawn by the native style engine, so the palette might not be used at all (see that question from the FAQ).
You can use an actual button with a stylesheet that you pass as the last parameter to the own button's style drawControl function.
class Widget : public QWidget
{
// To allow the automatic deletion without parenting it
QScopedPointer<QPushButton> button;
public:
Widget() : button(new QPushButton) {
button->setStyleSheet("background-color: red");
}
virtual void paintEvent(QPaintEvent* event)
{
QStyleOptionButton opt;
opt.state = QStyle::State_Active | QStyle::State_Enabled;
opt.rect = QRect(50, 25, 100, 50);
QPainter painter(this);
button->style()->drawControl(QStyle::CE_PushButton, &opt, &painter,
button.data());
}
};
But you will loose the native style, so you'll have to fake it (bali182's answer might be useful for that part).
Or you can use the same button with colorize effect and call its render() function to paint it:
class Widget : public QWidget {
QScopedPointer<QPushButton> button;
public:
Widget() : button(new QPushButton) {
QGraphicsColorizeEffect *effect = new QGraphicsColorizeEffect(button.data());
effect->setColor(Qt::red);
button->setGraphicsEffect(effect);
}
virtual void paintEvent(QPaintEvent* event) {
button->setFixedSize(100, 50);
button->render(this, QPoint(50, 25));
}
};
What you are trying to do, seems overly complicated. If you just want a red button, why not use the setStyleSheet() method of the QPushButton? It takes a QString, and you can define your button similar to CSS. Here i created you a red button, similar to the XP ui buttons:
QPushButton
{
background: qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 #f4a3a3,stop: 1 #cc1212);
border-width: 1px;
border-color: #d91414;
border-style: solid;
padding: 5px;
padding-left:10px;
padding-right:10px;
border-radius: 3px;
color:#000;
}
QPushButton:hover
{
border-color: #e36666;
}
QPushButton:pressed
{
background:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop: 0 #de8383, stop: 1 #ad0C0C);
border-color: #d91414;
}
Now you just need to pass the code above as a string to your buttons setStyleSheet() method. If you want to create a button widget, what is red by default, then extend the QPushButton class, create a static QString field with the content above, and set the button as stylesheet in the constructor.
More easy to understand examples on stylesheets:
Stylesheet Examples
I have this little test-case which is supposed to show two widgets, with one overlapping the other completely. The one is translucent so the other widget should shine through it.
For that purpose, I set a style sheet on the one widget using a type-selector Menu (which is its class name). But instead of making the widget opaque by a factor of 200/255, it makes it completely translucent as if the type-selector doesn't apply at all to the menu object, so that I see no shine of blue anymore.
If I instead use the * selector, it works as expected. I tested the value of metaObject()->className(), which correctly reports Menu. Can anyone hint me to the error I have made please? This is a reduced testcase of a real program which shows a much more weird behavior, and I first want to make this reduced testcase work.
#include <QtGui/QApplication>
#include <QtGui/QWidget>
#include <QtGui/QLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QResizeEvent>
class Menu: public QWidget {
Q_OBJECT
public:
Menu(bool translucent, QWidget *p):QWidget(p) {
if(translucent) {
setStyleSheet("Menu { background-color: rgba(0, 0, 150, 200) }");
}
QLabel *label = new QLabel(
translucent ? "\n\nHello I'm translucent" : "I'm not translucent");
label->setStyleSheet("color: white; font-size: 20pt");
QLayout *mylayout = new QVBoxLayout;
setLayout(mylayout);
mylayout->addWidget(label);
}
};
class MyWindow : public QWidget {
public:
MyWindow() {
Menu *m1 = new Menu(false, this);
Menu *m2 = new Menu(true, this);
m1->lower();
m2->raise();
}
protected:
void resizeEvent(QResizeEvent *event) {
foreach(QWidget *w, findChildren<QWidget*>()) {
w->setGeometry(0, 0, width(), height());
}
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MyWindow w;
w.show();
app.exec();
}
When using stylesheets with QWidget subclasses, you are supposed to override paintEvent this way:
void Menu::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
See the stylesheet reference from Qt documentation.