问题
Inspired by Label on QToolBar, possible? I'm trying to develop it. But my button do not blink on click, why?
I see in the other app looks like the button color gets gray during the click (while pressed) and the normal button gets blue. But my button which is just all an image don't have any behavior during the click.
On the left side is the toolbar using QAction
(question linked above) and on the right side is the code below.
QApplication a(argc, argv);
QMainWindow w;
QToolBar barA;
barA.setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
QWidget widget;
QVBoxLayout vLayout(&widget);
QHBoxLayout hLayout;
vLayout.addLayout(&hLayout);
QPixmap pixmap("../../../on.png");
QIcon ButtonIcon(pixmap);
QPushButton bt;
bt.setIcon(ButtonIcon);
bt.setIconSize(QSize(32,32));
bt.setFixedSize(QSize(32,32));
bt.show();
hLayout.addWidget(&bt);
barA.addWidget(&widget);
QPushButton bt2("clickc");
barA.addWidget(&bt2);
w.addToolBar(&barA);
w.show();
return a.exec();
回答1:
do something like:
auto b = new QPushButton(this);
b->setText("hello");
connect(b, &QPushButton::clicked, [](){qDebug()<< "ok...";});
ui->statusBar->addWidget(b);
回答2:
Still a shy blink though, not as good as the one from left app.
button.h
#include <QPushButton>
class Button : public QPushButton {
Q_OBJECT
QPixmap m_pixmap;
public:
explicit Button(QString img, QWidget *parent = nullptr);
public slots:
void enable();
void disable();
};
#endif // BUTTON_H
button.cpp
#include "button.h"
Button::Button(QString img, QWidget *parent) : QPushButton(parent) {
setIcon(QIcon(img));
setIconSize(QSize(32,32));
setFixedSize(QSize(32,32));
connect(this, &QPushButton::pressed, this, &Button::disable);
connect(this, &QPushButton::released, this, &Button::enable);
}
void Button::enable(){
setIcon(m_pixmap);
}
void Button::disable(){
m_pixmap = icon().pixmap(32,32,QIcon::Normal);
QPixmap pixmap = icon().pixmap(32,32,QIcon::Selected);
setIcon(pixmap);
}
回答3:
You should check out the docs: https://doc.qt.io/qt-5/stylesheet-examples.html
You probably just need to set the style sheet on it.
QToolButton:pressed { }
I am making an assumption here, but the tool bar probably already has a style sheet that handles the color change you are observing.
回答4:
The toolbar on the left which is using QToolButton
to show the QAction
s will have special QMacStyle
styling applied to the down/pushed state. https://code.woboq.org/qt5/qtbase/src/plugins/styles/mac/qmacstyle_mac.mm.html#3538 (more specifically here where it calls darkenPixmap()
)
Simplest solution seems like using a QToolButton
or just the QAction
route (actions are way more flexible than buttons anyway, you can use them multiple times in different UI elements).
Otherwise the code you posted in "Still a shy blink though" answer should work if you specifically add a file to the QIcon
for the Selected
mode. Or just use two icons and swap between them (seems easier).
来源:https://stackoverflow.com/questions/58012382/qpushbutton-not-blinking