I have a QTabWidget with a background gradient and two problems.
How dow I remove the anoying outline around the active tab (see image)? I tried "outline: none" like with push buttons but it does not seem to have an effect.
How do I style disabled tabs? I tried :disabled and :!enabled but both do not work. // Edit: This works with :disabled but not with all properties. Seems like I tried the only not supported.
The qt documentation was no help. Google either. :-(
It seems that the focus rectangle is handled by the QStyle (not to be confused with style sheets) that is in use. You can write a QStyle subclass and apply that to your to your QTabWidget. The subclass should override the drawControl() method and do nothing if it is currently drawing the focus rectangle.
The subclass would look something like this:
NoFocusRectStyle.h
#ifndef NOFOCUSRECTSTYLE_H
#define NOFOCUSRECTSTYLE_H
#include <QWindowsVistaStyle> // or the QStyle subclass of your choice
class NoFocusRectStyle : public QWindowsVistaStyle
{
public:
NoFocusRectStyle();
protected:
void drawControl(ControlElement element, const QStyleOption *option,
QPainter *painter, const QWidget *widget = 0) const;
};
#endif // NOFOCUSRECTSTYLE_H
NoFocusRectStyle.cpp
#include "NoFocusStyle.h"
NoFocusRectStyle::NoFocusRectStyle()
{
}
void NoFocusRectStyle::drawControl(ControlElement element,
const QStyleOption *option, QPainter *painter,
const QWidget *widget) const
{
if(element == CE_FocusFrame)
return;
QWindowsVistaStyle::drawControl(element, option, painter, widget);
}
Somewhere in your form's intializer/constructor you would apply the custom style subclass to the tab widget:
ui->tabWidget->setStyle(new NoFocusRectStyle());
This should allow your style sheets to continue to work.
It would be nice if there was an easier way to do this but I couldn't find one :)
This thread is old but maybe this would help people.
If you don't need to use the focus, then you can just set it through your tab widget:
ui->tabWidget->setFocusPolicy(Qt::NoFocus);
Focus rectangle could be removed by adding snippet below to your style:
QWidget {
outline: 0;
}
It is not related directly to style of QTabWidget but works as you expect.
Related
Is there any way to customize focus rect size for QTreeView item? I have reviewed source code of paint() event of QStyledItemDelegate, and there is query for textRect inside them, but i not found the way to resize focus rect, it only paint a part of cell, containing text, i need to focus rect fill the entire cell rect. Any help?
cell focus rect example
The default selection highlight depends on the current app style. On Windows it's partial, which is how other Windows apps behave. With Fusion style (default on Linux) the selection highlight already covers the full item rectangle. Not sure on Mac.
Anyway, it's easily controlled with a style option which is set in the item delegate. All we need to do is set a flag, and luckily the style option init function is virtual. This is the same flag which is set by default for some styles. Try this item delegate:
class HighlightDelegate : public QStyledItemDelegate
{
public:
using QStyledItemDelegate::QStyledItemDelegate;
protected:
void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override
{
QStyledItemDelegate::initStyleOption(option, index);
option->showDecorationSelected = true;
}
};
I subclassed a QTreeView and I have two columns where there are checkboxes. I would like to set two different images: one for the first column, and another one for the second column. I know I can change the image in the stylesheet with:
QTreeView::indicator:checked{
image: url(:/checked);
}
QTreeView::indicator:unchecked{
image: url(:/unchecked);
}
but it will change all the checkboxes in the tree view. Is there a way to do it with the stylesheets, or do I need to use a delegate?
Short answer: Stylesheets can't do that (as far as I know). They are a pretty immature feature in Qt, and there seems to be no development on them either.
What you can do:
Stylesheets
You cannot assign properties to a column or an item and you cannot access the columns by index.
But you can use some of the pseudo-states selectors like :first, :middle and :last:
QTreeView::indicator:first:checked{
background: red;
}
QTreeView::indicator:middle:checked{
background: blue;
}
QTreeView::indicator:unchecked{
background: lightgray;
}
I used colors instead of images for the sake of simplicity.
Note however, that these pseudo-states are actual currently visible states, so if the user is allowed to reorder columns, the style of the column might change. For example if the user drags one of the :middlecolumns and drops it at the end, the box will not be blue anymore.
DecorationRole
You can fake it using Qt::DecorationRole.
To do so, you have to receive the mousePressEvent either by subclassing QTreeView or by installing an event filter. You can then change the icon (via Qt::DecorationRole + emit dataChanged()) when the user clicks in the area of the icon.
This does not work with the keyboard of course.
Custom ItemDelegate
Subclass QStyledItemDelegate and override paint(), just as you suggested.
Custom Style
If you are creating a heavily styled application, you probably have to create a custom Style sooner or later. Stylesheets just don't support some features.
To do so, subclass QProxyStyle, override drawPrimitive and handle the drawing if QStyle::PE_IndicatorViewItemCheck is passed. You will also receive a QStyleOptionViewItem of which has some useful properties like checkState, features (contains QStyleOptionViewItem::HasCheckIndicator if there is a checkbox), and of course index so you can determine what kind of checkbox you want to draw.
Edit: Appendix
Example Using a Custom QStyledItemDelegate
void MyItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyledItemDelegate::paint(painter, option, index);
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
const QWidget *widget = option.widget;
QStyle *style = widget ? widget->style() : QApplication::style();
QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &opt, widget);
drawCheckBox(painter, checkRect, opt.checkState, index);
}
void MyItemDelegate::drawCheckBox(QPainter * painter, const QRect & checkRect, Qt::CheckState checkState, const QModelIndex & index) const
{
if (checkState == Qt::Checked)
{
switch (index.column())
{
case 0:
painter->fillRect(checkRect, Qt::red);
break;
default:
painter->fillRect(checkRect, Qt::blue);
}
}
else
{
painter->fillRect(checkRect, Qt::lightGray);
}
}
This example is quick and easy. Simply paint over the checkbox drawn by QStyledItemDelegate. Requires you to fill the whole box however, otherwise the original will be visible.
You can try to use QStyledItemDelegate to draw anything but the checkbox, and draw the checkbox afterwards, but that is a little harder and will leave you with some minor drawing artifacts if you don't want to spend too much time on it.
Example Using a Custom QProxyStyle
void MyStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption * opt, QPainter * p, const QWidget * w) const
{
if (pe == QStyle::PE_IndicatorViewItemCheck)
{
const QStyleOptionViewItem * o = static_cast<const QStyleOptionViewItem *>(opt);
drawCheckBox(p, opt->rect, o->checkState, o->index);
return;
}
QProxyStyle::drawPrimitive(pe, opt, p, w);
}
The drawCheckBox() function is the same as in the first example.
As you can see, this way is much simpler, cleaner and has none of the drawbacks. You can apply the style globally, or only for a single widget.
When I change the font of my QComboBox comboBox->setFont(whateverQFont); it is applied on the dropdown menu as well (all the items), and it overrides the Qt::FontRole data I have set on my items with comboBox->setItemData(index, itemSpecificFont, Qt::FontRole);
I'd like to set a font on the QComboBox label only and leave the dropdown displayed as it was. Or even better : to have directly the same font as the selected item.
Is there an easy way to do that ?
Edit: Solution of Jasonhan works fine for an editable QComboBox (-> setting the font on the QLineEdit) but is not applicable for a regular QComboBox, as the QLabel is private.
Before starting implement a custom model you could try with QListView.
It just applies to the drop-down menu and you can change its font with the usual setFont function; the you have to apply it to your QComboBox thorugh routine setView.
Something like this (it's not Qt C++ code, I've skipped all arguments in function calls):
QComboBox *combobox = new QComboBox();
combobox->setFont();
...
QListView *listview = new QListView();
listview->setFont();
combobox->setView(listview);
After 2 years, I saw this question. I don't know whether you have found a better method or not. If not, following code may give you a hint.
QComboBox label as you said is actually a QLineEdit, so you just need to set this component's font, and it will solve your problem.
QComboBox *box = new QComboBox();
//add some list items to box
if (box->lineEdit())
box->lineEdit()->setFont(font);//font is your desirable font
Something that works for a non-editable QComboBox is to install a QProxyStyle that sets the font when a CE_ComboBoxLabel control element is drawn.
Here's an example that sets the label font to italic:
#include <QApplication>
#include <QProxyStyle>
#include <QPainter>
#include <QComboBox>
class MyProxyStyle : public QProxyStyle
{
public:
void drawControl(QStyle::ControlElement element, const QStyleOption *option,
QPainter *painter, const QWidget *widget = nullptr) const override
{
if (element == QStyle::CE_ComboBoxLabel)
{
auto fnt = painter->font();
fnt.setItalic(true);
painter->setFont(fnt);
}
QProxyStyle::drawControl(element, option, painter, widget);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setStyle(new MyProxyStyle);
QComboBox cb;
cb.addItem("Option 1");
cb.addItem("Option 2");
cb.addItem("Option 3");
cb.show();
app.exec();
}
I have a QDialog subclass that presents some options to the user for their selecting. One of these options is a color. I have seen the QColorDialog, and I need something much simpler, that is also a regular widget so I can add to my layout as part of my dialog. Does Qt offer anything like this or will I have to make my own? If the latter, what is the best strategy?
Have you looked at the QtColorPicker, part of Qt Solutions?
QtColorPicker provides a small widget in the form of a QComboBox with a customizable set of predefined colors for easy and fast access. Clicking the ... button will open the QColorDialog. It's licensed under LGPL so with dynamic linking and proper attribution it can be used in commercial software. Search for QtColorPicker and you'll find it. Here's a link to one site that hosts many of the Qt Solutions components:
https://github.com/pothosware/PothosFlow/tree/master/qtcolorpicker
There's a very easy way to implement that using a QPushButton to display the current color and pickup one when it is clicked:
Definition:
#include <QPushButton>
#include <QColor>
class SelectColorButton : public QPushButton
{
Q_OBJECT
public:
SelectColorButton( QWidget* parent );
void setColor( const QColor& color );
const QColor& getColor() const;
public slots:
void updateColor();
void changeColor();
private:
QColor color;
};
Implementation:
#include <QColorDialog>
SelectColorButton::SelectColorButton( QWidget* parent )
: QPushButton(parent)
{
connect( this, SIGNAL(clicked()), this, SLOT(changeColor()) );
}
void SelectColorButton::updateColor()
{
setStyleSheet( "background-color: " + color.name() );
}
void SelectColorButton::changeColor()
{
QColor newColor = QColorDialog::getColor(color, parentWidget());
if ( newColor != color )
{
setColor( newColor );
}
}
void SelectColorButton::setColor( const QColor& color )
{
this->color = color;
updateColor();
}
const QColor& SelectColorButton::getColor() const
{
return color;
}
Qt doesn't offer anything simpler than QColorDialog natively, but there are several color picking widgets as part of wwWidgets, a user made set of widgets for Qt (note that this is "wwWidgets" with a "w" and not "wxWidgets" with an "x").
I think QColorDialog is best suited for your application. If you want to go for something simpler, it will come with reduced functionality. I'm not aware of any standard widget in Qt offering such an option but you can try out the following:
QCombobox with each entry corresponding to a different color. You can maybe even have the colors of the names in their actual color.
One or more slider bars to adjust the hue, saturation, val or R,G,B components.
QLineEdit fields for individual R,G,B components. You can also have a signal / slot mechanism wherein once the user changes a color, the color shown to the user gets changed accordingly.
You can have '+' and '-' signs to increase / decrease the above color component values.
I hope the above gives you some ideas.
I have a QLabel with a 'StyledPanel, raised' frame.
It is clickable, by subclassing QLabel;
class InteractiveLabel(QtGui.QLabel):
def __init__(self, parent):
QtGui.QLabel.__init__(self, parent)
def mouseReleaseEvent(self, event):
self.emit(QtCore.SIGNAL('clicked()'))
However, a general opinion is that this 'Box' is not easily recognised as clickable.
In an effort toward usability, I'd like the 'Box' to show it is clickable when the mouse is hovered over it.
Obviously a reaction to a mouse hover is easily achieved by connecting the mouseHoverEvent.
However, the 'button indicator' must be natively inherited, since my Qt application allows the User to change the style (out of Windows XP, Windows 7, plastique, motif, cde).
This image shows the particular widget (bottom right corner) and the mouseHover aesthetics I desire in two different styles.
When a mouse is hovered over 'Box', I'd like it to respond like the combobox has in the top, middle.
(The 'response' is aesthetically native and occurs with all Qt buttons, except in 'CDE' and 'motif'styles.).
Is there a way to implement this with PyQt4?
(I suppose non-native solutions would involve QGradient and checking the native style, but that's yucky.)
UPDATE:
lol4t0's idea of a QLabel over a QPushButton.
Here's my pythonic implementation with signals working properly and all the appropriate button aesthetics.
The RichTextBox is the widget you would embed into the program.
from PyQt4 import QtCore, QtGui
class RichTextButton(QtGui.QPushButton):
def __init__(self, parent=None):
QtGui.QPushButton.__init__(self, parent)
self.UnitText = QtGui.QLabel(self)
self.UnitText.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.UnitText.setAlignment(QtCore.Qt.AlignCenter)
self.UnitText.setMouseTracking(False)
self.setLayout(QtGui.QVBoxLayout())
self.layout().setMargin(0)
self.layout().addWidget(self.UnitText)
Thanks!
Specs:
- python 2.7.2
- Windows 7
- PyQt4
Main idea
You can add QLabelabove QPushButton (make QLabel child of QPushButton) and show rich text in label, while clicks and decorations can be processed with QPushButton
Experiment
Well, I am a C++ programmer, but there is nothing complicated, I hope, you understand the code
Implementing main idea:
QLabel * label = new QLabel(pushButton);
label->setText("<strong>sss</strong>");
label->setAlignment(Qt::AlignCenter);
label->setMouseTracking(false);
pushButton->setLayout(new QVBoxLayout(pushButton));
pushButton->layout()->setMargin(0);
pushButton->layout()->addWidget(label);
And this almost works! The only one silly bug (or my global misunderstanding) is that when you press button with mouse and then release it, it remains pressed.
- So, it seems we need to reimplement mouseReleaseEvent in our label to fix always pressed issue:
I'm pretty sure, there is a bit more elegant solution, but I'm too lazy to find it now, so, I made following:
class TransperentLabel: public QLabel
{
public:
TransperentLabel(QWidget* parent):QLabel(parent) {}
protected:
void mouseReleaseEvent(QMouseEvent *ev)
{
/*
QApplication::sendEvent(parent(), ev); -- does not help :(
*/
static_cast<QPushButton*>(parent())->setDown(false);
static_cast<QPushButton*>(parent())->click(); //fixing click signal issues
}
};
As #Roku said, to fix that issue, we have to add
label->setTextInteractionFlags(Qt::NoTextInteraction);
#Lol4t0, i have some improvements for your method...
This is my header file:
#ifndef QLABELEDPUSHBUTTON_H
#define QLABELEDPUSHBUTTON_H
#include <QPushButton>
class QLabel;
class QLabeledPushButton : public QPushButton
{
Q_OBJECT
QLabel * m_label;
public:
QLabeledPushButton(QWidget * parent = 0);
QString text() const;
void setText(const QString & text);
protected:
void resizeEvent(QResizeEvent * event);
};
#endif // QLABELEDPUSHBUTTON_H
And there is my cpp file:
#include <QLabel>
#include <QVBoxLayout>
#include <QResizeEvent>
#include "QLabeledPushButton.h"
QLabeledPushButton::QLabeledPushButton(QWidget * parent)
: QPushButton(parent)
, m_label(new QLabel(this))
{
m_label->setWordWrap(true);
m_label->setMouseTracking(false);
m_label->setAlignment(Qt::AlignCenter);
m_label->setTextInteractionFlags(Qt::NoTextInteraction);
m_label->setGeometry(QRect(4, 4, width()-8, height()-8));
}
QString QLabeledPushButton::text() const
{
return m_label->text();
}
void QLabeledPushButton::setText(const QString & text)
{
m_label->setText(text);
}
void QLabeledPushButton::resizeEvent(QResizeEvent * event)
{
if (width()-8 < m_label->sizeHint().width())
setMinimumWidth(event->oldSize().width());
if (height()-8 < m_label->sizeHint().height())
setMinimumHeight(event->oldSize().height());
m_label->setGeometry(QRect(4, 4, width()-8, height()-8));
}
So text on QLabel is always visible. QPushButton can't be too small to hide part of text. I think this way is more comfortable to use...