Disable validation in QSpinBox - qt

Hence I have a QSpinBox, and want to unset validation for writing not only int values, but also string in it.
Please help me to fix this.
I have tried this, but it does not work:
class Spinbox:public QSpinBox
{
public:
Spinbox(QWidget* parent=0)
:QSpinBox(parent){}
void setLineEdit(QLineEdit *l)
{
QSpinBox::setLineEdit(l);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Spinbox de;
QLineEdit le;
le.setValidator(0);
le.setText("text");
de.setLineEdit(&le);
de.show();
return a.exec();
}

Qt docs say that:
If QLineEdit::validator() for the lineEdit returns 0, the internal
validator of the spinbox will be set on the line edit.
Thus, in order to disable the QSpinBox's built in validator, you need to set your own (dummy?). I.e.
class Validator : public QValidator
{
public:
State validate(QString &input, int &pos ) const
{
return QValidator::Acceptable;
}
};
[..]
Spinbox de;
QLineEdit le;
le.setValidator(new Validator());
le.setText("text");
de.setLineEdit(&le);
de.show();

Related

How to check if the application has been minimized

Whenever the application window is minimized or maximized i want to link that signal with a function.
This is the code.
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
Renderer w(model ); // This is QWidget
w.show();
QObject::connect(&w, &QWindow::windowStateChanged, [&](Qt::WindowState state) {
});
// how will i define the QObject::connect
return application.exec();
}
What would be the parameters for the QObject::connect function ?
You cannot use the connect function to connect to different slots based on the given value. You can however simply call the functions based on the value by checking the value in your lambda.
At least, you could if you had the signal. However, your connect suggests that w is - or inherits - a QWindow. You can obviously only connect to signals your class provides. As your Renderer is a QWidget, you have to check that class.
The documentation of QWidget tells us, that there is no windowStateChanged signal, but it states:
When the window state changes, the widget receives a changeEvent() of type QEvent::WindowStateChange.
So therefor we can create our own signal and connect to that. This can look similar to the following working example:
#ifndef RENDERER_H
#define RENDERER_H
#include <QWidget>
#include <QEvent>
class Renderer : public QWidget {
Q_OBJECT
signals:
void stateChanged(bool isMaximized);
protected:
void changeEvent(QEvent *e)
{
if(e->type() == QEvent::WindowStateChange) {
emit stateChanged(windowState() & ~Qt::WindowMaximized);
}
QWidget::changeEvent(e);
}
};
#endif // RENDERER_H
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
Renderer w; // This is QWidget
w.show();
QObject::connect(&w, &Renderer::stateChanged, [&](bool maximized) {
qDebug() << "Maximized?" << maximized;
});
return application.exec();
}
I was able to solve by using QApplication::focusWindow()
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
Renderer w; // This is QWidget
w.show();
QObject::connect(QApplication::focusWindow(), &Renderer::stateChanged, [&](bool maximized) {
qDebug() << "Maximized?" << maximized;
});
return application.exec();
}

Is it possible to change default behavior of a checkable QGroupBox?

