How to change the font of the qcombobox label/header only? - qt

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

Related

Can you hide a QGroupBox frame but preserve it's content visible?

I have a QGroupBox. Depending on the context, it's title may be redundent (displayed in another place of the GUI), so I then need to make as if the QGroupBox was not here....but I must preserve it's content visible (so I don't want to call QGroupBox::hide())!
I need to do this dynamically at runtime and would like to avoid creating/destroying the QGroupBox + reparenting it's content....there must be an easier way to do this.
What I tried so far:
QGroupBox visible:
QGroupBox::setTitle("") removes the text.
QGroupBox::setFlat(true) makes the frame be a single line.
I end up with this:
Not too bad...but a line remains....is there a way to completely hide the QGroupBox frame but preserve it's content visible?
My option:
QGroupBox theBox;
theBox.setFlat(true);
//This removes the border from a QGroupBox named "theBox".
theBox.setStyleSheet("QGroupBox#theBox {border:0;}");
//This removes the border from the group box and all of its children
theBox.setStyleSheet("border:0;");
You can derive your own Group Box from the QGroupBox and reimplement the paintEvent() method. It should be very simple. Original QGroupBox::paintEvent() looks like this:
void QGroupBox::paintEvent(QPaintEvent *)
{
QStylePainter paint(this);
QStyleOptionGroupBox option;
initStyleOption(&option);
paint.drawComplexControl(QStyle::CC_GroupBox, option);
}
What you need to do is just to modify the style option right before the widget is painted:
void CMyGroupBox::paintEvent(QPaintEvent *)
{
QStylePainter paint(this);
QStyleOptionGroupBox option;
initStyleOption(&option);
// This should disable frame painting.
option.features = QStyleOptionFrame::None;
paint.drawComplexControl(QStyle::CC_GroupBox, option);
}
You can use QFrame + QGridLayout (or some more complex combination of layouts) + QSS instead of a QGroupBox.
Considering a QGroupBox only, a trivial solution via QSS could be:
static const char kSavedTitle[] = "_savedTitle";
void hideBoxFrame(QGroupBox * box) {
box->setProperty(kSavedTitle, box->title());
box->setTitle(QString());
box->setStyleSheet("border:none");
}
void showBoxFrame(QGroupBox * box) {
box->setTitle(box->property(kSavedTitle).toString());
box->setStyleSheet(QString());
}
Here's an example that does it by swapping the widgets and reparenting the children. It works for any widget that has direct children, not only QGroupBox. It would require special case handling for widgets such as QScrollArea and QMainWindow that wrap children in a special sub-widget.
See this question for a related discussion of programmatically promoting widgets.
// https://github.com/KubaO/stackoverflown/tree/master/questions/group-reparent-36603051
#include <QtWidgets>
/// Replaces the visible widget with a hidden widget, preserving the layout of the
/// children, and making the new widget visible.
void swapWidgets(QWidget * a, QWidget * b)
{
auto src = a->isVisible() ? a : b;
auto dst = a->isVisible() ? b : a;
Q_ASSERT(dst->isHidden());
/// Move the children to the destination
dst->setLayout(src->layout());
/// Replace source with destination in the parent
auto layout = src->parentWidget()->layout();
delete layout->replaceWidget(src, dst);
/// Unparent the source, otherwise it won't be reinsertable into the parent.
src->setParent(nullptr);
/// Only the destination should be seen.
src->hide();
dst->show();
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
QGridLayout wLayout{&w};
QPushButton swapBtn{"Swap"};
wLayout.addWidget(&swapBtn);
QWidget noBox;
QGroupBox box{"Group"};
wLayout.addWidget(&box);
QGridLayout boxLayout{&box};
for (int i = 0; i < 16; ++i)
boxLayout.addWidget(new QLabel(QString("Tr%1").arg(i)), i/8, i%8);
swapBtn.connect(&swapBtn, &QPushButton::clicked, [&] { swapWidgets(&box, &noBox); });
w.show();
return app.exec();
}
Yes there is a alternative that you can Try.
You can morph into a QFrame which will keep the behavior But make the container boundaryless
You can simply right click on the Group Box in the QDesigner and Select the 'Morph Into' option to select from

How to continue text editing after formatting changes of QGraphicsTextItem?

I am trying to make changes (font changes) to a QGraphicsTextItem that is editable.
I am trying to change formatting of fragments of text, or the formatting applied at typing point (if I set text bold, the text I type after that action at cursor position would be bold).
Setting formatting for text fragments works - but I can't find a way to return the focus correctly to the item.
I can show the caret at the right position, but I can't type in the box unless I actually click in box (even though it seems hat I should be able to).
Simple sample (for some reason it crashes on closing program but I don't care about that since I am testing the text class, not the main program):
header: mytextitem.h
#include <QGraphicsTextItem>
class MyTextItem : public QGraphicsTextItem
{
Q_OBJECT
public:
MyTextItem();
~MyTextItem() {}
public slots:
void setItemBold(const int b);
};
mytextitem.cpp
#include "mytextitem.h"
#include <QTextCursor>
MyTextItem::MyTextItem()
{
setPlainText("ABCD");
setFont(QFont("Arial", 20));
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
setTextInteractionFlags(Qt::TextEditorInteraction);
}
void MyTextItem::setItemBold(const int b)
{
int _weight = (b != 0) ? QFont::Bold : QFont::Normal;
QTextCursor _cursor = textCursor();
//int p = _cursor.position(); // this won't help
QTextCharFormat _format = _cursor.charFormat();
_format.setFontWeight(_weight);
_cursor.setCharFormat(_format);
//_cursor.setPosition(p, QTextCursor::KeepAnchor); // makes no difference on allowing me to type, but I can make the cursor move
//_cursor.movePosition(QTextCursor::NoMove, QTextCursor::KeepAnchor, 0); // makes no difference but I just thought some action might
setTextCursor(_cursor);
setFocus(Qt::MouseFocusReason);
// grabKeyboard(); // does nothing
}
main.cpp
#include <QApplication>
#include <QGraphicsView>
#include <QGridLayout>
#include <QtWidgets>
#include <QCheckBox>
#include "mytextitem.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene(-20, -20, 150, 100);
QGraphicsView view(&scene);
QWidget widget;
QGridLayout layout(&widget);
layout.addWidget(&view, 0, 0);
QCheckBox bold("Bold");
layout.addWidget(&bold, 0, 1);
MyTextItem* item = new MyTextItem();
scene.addItem(item);
QObject::connect(&bold, SIGNAL(stateChanged(int)), item, SLOT(setItemBold(int)));
view.ensureVisible(scene.sceneRect());
widget.show();
return a.exec();
}
Editing the item is possible only if clicking in the box.
Assuming that I am already in the box (editing), and I push the "Bold" checkbox, I expect to be able to continue editing - type in the box - but even though I try to
set focus (which places the blinking text cursor in the box),
set position for cursor (I can move it, or select things... that works but I want to keep current position and selection)
grab keyboard - seems to do nothing
nothing seems to return me to the box so I continue typing (with the new font setting).
How can I get the QTextCursor or anything else to allow me to keep editing the text ?
You need to focus on QGraphicsView after format change. You can't focus on QGraphicsTextItem because it isn't QWidget.

QTabWidget how to hide pane only?

I have added a QToolButton as corner widget in QTabWidget which is checkable. I want to hide all tabs (panes only) when the tool button is unchecked. I tried to connect button's signal clicked(bool) with all tab's setVisible(bool) slot not working but. I also connected tabwidget's setvisible to the signal but complete widget became invisible(it was a silly trial). Is there any way to make only pane invisible and tab bar will not disappear ?
Edit: Code (ui have a tabwidget and two tabs namely tab and tab_2)
ui->setupUi(this);
QToolButton * b = new QToolButton;
b->setCheckable(true);
b->setChecked(true);
b->setAutoRaise(true);
b->setText("Hide Tabs");
ui->tabWidget->setCornerWidget(b);
connect(b,SIGNAL(clicked()),ui->tab,SLOT(hide()));
connect(b,SIGNAL(clicked()),ui->tab_2,SLOT(hide()));
Use qFindChild to find the QTabBar within the QTabWidget:
QTabBar *tabBar = qFindChild<QTabBar *>(ui->tabWidget);
tabBar->hide();
For Qt5:
QTabBar *tabBar = ui->tabWidget->findChild<QTabBar *>();
tabBar->hide();
so I understand it like this, you want to hide the TabBar and let the tab visible. Or at least that's what I get from your question
Well if that the case all you have to do it's this:
connect(ui->pushButton,SIGNAL(clicked()),ui->tabWidget->tabBar(),SLOT(hide()));
I hope this was helpful, even do the questions in a little old, I though it may help new viewers.
Here is my take on this. I've created a class that inherits QTabWidget. What I do is; set the "maximum vertical size of QTabWidget" to its tabBars height to hide the panels.
It is a hacky solution and I had to add some extra lines to deal with quirks.
file: hidabletabwidget.h
#ifndef HIDABLETABWIDGET_H
#define HIDABLETABWIDGET_H
#include <QTabWidget>
#include <QAction>
class HidableTabWidget : public QTabWidget
{
Q_OBJECT
public:
explicit HidableTabWidget(QWidget *parent = 0);
QAction hideAction;
private slots:
void onHideAction(bool checked);
void onTabBarClicked();
};
#endif // HIDABLETABWIDGET_H
file: hidablewidget.cpp
#include "hidabletabwidget.h"
#include <QTabBar>
#include <QToolButton>
HidableTabWidget::HidableTabWidget(QWidget *parent) :
QTabWidget(parent),
hideAction("▾", this)
{
hideAction.setCheckable(true);
hideAction.setToolTip("Hide Panels");
QToolButton* hideButton = new QToolButton();
hideButton->setDefaultAction(&hideAction);
hideButton->setAutoRaise(true);
this->setCornerWidget(hideButton);
connect(&hideAction, SIGNAL(toggled(bool)), this, SLOT(onHideAction(bool)));
connect(this, SIGNAL(tabBarClicked(int)), this, SLOT(onTabBarClicked()));
}
void HidableTabWidget::onHideAction(bool checked)
{
if (checked)
{
this->setMaximumHeight(this->tabBar()->height());
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
}
else
{
this->setMaximumHeight(QWIDGETSIZE_MAX); // by default widgets can expand to a maximum sized defined by this macro
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
}
void HidableTabWidget::onTabBarClicked()
{
hideAction.setChecked(false);
}
To use this, you can simply "promote" your QTabWidget to "HidableTabWidget" using qt designer.
And here is how it looks on my system:
You usually want to remove the Tab from the QTabWidget:
void QTabWidget::removeTab ( int index )
The Tab removed will not be deleted and can be reinserted!
So you would connect your QToolButton b to a slot which simply removes the Tabs like this:
connect( b, SIGNAL(clicked()), this, SLOT(hideTabs() );
..
void Foobar::hideTabs( void )
{
for( int i = 0; i < ui->tabWidget->count(); ++i )
ui->tabWidget->removeTab(i);
}
I can not comment due to my low "reputation" so far. If I could I'd just add a comment to Anatoli's answer: the goal is to hide "page area", not "tab bar". So if we imply they always use QStackedWidget for that then the answer should be more like:
auto * tab_pane = qFindChild<QStackedWidget *>(ui->tabWidget);
tab_pane->hide();
or for Qt5:
auto * tab_pane = ui->tabWidget->findChild<QStackedWidget *>();
tab_pane->hide();

qt: How to animate the transparency of a child QPushButton using QPropertyAnimation?

I want to progressively decrease the opacity of a QPushButton over a time of 2 seconds to complete transparency. For that I used the QPropertyAnimation class and used the property "windowOpacity" of the button to achieve the effect. But that worked only for a standalone QPushButton. When I assigned a parent to the button, the effect disappeared. Is there any way of achieving the same effect for child buttons ?
The windowOpacity property only applies to top level windows so it won't help you with animating transparency on child widgets unfortunately.
Standard controls are a bit problematic as well as there are many considerations contributing to their final appearance. There are many approaches you could take but they will all involve a certain amount of coding. There is no easy way :)
To set the transparency of a QPushButton, you would need to either set a stylesheet for it, or change some of the properties of the palette. Since neither of these options are directly usable by a QPropertyAnimation, you can create your own custom property and animate that.
Below is some code that specifies a custom property for a MainWindow called alpha. The alpha value is used to set the alpha portion of the button color. With this property in place, we can use QPropertyAnimation to animate it. The result is a button that fades in and out. This only handles the buttons background and not the text but it should provide a starting point for you.
MainWindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QPushButton>
class MainWindow : public QWidget
{
Q_OBJECT
Q_PROPERTY(int alpha READ alpha WRITE setAlpha);
public:
MainWindow();
virtual ~MainWindow();
private:
int m_alpha;
QPushButton * m_button1, *m_button2;
int alpha() const;
void setAlpha(const int a_alpha);
};
#endif /* MAINWINDOW_H */
MainWindow.cpp: (Updated to include stylesheet transparency example)
#include <QPlastiqueStyle>
#include <QPropertyAnimation>
#include "MainWindow.h"
MainWindow::MainWindow() :
m_button1(0),
m_button2(0),
m_alpha(255)
{
resize(200, 200);
QPalette windowPalette(palette());
windowPalette.setBrush(QPalette::Background, QBrush(QColor(200, 0, 0)));
setPalette(windowPalette);
m_button1 = new QPushButton(this);
m_button1->setText("Palette Transparency");
m_button1->setAutoFillBackground(false);
// NOTE: Changing the button background color does not work with XP Styles
// so we need to use a style that allows it.
m_button1->setStyle(new QPlastiqueStyle());
m_button2 = new QPushButton(this);
m_button2->move(0, 50);
m_button2->setText("Stylesheet Transparency");
m_button2->setAutoFillBackground(false);
m_button2->setStyle(new QPlastiqueStyle());
QPropertyAnimation *animation = new QPropertyAnimation(this, "alpha");
animation->setDuration(1000);
animation->setKeyValueAt(0, 255);
animation->setKeyValueAt(0.5, 100);
animation->setKeyValueAt(1, 255);
animation->setLoopCount(-1);
animation->start();
}
MainWindow::~MainWindow()
{
}
int MainWindow::alpha() const
{
return m_alpha;
}
void MainWindow::setAlpha(const int a_alpha)
{
m_alpha = a_alpha;
QPalette buttonPalette(m_button1->palette());
QColor buttonColor(buttonPalette.button().color());
buttonColor.setAlpha(m_alpha);
buttonPalette.setBrush(QPalette::Button, QBrush(buttonColor));
m_button1->setPalette(buttonPalette);
QString stylesheet("background-color: rgba(0,200,0," + QString::number(m_alpha) + ");");
m_button2->setStyleSheet(stylesheet);
}
main.cpp:
#include <QtGui/QApplication>
#include "MainWindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow m;
m.show();
return app.exec();
}
I faced the same problem a while ago and came to basically the same solution(manipulating the controls palette). But, while the helper property in the MainWindow is surely a quick and easy solution, it's a dirty one too. So, at least for larger and reoccurring usage it seamed much more appropriate to create a new animation class covering those needs. This isn't much more code(simply inherit QAbstractAnimation, move that palette stuff in there and pass the target control as a parameter into that class) but it keeps your parent control(like the mainwindow-class) free from such animation implementation details which surely don't belong in there.

problem with replacing a background image using signal / slot in qt

i want to make a simple chess program. So far i've made the board using QTableWidget and loaded the piece pictures in the cells of table. Now i wnat to use signal and slot so that when user clicks a cell and then click another cell the piece picture from first cell goes to second cell, But I don't know how to do it.
Note that i don't want these "piece moves" obey the real chess rules. I only wnat to do the picture replacement between two cells . Later i will make them obey the rules.
here is the code. in this code only table's item(0,0) has a picture. can anyone say how to write a code so that when i click that item then click to item(1,1) , picture "1.bmp" goes to background of item(1,1)?
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QHBoxLayout>
#include <QTableWidget>
#include <QHeaderView>
class Table : public QWidget
{
Q_OBJECT
public:
Table(QWidget *parent = 0);
slots:
//??????
};
Table::Table(QWidget *parent)
: QWidget(parent)
{
QHBoxLayout *hbox = new QHBoxLayout(this);
QTableWidget *table = new QTableWidget(8 , 8 , this);
table->setFixedSize(900,900);
table->horizontalHeader()->setDefaultSectionSize(100);
table->verticalHeader()->setDefaultSectionSize(100);
table->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
table->verticalHeader()->setResizeMode(QHeaderView::Fixed);
QString fileName = "/1.bmp";
QPixmap pic(fileName);
QBrush brush(pic);
QTableWidgetItem* item = new QTableWidgetItem();
item->setBackground(brush);
table->setItem(0,0,item);
hbox->addWidget(table);
setLayout(hbox);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Table table;
table.show();
return app.exec();
}
There are really two questions here.
The first one regarding signals/slots with QTableWidgetItem, and the second regarding handling mouse clicks on the QTableWidget.
Signals Slots on a QTableWidgetItem
note: I don't recommend doing it this way, read all the way to the bottom*
Using signals and slots requires that the object that emits the signal, have the signal defined in the class definition. Likewise the object that receives a slot, must have that slot declared in the class definition.
You'll notice (on the Qt docs) that QTableWidgetItem doesn't have a signals or slots to set/remove the background brush you are using to draw your picture. So, you will have to subclass QTableWidgetItem, and provide this signals/slots yourself.
Example:
class ChessItem : public QTableWidgetItem
{
// constructor / destructor
// other methods
public slots:
void slotChangeBackground( const QBrush & brush )
{
setBackground( brush );
}
};
Handling Mouse Clicks on the QTableWidget
edit: I removed the event handling paragraph, because using QTableWidget's builtin signals is easier
QTableWidget offers the cell clicked signal:
void QTableWidget::cellClicked ( int row, int column )
So in your Table class add a slot, then connect it the cellClicked signal to it:
// in your Table's constructor:
connect( table, SIGNAL( cellClicked(int, int) ), this, SLOT( slotCellClicked(int,int) ) ) );
// elsewhere...
void slotCellClicked(int row, int column) {
// handle mouse clicking here
}
The problem as I see it is you don't want to just connect any ol signal to slotChangeBackground, because that would change every background. So I suggest not using signals/slots for changing the background, and instead use QTableWidget::itemAt ( int ax, int ay ) in your slotCellClicked(x,y) to retrieve the item at a coordinate, then call setBackground on it.

Resources