In a QTableWidget, changing the text color of the selected row - qt

I'm using a QTableWidget to display several rows. Some of these rows should reflect an error and their text color is changed :
Rows reflecting that there is no error are displayed with a default color (black text on white background on my computer).
Rows reflecting that there is an error are displayed with a red text color (which is red text on white background on my computer).
This is all fine as long as there is no selection. As soon as a row is selected, no matter of the unselected text color, the text color becomes always white (on my computer) over a blue background.
This is something I would like to change to get the following :
When a row is selected, if the row is reflecting there is no error, I would like it to be displayed with white text on blue background (default behavior).
If the row is reflecting an error and is selected, I would like it to be displayed with red text on blue background.
So far I have only been able to change the selection color for the whole QTableWidget, which is not what I want !

Answering myself, here is what I ended up doing : a delegate.
This delegate will check the foreground color role of the item. If this foreground color is not the default WindowText color of the palette, that means a specific color is set and this specific color is used for the highlighted text color.
I'm not sure if this is very robust, but at least it is working fine on Windows.
class MyItemDelegate: public QItemDelegate
{
public:
MyItemDelegate(QObject* pParent = 0) : QItemDelegate(pParent)
{
}
void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const
{
QStyleOptionViewItem ViewOption(rOption);
QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>();
if (ItemForegroundColor.isValid())
{
if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))
{
ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);
}
}
QItemDelegate::paint(pPainter, ViewOption, rIndex);
}
};
Here is how to use it :
QTableWidget* pTable = new QTableWidget(...);
pTable->setItemDelegate(new MyItemDelegate(this));

What you'll want to do is connect the selectionChanged() signal emitted by the QTableWidget's QItemSelectionModel to a slot, say OnTableSelectionChanged(). In your slot, you could then use QStyleSheets to set the selection colours as follows:
if (noError)
{
pTable->setStyleSheet("QTableView {selection-background-color: #000000; selection-color: #FFFFFF;}");
}
else
{
pTable->setStyleSheet("QTableView {selection-background-color: #FF0000; selection-color: #0000FF;}");
}

It looks ok, but you might want to look at the documentation of QStyleOption it can tell you wether the item drawn is selected or not, you don't have to look at the draw color to do that. I would probably give the model class a user role that returns whether the data is valid or not and then make the color decision based on that. I.e. rIndex.data(ValidRole) would return wether the data at this index is valid or not.
I don't know if you tried overriding data for the BackgroundRole and returning a custom color, Qt might do the right thing if you change the color there

You could, of course, inherit from the table widget and override the paint event, but I don't think that is what you want to do.
Instead, should use the QAbstractItemDelegate functionality. You could either create one to always be used for error rows, and set the error rows to use that delegate, or make a general one that knows how to draw both types of rows. The second method is what I would recommend. Then, your delegate draws the rows appropriately, even for the selected row.

You could use e.g. a proxy model for this where you return a different color if you have an error for the specific modelindex;
QVariant MySortFilterProxyModel::data(const QModelIndex & index, int role = Qt::DisplayRole) {
// assuming error state and modelindex row match
if (role==Qt::BackgroundRole)
return Qt::red;
}

Related

How to replace down arrow with text in a combobox in JavaFX