The question is pretty straight forward: is it possible to change the default behavior of a checkable QGroupBox object? I designed a user interface with many QLineEdit objects inside a checkable QGroupBox, the desired behavior is: when QGroupBox is not checked all of its children are enable and when it is checked all of its children are disable.
As you can see at the oficial QGroupBox documentation, it says:
If the check box is checked, the group box's children are enabled; otherwise, the children are disabled and are inaccessible to the user.
One trick is to modify the painting so that when it is checked the check is not shown and vice versa:
#include <QtWidgets>
class GroupBox: public QGroupBox{
public:
using QGroupBox::QGroupBox;
protected:
void paintEvent(QPaintEvent *){
QStylePainter paint(this);
QStyleOptionGroupBox option;
initStyleOption(&option);
if(isCheckable()){
option.state &= ~(isChecked() ? QStyle::State_On : QStyle::State_Off);
option.state |= (isChecked() ? QStyle::State_Off : QStyle::State_On);
}
paint.drawComplexControl(QStyle::CC_GroupBox, option);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GroupBox groupBox;
groupBox.setCheckable(true);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(new QLineEdit);
vbox->addWidget(new QLineEdit);
vbox->addWidget(new QLineEdit);
vbox->addStretch(1);
groupBox.setLayout(vbox);
groupBox.show();
return a.exec();
}

QLineEdit should accept hexadecimal values ranging from [0 - FFFFF]

I have a requirement where I want my QLineEdit should accept hexadecimal values ranging from [0 - FFFFF]. can someone help me out with this?
I have tried the below code, but it holds good for only 1 char display.
I don't see any code in your post, but what you're looking for is a validator, derived from the QValidator class. Create a sub-class, say HexValidator, and implement the "validate" method. You check the input string for the allowed characters and range and return the appropriate state.
You then assign the validator to the QLineEdit using the QLineEdit::setValidator method. Note that the QLineEdit doesn't take ownership of the validator, so you need to make sure you delete it separately or give it a parent so that it gets cleaned up when the parent is deleted. You can create a single validator and assign it to multiple fields if needed.
I was wrong in my comment about Qt docs having a Hex spin box example... so I found one in my archive instead. It could be more flexible, but OTOH it's very simple and short. I know this isn't a QLineEdit but maybe it'll help anyway. The QValidator used here could be used in a line edit also.
#ifndef _HEXSPINBOX_H_
#define _HEXSPINBOX_H_
#include <QSpinBox>
#include <QRegularExpressionValidator>
// NOTE: Since QSpinBox uses int as the storage type, the effective editing range
// is +/- 0x7FFF FFFF, so it can't handle a full unsigned int.
// QDoubleSpinBox would be a more suitable base class if a wider range is needed.
class HexSpinBox : public QSpinBox
{
Q_OBJECT
public:
HexSpinBox(QWidget *parent = nullptr,
bool showPrefix = false,
const QString &format = QStringLiteral("%x")) :
QSpinBox(parent),
format(format)
{
// Validates hex strings up to 8 chars with or w/out leading "0x" prefix.
// For arbitrary prefix/suffix, the regex could be built dynamically
// in validate(), or override setPrefix()/setSuffix() methods.
const QRegularExpression rx("(?:0[xX])?[0-9A-Fa-f]{1,8}");
validator = new QRegularExpressionValidator(rx, this);
setShowPrefix(showPrefix);
}
public slots:
void setShowPrefix(bool show)
{
if (show)
setPrefix(QStringLiteral("0x"));
else
setPrefix(QString());
}
void setFormat(const QString &text)
{
format = text;
lineEdit()->setText(textFromValue(value()));
}
protected:
QValidator::State validate(QString &text, int &pos) const override
{
return validator->validate(text, pos);
}
int valueFromText(const QString &text) const override
{
return text.toInt(0, 16);
}
QString textFromValue(int value) const override
{
return QString().sprintf(qPrintable(format), value);
}
private:
QRegularExpressionValidator *validator;
QString format;
};
#endif // _HEXSPINBOX_H_
Example:
#include "HexSpinBox.h"
#include <QApplication>
#include <QBoxLayout>
#include <QDialog>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDialog d;
d.setLayout(new QVBoxLayout);
HexSpinBox* sb = new HexSpinBox(&d);
sb->setMaximum(0xFFFFF);
sb->setValue(0x0A234);
d.layout()->addWidget(sb);
HexSpinBox* sb2 = new HexSpinBox(&d, true, QStringLiteral("%05X"));
sb2->setMaximum(0xFFFFF);
sb2->setValue(0x0A234);
d.layout()->addWidget(sb2);
return d.exec();
}

Disable specific items in QComboBox

