How to catch QEvent::LanguageChange in QObject - qt

My goal is to retranslate a QObject subclass on the fly.
In QWidget it's really simple to catch QEvent::LanguageChange: we just override changeEvent. However, there is not such method in QObject and this is where I'm stuck.
How to catch QEvent::LanguageChange in QObject?

You can simply override the QObject::event method...
class my_object: public QObject {
using super = QObject;
protected:
virtual bool event (QEvent *event) override
{
if (event->type() == QEvent::LanguageChange) {
/*
* Retranslation code goes here...
*/
/*
* Return true to prevent further processing. This may
* or may not be what you want depending on your needs.
*/
return true;
}
/*
* Fall through to the base class implementation.
*/
return super::event(event);
}
};
Alternatively, you could put the same logic in an event filter and attach that to the QObject of interest.

Related

How to connect clicking on context help button with my custom action?

I have a dialog with two buttons in the title bar: the context help button and the close button. How can I find out that the user clicked the context help button to perform my custom action? (I want to show some help page in the browser as in VS dialogs.)
I found a similar question, but how to do this with qt?
Context help button behaviour on CPropertySheet
Update.
Now I use the code like this:
class MyHelper : public QObject
{
Q_OBJECT
public:
explicit MyHelper( QObject * parent = nullptr ) {
qApp->installEventFilter( this );
}
protected:
virtual bool eventFilter( QObject * obj, QEvent * ev ) override {
if ( ev->type() == QEvent::EnterWhatsThisMode ) {
showHelp( QApplication::activeWindow() );
return true;
}
return QObject::eventFilter( obj, ev );
}
private:
void showHelp( QWidget * sender ) {
//TODO
}
};
I believe that QWidget::nativeEvent is what you are looking for.

Override checkable QGroupBox toggle behaviour

I've subclassed the QGroupBox class, with the checkable property enabled. I'm trying to override the behaviour of the toggle/checked events.
Here's the code:
class SideWidgetGroupBox: public QGroupBox
{
Q_OBJECT
public:
SideWidgetGroupBox(QWidget* parent = 0): QGroupBox(parent)
{
this->setCheckable(true);
connect(this, SIGNAL(toggled(bool)), this, SLOT(my_toggled(bool)));
}
private slots:
void my_toggled (bool on)
{
std::cout << "my toggled method" <<std::endl;
}
};
So far so good, my slot gets executed. However the groupboxs' contents also get enabled/disabled. Is there a way to prevent that? Or do I have to manually reset the original enabled/disabled state?
Is there a way to prevent enabling/disabling of a content?
Yes, but this way is not easy, because there is no QCheckBox there. What looks like a check box is an area of QGroupBox. And all events are processed by QGroupBox:
1. Override event method and prevent processing of QEvent::KeyRelease and QEvent::MouseRelease events by the base class.
bool SideWidgetGroupBox::event(QEvent *e)
{
switch (e->type()) {
case QEvent::KeyRelease:
case QEvent::MouseButtonRelease:
myHandler(e);
return true;
}
return QGroupBox::event(e);
}
2. In myHandler check whether space pressed or the mouse clicked on the checkbox. Store checkBox value and do what you need. Use this code to check what is under cursor:
QStyleOptionGroupBox box;
initStyleOption(&box);
QStyle::SubControl released = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
event->pos(), this);
bool toggle = released == QStyle::SC_GroupBoxLabel || released == QStyle::SC_GroupBoxCheckBox;
if (toggle)
{
m_state = !m_state;
update();
}
3. Add method initStyleOption and set state to the state of the checkBox (you should store it by yourself):
void SideWidgetGroupBox::initStyleOption(QStyleOptionGroupBox *option) const
{
QGroupBox::initStyleOption(option);
QStyle::State flagToSet = m_state ? QStyle::State_On : QStyle::State_Off;
QStyle::State flagToRemove = m_state ? QStyle::State_Off : QStyle::State_On;
option->state |= flagToSet;
option->state &= ~flagToRemove;
option->state &= ~QStyle::State_Sunken;
}
4.Method initStyleOption in QGroupBox is not virtual that is why you need to reimplement paintEvent also:
void paintEvent(QPaintEvent *)
{
QStylePainter paint(this);
QStyleOptionGroupBox option;
initStyleOption(&option);
paint.drawComplexControl(QStyle::CC_GroupBox, option);
}
do I have to manually reset the original enabled/disabled state?
You can't do this with setEnabled because it checks current checked state and prevents enabling of children. Although you can call setEnabled for children directly using this->findChildren<QWidget*>
Suggestion
You can use ways described above or remove standard checkBox and(or) label and put your own QCheckBox over the group (without layout, of course) and use it as you want. If you group can be moved you will need to move the check box also.