I'm trying to remove the down arrow from a combobox. All the solutions I have found just make the arrow disappear, for example this one.
Is there a way to remove completely the space where the arrow appears and fill the box just with the text of the selected choice?
If you want to completely elimnate the arrow & arrow button space, you can try with the below custom ComboBox.
The below code is setting the arrow button and arrow nodes size to 0 and asking to rerender the comboBox. The null check is to let this changes apply only once.
public class MyComboBox<T> extends ComboBox<T>{
Region arrowBtn ;
#Override
protected void layoutChildren() {
super.layoutChildren();
if(arrowBtn==null){
arrowBtn= (Region)lookup(".arrow-button");
arrowBtn.setMaxSize(0,0);
arrowBtn.setMinSize(0,0);
arrowBtn.setPadding(new Insets(0));
Region arrow= (Region)lookup(".arrow");
arrow.setMaxSize(0,0);
arrow.setMinSize(0,0);
arrow.setPadding(new Insets(0));
// Call again the super method to relayout with the new bounds.
super.layoutChildren();
}
}
}
UPDATE :
Based on the suggestion of #kleopatra, we can get the same behaviour using css as well (without the need to create a new class for ComboBox).
.combo-box .arrow-button,
.combo-box .arrow{
-fx-max-width:0px;
-fx-min-width:0px;
-fx-padding:0px;
}
The below image will tell you the difference of a normal combox box and this custom combo box. The left one is the normal comboBox, you can see the list cell when inspecting with ScenicView. The right one is the custom one. The list cell is completely occupied suppressing the arrow space.

JavaFX change single style in CSS stylesheet

I've created a small text editor window that allows the user to change some basic properties of a text area included within the screen. Two of the options available to change the properties of the textArea are font color and font color fill, which are both handled by separate color pickers.
I ran into an issue when testing these buttons using the setStyle method that only one property could be saved at a time. Example, if text color was set to BLUE, and afterwards fill color was set to YELLOW, text color would not remain blue, but instead revert back to its default defined in the stylesheet (black).
To fix this problem, I have created the following method;
private void updateTheSyle()
{
this.textArea.setStyle("-fx-control-inner-background: " + toRgbString(this.colorPickerFill.getValue()) +
"; -fx-text-fill: " + toRgbString(this.colorPickerFont.getValue()) + ";");
}
The toRgbString() method is also called, this is simply passing the user input from the color picker into a string such that the setStyle method can pass the correct parameters to the stylesheet.
This solution does work, as it enables me to change both the fill and the font color without reverting back to default upon selection. However, my program includes more than just fill and font color, which will contribute to a far longer setStyle statement as these options are added.
TLDR: Is there a way to edit a single style included in a CSS stylesheet without affecting the other styles in a given class?
For your first question (longer setStyle statement), If we take into account that the style is defined by a String, and it takes a whole set of details to provide for a single Style, so why not use a List<String> :
List<String> example = new ArrayList<>();
String style = "";
//For example if you use 2 textField to get the (value) and (type):
example.add("-fx-"+textFieldType+":"+textFieldValue + "; ");
//To gather all the properties in a single string
for(String property: example){
style += example;
}
yourNode.setStyle(style);
I do not know if there is a better approach but it works, good luck !
Edit :
I think this tip answers your second question:
private void Update(String type,String newValue){
for(int i = 0; i < example.size(); i++){
if(example.get(i).contains(type)){
example.set(i, "-fx-"+type+":"+newValue + "; ");
//Here you add a (break;) to not alter the other similar styles !
}
}
//Here you use a loop to update the new elements changed
}
I hope this will help you solve your problem !

How to change (remove) selection/active color of QListWidget

