Elegant way of getting if element is focused in function QGraphicsItem::shape() - qt

In a graphical qt application,
i can learn if my object that inherits from QGraphicsItem is focused in paint method:
Qt Code:
void MyQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
if (option->state & QStyle::State_HasFocus) {
//if focus some shape
} else {
//if no focus another shape
}
}
but i must click it and the shape must change whether it is focused or not.
how can i get if focused information in
Qt Code:
QPainterPath QGraphicsItem::shape() const
method in an appropriate way?
I think to declare a global variable but i do not like this idea.
thanks

Use QGraphicsItem::hasFocus() :
Returns true if this item is active, and it or its focus proxy has
keyboard input focus; otherwise, returns false.
Incidentally, if you want the shape to change when you focus the item, you will need to override focusInEvent() and focusOutEvent() and remember to call prepareGeometryChange() before the shape changes.

Related

QTreeView cell selected highlight resize

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;
}
};

Set different images for different checkboxes in a QTreeView

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.

Hide QLineEdit blinking cursor

I am working on QT v5.2
I need to hide the blinking cursor (caret) of QLineEdit permanently.
But at the same time, I want the QLineEdit to be editable (so readOnly and/or setting editable false is not an option for me).
I am already changing the Background color of the QLineEdit when it is in focus, so I will know which QLineEdit widget is getting edited.
For my requirement, cursor (the blinking text cursor) display should not be there.
I have tried styleSheets, but I can't get the cursor hidden ( {color:transparent; text-shadow:0px 0px 0px black;} )
Can someone please let me know how can I achieve this?
There is no standard way to do that, but you can use setReadOnly method which hides the cursor. When you call this method it disables processing of keys so you'll need to force it.
Inherit from QLineEdit and reimplement keyPressEvent.
LineEdit::LineEdit(QWidget* parent)
: QLineEdit(parent)
{
setReadOnly(true);
}
void LineEdit::keyPressEvent(QKeyEvent* e)
{
setReadOnly(false);
__super::keyPressEvent(e);
setReadOnly(true);
}
As a workaround you can create a single line QTextEdit and set the width of the cursor to zero by setCursorWidth.
For a single line QTextEdit you should subclass QTextEdit and do the following:
Disable word wrap.
Disable the scroll bars (AlwaysOff).
setTabChangesFocus(true).
Set the sizePolicy to (QSizePolicy::Expanding, QSizePolicy::Fixed)
Reimplement keyPressEvent() to ignore the event when Enter/Return is hit
Reimplement sizeHint to return size depending on the font.
The implementation is :
#include <QTextEdit>
#include <QKeyEvent>
#include <QStyleOption>
#include <QApplication>
class TextEdit : public QTextEdit
{
public:
TextEdit()
{
setTabChangesFocus(true);
setWordWrapMode(QTextOption::NoWrap);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setFixedHeight(sizeHint().height());
}
void keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
event->ignore();
else
QTextEdit::keyPressEvent(event);
}
QSize sizeHint() const
{
QFontMetrics fm(font());
int h = qMax(fm.height(), 14) + 4;
int w = fm.width(QLatin1Char('x')) * 17 + 4;
QStyleOptionFrameV2 opt;
opt.initFrom(this);
return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
expandedTo(QApplication::globalStrut()), this));
}
};
Now you can create an instance of TextEdit and set the cursor width to zero :
textEdit->setCursorWidth(0);
Most straight forward thing I found was stolen from this github repo:
https://github.com/igogo/qt5noblink/blob/master/qt5noblink.cpp
Basically you just want to disable the internal "blink timer" Qt thinks is somehow good UX (hint blinking cursors never were good UX and never will be - maybe try color or highlighting there eh design peeps).
So the code is pretty simple:
from PyQt5 import QtGui
app = QtGui.QApplication.instance()
app.setCursorFlashTime(0)
voilĂ .
Solution in python:
# somelibraries
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.setFocus() # this is what you need!!!
container = QWidget()
container.setLayout(self.layout)
# Set the central widget of the Window.
self.setCentralWidget(container)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
I ran into the same problem but setReadOnly is not a viable option because it alters the UI behavior in other places too.
Somewhere in a Qt-forum I found the following solution that actually solves the problem exactly where it occurs without having impact on other parts.
In the first step you need to derive from QProxyStyle and overwrite the pixelMetric member function:
class CustomLineEditProxyStyle : public QProxyStyle
{
public:
virtual int pixelMetric(PixelMetric metric, const QStyleOption* option = 0, const QWidget* widget = 0) const
{
if (metric == QStyle::PM_TextCursorWidth)
return 0;
return QProxyStyle::pixelMetric(metric, option, widget);
}
};
The custom function simply handles QStyle::PM_TextCursorWidth and forwards otherwise.
In your custom LineEdit class constructor you can then use the new Style like this:
m_pCustomLineEditStyle = new CustomLineEditProxyStyle();
setStyle(m_pCustomLineEditStyle);
And don't forget to delete it in the destructor since the ownership of the style is not transferred (see documentation). You can, of course, hand the style form outside to your LineEdit instance if you wish.
Don't get complicated:
In QtDesigner ,
1.Go the the lineEdit 's property tab
2.Change focusPolicy to ClickFocus
That's it...