Checking that value of ui elements has been changed

Is there any way to check that the ui elements(line edit,combo box,etc.) of the dialog has been changed.
What I want is to show a message to the user if he changes the value of any single ui element, saying that details have been partially filled.
What i can do is use connect for each ui element & based on the value changed of each element i am setting a boolean flag & at the time of close event i am checking that boolean flag.
But Its quite complicate to check it for each widget.
Is there any easier way.
Code that I am using for single ui element is,
connect(ui->leAge,SIGNAL(textChanged(QString)),this,SLOT(functChanged())); //In Constructor
void DemoDialog::functChanged() //Will be called if value of line edit (ui->leAge) is changed
{
flag=true;
}
void DemoDialog::closeEvent(QCloseEvent *event)
{
if (flag) {
if (QMessageBox::warning(this,"Close","Do you want to close?",QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes) {
this->close();
}
}
You can't reimplement closeEvent to prevent closing a window. The close() call that you do is either redundant or an error (infinite recursion), since a closeEvent method call is just a way of being notified that a closing is imminent. At that point it's too late to do anything about it.
Keep in mind the following:
Closing a dialog usually is equivalent to canceling the dialog. Only clicking OK should accept the changes.
When a user wants to close a dialog, you don't have to ask them about it. They initiated the action. But:
It is proper to ask a user about dialog closure if there are changes have not been accepted - on platforms other than OS X.
So, you have to do several things:
Reimplement the void event(QEvent*) method. This allows you to reject the close event.
Offer Apply/Reset/Cancel buttons.
Your flag approach can be automated. You can find all the controls of the dialog box and set the connections automatically. Repeat the statement below for every type of control - this gets tedious rather quickly:
foreach(QTextEdit* w, findChildren<QTextEdit*>())
connect(w, SIGNAL(textChanged(QString)), SLOT(functChanged()));
You can leverage the meta property system. Most controls have a user property - that's the property that holds the primary value of the control (like text, selected item, etc). You can scan all of the widget children, and connect the property change notification signal of the user property to your flag:
QMetaMethod slot = metaObject().method(
metaObject().indexOfSlot("functChanged()"));
foreach (QWidget* w, findChildren<QWidget*>()) {
QMetaObject mo = w->metaObject();
if (!mo.userProperty().isValid() || !mo.userProperty().hasNotifySignal())
continue;
connect(w, mo.notifySignal(), this, slot);
}
Each widget is a QObject. QObjects can have properties, and one of the properties can be declared to be the user property. Most editable widget controls have such a property, and it denotes the user input (text, numerical value, selected index of the item, etc.). Usually such properties also have change notification signals. So all you do is get the QMetaMethod denoting the notification signal, and connect it to your function that sets the flag.
To determine the changed fields, you don't necessarily need a flag. In many dialog boxes, it makes sense to have a data structure that represent the data in the dialog. You can then have a get and set method that retrieves the data from the dialog, or sets it on the dialog. To check for changed data, simply compare the original data to current data:
struct UserData {
QString name;
int age;
UserData(const QString & name_, int age_) :
name(name_), age(age_) {}
UserData() {}
};
class DialogBase : public QDialog {
QDialogButtonBox m_box;
protected:
QDialogButtonBox & buttonBox() { return m_box; }
virtual void isAccepted() {}
virtual void isApplied() {}
virtual void isReset() {}
virtual void isRejected() {}
public:
DialogBase(QWidget * parent = 0) : QDialog(parent) {
m_box.addButton(QDialogButtonBox::Apply);
m_box.addButton(QDialogButtonBox::Reset);
m_box.addButton(QDialogButtonBox::Cancel);
m_box.addButton(QDialogButtonBox::Ok);
connect(&m_box, SIGNAL(accepted()), SLOT(accept()));
connect(&m_box, SIGNAL(rejected()), SLOT(reject()));
connect(this, &QDialog::accepted, []{ isAccepted(); });
connect(this, &QDialog::rejected, []{ isRejected(); });
connect(&buttonBox(), &QDialogButtonBox::clicked, [this](QAbstractButton* btn){
if (m_box.buttonRole(btn) == QDialogButtonBox::ApplyRole)
isApplied();
else if (m_box.buttonRole(btn) == QDialogButtonBox::ResetRole)
isReset();
});
}
}
class UserDialog : public DialogBase {
QFormLayout m_layout;
QLineEdit m_name;
QSpinBox m_age;
UserData m_initialData;
public:
UserDialog(QWidget * parent = 0) : QDialog(parent), m_layout(this) {
m_layout.addRow("Name", &m_name);
m_layout.addRow("Age", &m_age);
m_age.setRange(0, 200);
m_layout.addRow(&buttonBox());
}
/// Used by external objects to be notified that the settings
/// have changed and should be immediately put in effect.
/// This signal is emitted when the data was changed.
Q_SIGNAL void applied(UserData const &);
UserData get() const {
return UserData(
m_name.text(), m_age.value());
}
void set(const UserData & data) {
m_name.setText(data.name);
m_age.setValue(data.age);
}
void setInitial(const UserData & data) { m_initialData = data; }
bool isModified() const { return get() == m_initialData; }
protected:
void isAccepted() Q_DECL_OVERRIDE { emit applied(get()); }
void isApplied() Q_DECL_OVERRIDE { emit applied(get()); }
void isReset() Q_DECL_OVERRIDE { set(m_initialData); }
};
If you're only checking whether the input fields are filled when the Dialog closes, you don't need the flags you can only check if there is any input.
If you are filling the input fields programatically at some points but are also only interested in the change when the dialog closes, you can also check in the close function whether the current input is equal to the one you set earlier.
From the code you posted, I can't really see what you need the flags for.

event(QEvent*) conflicts with mousePressEvent(QMouseEvent *)?

In QT: I use a class inherited from QToolButton and rewrite event(QEvent*), now I want to add 'mousePressEvent', but it never gets hit, does event(QEvent*) conflict with mousePressEvent(QMouseEvent *) ? Thank you.
bool IconLabel::event (QEvent* e ) {
if ( e->type() == QEvent::Paint) {
return QToolButton::event(e);
}
return true;
}
void IconLabel::mousePressEvent(QMouseEvent* e)
{
int a = 1;//example
a = 2;// example//Handle the event
}
The class is:
class IconLabel : public QToolButton
{
Q_OBJECT
public:
explicit IconLabel(QWidget *parent = 0);
bool event (QEvent* e );
void mousePressEvent(QMouseEvent* e);
signals:
public slots:
};
All events received by a widget pass through event(..), and then are redirected to the appropriate event handler method. You have made the mistake of not forwarding on any events except paint events, if you just want to add mouse press event handling do this:
bool IconLabel::event (QEvent* e ) {
if ( e->type() == QEvent::Paint ||
e->type() == QEvent::QEvent::MouseButtonPress ) {
return QToolButton::event(e);
}
return true;
}
Also event handler methods should really be in protected, because events are only supposed to be distributed via the event queue (QCoreApplication::postEvent(..), etc.).

QTextEdit not working

Why doesn't drag and drop pictures work on this QTextEdit? I have tried everything.
here is the class TextEdit:
//textedit
class TextEdit : public QTextEdit
{
Q_OBJECT
public:
TextEdit(QWidget*parent) : QTextEdit(parent)
{
this->setAcceptDrops(true);
}
virtual void dragEnterEvent(QDragEnterEvent *e)
{
e->accept();
//QTextEdit::dragEnterEvent(e);
}
virtual void dragLeaveEvent(QDragLeaveEvent *e)
{
e->accept();
//QTextEdit::dragLeaveEvent(e);
}
//
virtual void dragMoveEvent(QDragMoveEvent *e)
{
e->accept();
// QTextEdit::dragMoveEvent(e);
}
virtual void dropEvent(QDropEvent *e)
{
QTextEdit::dropEvent(e);
}
bool canInsertFromMimeData(const QMimeData *source ) const
{
if (source->hasImage())
return true;
else
return QTextEdit::canInsertFromMimeData(source);
}
void insertFromMimeData( const QMimeData *source )
{
if (source->hasImage())
{
QImage image = qvariant_cast<QImage>(source->imageData());
QTextCursor cursor = this->textCursor();
QTextDocument *document = this->document();
document->addResource(QTextDocument::ImageResource, QUrl("image"), image);
cursor.insertImage("image");
}
}
};
context context context context context context context context context context context context context context context context context context context context context context context context context context context context context context context context
It depends on what application you are dragging the images from and what data that application decides to include in the operation. If it is not working for you, it is because whatever you are dropping contains no image data and probably only contains a URL or file path.
Dragging images from the file explorer under Windows 7 for me at least does not work but opening an image in the latest version of Firefox and dragging that onto the text edit does work. Try it :)

Resources