In my application, I want to disable some items (i.e. not selectable, no highlights when mouse hovering above, and the texts are greyed out) in the QComboBox when certain conditions are met.
I indeed found someone did ask the same question here: Disable Item in Qt Combobox
But none of these solutions in the answers seem to actually work (including the trick).
Is there a decent and 'correct' way to implement this?
EDIT:
I found out why setting the flags wouldn't disable the items in my application: for some reasons, I had to set the style QStyle::SH_ComboBox_UseNativePopup(see https://codereview.qt-project.org/#/c/82718/). And this setting for some reasons blocked the flag setting. Does anyone have an idea why, and how to work around? A minimum test example is included (modified from the answer of #Mike):
#include <QApplication>
#include <QComboBox>
#include <QStandardItemModel>
#include <QProxyStyle>
class ComboBoxStyle : public QProxyStyle
{
public:
int styleHint ( StyleHint hint, const QStyleOption * option = 0, const QWidget * widget = 0, QStyleHintReturn * returnData = 0 ) const override
{
if ( hint == QStyle::SH_ComboBox_UseNativePopup )
{
return 1;
}
return QProxyStyle::styleHint( hint, option, widget, returnData );
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox comboBox;
// Setting this style would block the flag settings later on.
comboBox.setStyle( new ComboBoxStyle() );
comboBox.insertItem(0, QObject::tr("item1"));
comboBox.insertItem(1, QObject::tr("item2"));
QStandardItemModel* model = qobject_cast<QStandardItemModel*>(comboBox.model());
QStandardItem* item= model->item(1);
item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
comboBox.show();
return a.exec();
}
The answer linked in my comment above seems to be talking about an old version of Qt. I have tested on Qt5.4 and Qt5.6 and there is no need set the color yourself here, you just need to set and/or clear the Qt::ItemIsEnabled flag, here is an example:
#include <QtWidgets>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QComboBox comboBox;
comboBox.addItem(QObject::tr("item1"));
comboBox.addItem(QObject::tr("item2"));
comboBox.addItem(QObject::tr("item3"));
QStandardItemModel *model =
qobject_cast<QStandardItemModel *>(comboBox.model());
Q_ASSERT(model != nullptr);
bool disabled = true;
QStandardItem *item = model->item(2);
item->setFlags(disabled ? item->flags() & ~Qt::ItemIsEnabled
: item->flags() | Qt::ItemIsEnabled);
comboBox.show();
return a.exec();
}
Here is the technique #Mike describes, wrapped up in a convenient utility function:
void SetComboBoxItemEnabled(QComboBox * comboBox, int index, bool enabled)
{
auto * model = qobject_cast<QStandardItemModel*>(comboBox->model());
assert(model);
if(!model) return;
auto * item = model->item(index);
assert(item);
if(!item) return;
item->setEnabled(enabled);
}

Prevent QApplication app from closing if a service is running

I have a QML app in which I have subclassed QApplication to create my main screen with QML. The issue i have is on clicking Close button the application closes as intended, but I want to handle a situation where if some services are running I want to override close button behaviour.
I tried overriding closeEvent() without any luck. Can anyone point me to some ways I can handle this?
UPDATE : This is the code snippet I tried
class SingleApplication : public QApplication {
Q_OBJECT
public:
SingleApplication(int &argc, char **argv);
void closeEvent ( QCloseEvent * event )
{
event->ignore();
}
}
MAIN.cpp
#include "view.h"
#include <QDebug>
#include <QDesktopWidget>
#include "SingleApplication.h"
int main(int argc, char *argv[])
{
SingleApplication app(argc, argv);
if(!app.isRunning()) {
app.processEvents();
View view(QUrl("qrc:/qml/main.qml"));
#ifdef Q_OS_LINUX
view.setFlags(Qt::WindowMinimizeButtonHint|Qt::WindowCloseButtonHint);
#endif
view.setMaximumSize(QSize(1280,700));
view.setMinimumSize(QSize(1280,700));
// Centering the App to the middle of the screen
int width = view.frameGeometry().width();
int height = view.frameGeometry().height();
QDesktopWidget wid;
int screenWidth = wid.screen()->width();
int screenHeight = wid.screen()->height();
view.setGeometry((screenWidth/2)-(width/2),(screenHeight/2)-(height/2),width,height);
view.show();
return app.exec();
}
return 0;
}
There is no QApplication::closeEvent. Such virtual function belongs to QWidget.
Use of QApplication indicated that you have normal QWidget container for your QML UI (as you say UI is based on QML though). You should rather override that widget closeEvent e.g.:
class MyMainWidget : public QWidget // or is it QMainWindow?
{
// snip
private:
void closeEvent(QCloseEvent*);
}
void MyMainWidget::closeEvent(QCloseEvent* event)
{
// decide whether or not the event accepted
if (condition())
event->accept();
}
And if your container widget is not overridden yet (simply QWidget?), well, now you have to do so.
And you did not say whether or not you want to keep app window running. I assume you want that as well.

Resources