Qt Color Picker Widget?

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.

how to implement mouseEnter and mouseLeave event in QWidget?

how to implement mouseEnter and mouseLeave event in QWidget?
if the mouseEnter to the QWidget then i need to set the Background color into Gray,
if the mouseLeave from the QWidget then i need to set the background color is white
i tried
void enterEvent(QEvent *);
void leaveEvent(QEvent *);
in the inside of the enter&leave event i am using bool varibale set true & false. and i am calling the QPainter event update();
the code below:
void Test::enterEvent(QEvent *)
{
_mouseMove=true;
update();
}
void Test::leaveEvent(QEvent *)
{
_mouseMove=false;
update();
}
void Test::paintEvent(QPaintEvent *)
{
QPainter painter;
painter.begin(&m_targetImage);
painter.setRenderHint(QPainter::Antialiasing);
if(_mouseMove){
painter.fillRect(QRect(0,0,width(),height()),Qt::white);}
else{
painter.fillRect(QRect(0,0,width(),height()),Qt::gray);}
painter.end();
QPainter p;
p.begin(this);
p.drawImage(0, 0, m_targetImage);
p.end();
}
i am getting following error when i am moving the mouse in the QWidget
QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setRenderHint: Painter must be active to set rendering hints
QPainter::end: Painter not active, aborted
Please help me to fix this. if any one having sample code please provide me....
QWidgets also support the underMouse method which could be used instead of the StyleOption or Attribute solution:
if(underMouse()){
painter.fillRect(QRect(0,0,width(),height()),Qt::white);}
else{
painter.fillRect(QRect(0,0,width(),height()),Qt::gray);}
Use the styles.
Most widget support the :hover pseudo state, set the backgroundcolor property for your widget in the style
test->setStyleSheet(":hover {background-color: #dddddd;}");
or do it through designer, which is even more convenient, if you need to do custom drawing do it. but you don't need to do it for anything that just changes basic widget looks.
First I would use a member to save the current background color instead of a boolean. This will simplify the paintEvent code:
painter.fillRect(QRect(...), m_backColor);
I guess the errors appears for the first QPainter. Why are you using a QPainter to fill the image? If the var is a QImage you can use the fill function by example and the call drawImage as you do. You have the same kind of function for QPixmap.
Another way:
Use QStyleOption.
QStyleOption sopt;
sopt.initFrom(this);
if(sopt.state & QStyle::State_MouseOver)
{
painter.fillRect(QRect(...), m_colorHover);
}
else
{
painter.fillRect(QRect(...), m_colorNotHover);
}
Don't need use extra variable, like _mouseMove

Resources