In my QListWidget, there are some items that have non-default background color, I set them like so inside the custom QListWidget class:
item->setBackgroundColor(qcolor); // item is of type QListWidgetItem*
Those non-default colors that I set are distorted by the QListWidget's selection color. See an example:
Items three and four are supposed to be the same color, but they are not since the item four is selected, and thus the result color is a summation of original color and QListWidget's selection (active item?) color.
My question is how to edit or remove that selection color?
I tried inside my QListWidget (in special slot when I want to change the item's background color):
QPalette pal = this->palette();
pal.setColor(QPalette::Highlight, QColor(255,255,255,0));
this->setPalette(pal); // updated
But it did not produce any effect. what am I doing wrong? Is it a correct variable to set? Do I set it up inside QListWidget or inside its delegate?
Update: I tried using stylesheets as pointed by comment/answer, however, it will not be possible to use them for my application, because the items in my rows have 3 states (so I would need to use three colors). E.g., 3 states that correspond to three colors: pink for active, green for inactive and gray for the rest. When using stylesheets, I cannot set the custom property (let's say QListWidget::item[Inactive="true"]) to a single QListWidgetItem, but for the full QListWidget, and therefore it colors all the rows the same color.
Stylesheets were tried for similar problem here, and didn't work, therefore I make conclusion using stylesheets is not the way to go.
The background change method that I used originally works fine for my purpose, but I cannot figure out how to get rid of the default selection color (transparent light blue) which adds to the background color and produces the mixed color.
I think you'd be better served using the style sheets to do this. Here's an example
QListWidget::item
{
background: rgb(255,255,255);
}
QListWidget::item:selected
{
background: rgb(128,128,255);
}
::item indicates the individual items within the QListWidget, while :selected indicates the QListWidgetItems which are currently selected.
To then get the custom background on specific widgets, you could use custom style sheet properties. In your code, call something like this on the widget you want to apply a custom style on:
myList->setProperty( "Custom", "true" );
// Updates the style.
style->unpolish( myList );
style->polish( myList );
Then in your style sheet, define the style for your custom property like so.
QListWidget::item[Custom="true"]
{
background: rgb(128,255,128);
}
I found a suitable solution by using a delegate. So, there is no need to use QPalette; and for my problem the stylesheets will not work. This solution will also work when different rows (QListWidget or QTreeWidget) are needed to be colored in different colors, depending on some state.
The background color is set as described on the question:
item->setBackgroundColor(qcolor); // change color slot inside QListWidget class
In order to define rules how the widget is painted, I re-define the delegate:
class Delegate : public QStyledItemDelegate {};
Then I re-define Delegate's method paint(). There I define how to draw each row of my widget. More specifically, I only call custom drawing when the mouse hovering over an item, or that item is in selected state (those are the conditions when the row is selected by the light blue color which I want to avoid). The code looks like this:
void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if((option.state & QStyle::State_Selected) || (option.state & QStyle::State_MouseOver))
{
// get the color to paint with
QVariant var = index.model()->data(index, Qt::BackgroundRole);
// draw the row and its content
painter->fillRect(option.rect, var.value<QColor>());
painter->drawText(option.rect, index.model()->data(index, Qt::DisplayRole).toString());
}
else
QStyledItemDelegate::paint(painter, option, index);
// ...
}
Of course, do not forget to associate the QListWidget with Delegate:
listWidget->setItemDelegate(new Delegate());

Change color of purple tab text in Konsole CSS

When input comes in on a tab that is not active, the text for the tab changes to a purple color. What CSS selectors do I need to use to change this?
I am using a custom stylesheet in Konsole to change how the tabs look, but can't figure out how to change this one value. This page makes no mention of it.
I'm using Konsole 2.13.2(KDE 4.13.3) on Xubuntu 14.04(XFCE).
As of today, this tab-activity color appears to be set by
void TabbedViewContainer::setTabActivity(int index , bool activity)
{
const QPalette& palette = _tabBar->palette();
KColorScheme colorScheme(palette.currentColorGroup());
const QColor colorSchemeActive = colorScheme.foreground(KColorScheme::ActiveText).color();
const QColor normalColor = palette.text().color();
const QColor activityColor = KColorUtils::mix(normalColor, colorSchemeActive);
QColor color = activity ? activityColor : QColor();
if (color != _tabBar->tabTextColor(index))
_tabBar->setTabTextColor(index, color);
}
in konsole's src/ViewContainer.cpp and is therefore probably beyond the reach of a custom stylesheet configured in Konsole.
Note how KColorScheme::ActiveText is mixed with normalColor. You can have some influence over the color by changing the "Active Text" color in KDE System Settings -> Color -> Colors tab -> Active Text. Konsole has to restarted for the changes to take effect.

Resetting Qt Style Sheet

I've managed to style my QLineEdit to something like this:
alt text http://www.kimag.es/share/54278758.png
void Utilities::setFormErrorStyle(QLineEdit *lineEdit)
{
lineEdit->setStyleSheet(
"background-color: #FF8A8A;"
"background-image: url(:/resources/warning.png);"
"background-position: right center;"
"background-repeat: no-repeat;"
"");
}
I called the function using
Utilities *util = new Utilities;
util->setFormErrorStyle(lineNoStaf);
The flow should be something like this:
User open form
User fill data
User submit data
Got error
Use setFormErrorStyle()
User edit the text in the QLineEdit and the style disappear
This function should be reusable over and over again, but how can I connect QLineEdit signal such as textChanged() to a function in other class that will reset the Style Sheet and then disconnect the signal so that it won't be running continuously every time the text changed ?
Qt also allows dynamic properties in its stylesheet, that means you don't need to code your own class for every widget type in your form.
From http://qt-project.org/doc/qt-4.8/stylesheet-examples.html
Customizing Using Dynamic Properties
There are many situations where we need to present a form that has mandatory fields. To indicate to the user that the field is mandatory, one effective (albeit esthetically dubious) solution is to use yellow as the background color for those fields. It turns out this is very easy to implement using Qt Style Sheets. First, we would use the following application-wide style sheet:
*[mandatoryField="true"] { background-color: yellow }
This means that every widget whose mandatoryField Qt property is set to true would have a yellow background.
Then, for each mandatory field widget, we would simply create a mandatoryField property on the fly and set it to true. For example:
QLineEdit *nameEdit = new QLineEdit(this);
nameEdit->setProperty("mandatoryField", true);
QLineEdit *emailEdit = new QLineEdit(this);
emailEdit->setProperty("mandatoryField", true);
QSpinBox *ageSpinBox = new QSpinBox(this);
ageSpinBox->setProperty("mandatoryField", true);
Works also in Qt 4.3!
Allright, this is not compile but should work in principle, you should be able to change the look by calling editWidget->setProperty('isError',true) or editWidget->setError(false)
class ErrorTextEdit : QLineEdit
{
Q_OBJECT
QPROPERTY(bool isError, READ isError, WRITE setError);
public:
ErrorTextEdit(QWidget* parent) : QLineEdit(parent), m_isError(false)
{
m_styleSheet = "" // see below
setStyleSheet(m_styleSheet);
}
void setError(bool val)
{
if (val != m_isError)
{
m_isError = val;
setStyleSheet(m_styleSheet);
}
}
bool isError() {return m_isError;}
private:
QString m_styleSheet;
bool m_isError;
}
for the stylesheet
ErrorTextEdit[isError="false"]
{
optional ...
Style for textedit that is NOT an error
}
ErrorTextEdit[isError="true"]
{
background-color: #FF8A8A;
background-image: url(:/resources/warning.png);
background-position: right center;
background-repeat: no-repeat;
}
the term
[<property>="<value>"]
restricts the application of the stylesheet to instances of the class whose <property> has the appropriate <value> the only caveat is that the style is not changed when the property changes its' value, so the stylesheet has to be reapplied for the look of the widget to actually change, see Stylesheet Documentation -> Property Selector
This construction moves the stylesheet into the widget that uses it and makes switch internal to the widget, the widget changes in accordance to its state.
In general you have a couple of ways to handle invalid inputs in your form
a) observe every change and update the style appropriately, you should be able to use QValidator for that too, but that is a separate topic, using QValidator you will probably be able to completely internalize the state of a single QTextEdit and not have to deal with its validity from the outside
b) Do it in the submit loop that you have described above, whenever the user clicks on submit change the state of the correct and incorrect fields
it all depends the structure of your app and the view
See, the other idea is you need to override the paint evet of line edit and then set the background image and color.
here the implimentation is presetn here button, follow up the same to your line edit

Resources