Qt - requiring new model rows to be non-empty - qt

I'm making a program where the user can add multiple people (participants) in a list. When the "Add" button is clicked, a new row is added and "edit" is called for the name field. All is well so far, but there is a thing I'd like to implement, and I can't seem to figure out how: when the user closes the editing field (presses enter or escape, clicks elsewhere, etc.) and if the name field remains empty, I'd like the row to be deleted. In other words, a name has to be filled in. Here is what I have so far:
void MainWindow::addParticipant()
{
QList<QStandardItem *> newRow;
newRow << new QStandardItem()
<< new QStandardItem();
participantModel->appendRow(newRow);
participantView->edit(participantModel->index(participantModel->rowCount()-1, 0));
}
Here participantModel is a QStandardItemModel and participantView is a QTreeView. I tried using signals and slots to detect when a row is empty and to delete it, but it hasn't worked and the syntax is elusive to me.
Ideally I'd be able to detect when the name field is not being edited anymore, so that I can delete the row if need be.

Here is ugly but working solution: subclass from QItemDelegate and check input data inside setModelData member function. As far setModelData has a const qualifier you can not modify model inside it, so you need some trick: in the following example the model is modified inside handler of closeEditor signal.
class MainWidget : public QWidget
{
Q_OBJECT
public:
MainWidget ()
{
QStandardItemModel * model = new QStandardItemModel ();
ItemDelegate * delegate = new ItemDelegate ();
table->setItemDelegate (delegate);
connect (delegate, & ItemDelegate::closeEditor, [=](){
if (isEmpty) {
model->removeRow (emptyRow);
isEmpty = false;
emptyRow = -1;
}
});
connect (delegate, & ItemDelegate::cellEdited, [=](const int row){
isEmpty = true;
emptyRow = row;
});
}
bool isEmpty;
int emptyRow;
};
class ItemDelegate : public QItemDelegate
{
Q_OBJECT
signals:
void cellEdited (int) const;
public:
void setModelData (QWidget * widget, QAbstractItemModel * model, const QModelIndex & index) const override
{
if (0 == index.column () ) {
if (QLineEdit * cellWidget = qobject_cast <QLineEdit *> (widget) ) {
if (cellWidget->text ().isEmpty () ) {
emit cellEdited (index.row () );
return;
}
}
}
QItemDelegate::setModelData (widget, model, index);
}
};
Complete example available at GitLab.

The comments/answers posted thus far have urged me to look more into item delegates. Quite embarrassingly, after relatively little googling I found the following solution for my problem:
void MainWindow::addParticipant()
{
QStyledItemDelegate *participantDelegate = new QStyledItemDelegate;
participantView->setItemDelegateForColumn(0, participantDelegate);
QList<QStandardItem *> newRow;
newRow << new QStandardItem()
<< new QStandardItem();
participantModel->appendRow(newRow);
connect(participantDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), this, SLOT(checkRow()));
participantView->edit(participantModel->index(participantModel->rowCount()-1, 0));
}
Apparently the closeEditor signal (only available to delegates) is exactly what I was looking for. When the editor is closed, the slot checkRow() checks if the name field of the participant is empty and decides whether or not to delete the row.

Related

Qt - Not correctly adding widgets to QHBoxLayout after clearing the layout

I have a QHBoxLayout in which I added some widgets. I need to be able to refresh the layout dynamically so I use this to clear the layout :
void ClearLayout(QLayout* layout)
{
if (!layout)
return;
QLayoutItem* item;
while ((item = layout->takeAt(0)) != nullptr)
{
delete item->widget();
ClearLayout(item->layout());
}
}
This indeed removes all widgets and layouts. After this layout->isEmpty() returns true and layout->count() returns 0.
However, when I try to add new widgets (same type of other previously added but new instance) It does not work !
AddWidget()
{
// DeviceWidget inherits QWidget
DeviceWidget* deviceWidget = new DeviceWidget;
deviceWidget->setFixedSize(150, 200);
connect(deviceWidget->GetSignalObject(), &DeviceObject::Selected, this,
&DeviceLayout::SelectedDevice);
layout->addWidget(deviceWidget, 0, Qt::AlignCenter);
}
This is the same function used previously to add the widgets to the layout and worked the first time at Construction:
MainLayout(QWidget* parent) : QHBoxLayout(parent)
{
layout = new QHBoxLayout;
addLayout(layout);
uint32 nb = GetDeviceNumber(); // returns 2
for (uint32 i = 0; i < deviceNb; ++i)
AddDeviceWidget();
}
After trying to add 2 widgets I have layout->isEmpty() returns true and layout->count() returns 2 so I'm confused …
thanks for any help provided :)
EDIT:
The problem seems to be comming from my DeviceWidget class since trying to add a simple QLabel to the cleared layout worked. Here's the DeviceWidget Constructor:
DeviceWidget::DeviceWidget(QWidget* parent) : QWidget(parent)
{
QVBoxLayout* vLayout = new QVBoxLayout;
QLabel* deviceIcon = new QLabel("DeviceIcon", this);
deviceIcon->setFixedSize(128, 128);
deviceIcon->setPixmap(QPixmap::fromImage(QImage("Resources/Icons/device.png")));
deviceIcon->setObjectName("DeviceIcon");
// StatusWidget inherits QWidget
// Just override paintEvent to display a colored filled disk
m_status = new StatusWidget(20, Status::Close, this);
m_status->setObjectName("DeviceStatus");
vLayout->addWidget(deviceIcon, 0, Qt::AlignCenter);
vLayout->addWidget(m_status, 0, Qt::AlignCenter);
// DeviceObjct inherits from QObject an add a signal
m_object = new DeviceObject(size());
// Function clearing the stylesheet background-color
Clear();
setLayout(vLayout);
installEventFilter(this);
setObjectName(QString("DeviceWidget"));
}
Commenting installEventFilter(this) make it work so I think I need to add an event filter to make it work but I don't know which one
As said in the Edit, The problem is coming from DeviceWidget added in the layout that override eventFilter. There is probably a way to add a case in eventFilter to make it work but in my case it was best either (1) or (2):
1. Remove eventFilter from class DeviceWidget and put it in class DeviceObject: m_object is present to emit a signal according to event:
DeviceObject.h:
DeviceObject(QObject* parent);
bool eventFilter(QObject* obj, QEvent* event) override;
signals:
void Select(uint32 i);
Then in class DeviceWidget still call installEventFilter but with m_object as parameter: installEventFilter(m_object);
For the other event (Enter/Leave) I overrode void enterEvent(QEvent* event) and void leaveEvent(QEvent* event) for class DeviceWidget. That's what lead me to the second option that seems better.
2. Completely remove eventFilter and installEventFilter as it is only used to emit a signal when widget is clicked and do things when cursor hovers the widget. Instead override enterEvent and leaveEvent for class DeviceWidget like said before for hover event.
Then in class DeviceObjecy override void mousePressEvent(QMouseEvent*) for clicked event.

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.

How to make a Qt dialog read-only?

How to make a QT dialog read-only? Any general way to implement it easily? For example
(1) set all its containing widgets disable. (how to implement it?)
(2) Intercept edit events like key pressed, mouse pressed but how not to intercept the one to close the dialog?
I think this feature should be very helpful.
Disabling the widgets can be done similar to the following:
void myDialog::disableWidgets()
{
QList<QWidget *> widgets = this->findChildren<QWidget *>();
foreach(QWidget* widget, widgets)
{
widget->setEnabled(false);
}
}
To intercept events, QDialog includes the function installEventFilter(QObject*).
This allows you to use a separate object to receive all events passed to the dialog. You can then choose to handle the event in the object, or pass it on to the dialog itself by calling the base class QObject::eventFilter
class MyEventHandler : public QObject
{
Q_OBJECT
protected:
bool MyEventHandler::eventFilter(QObject *obj, QEvent *event)
{
// handle key press events
if (event->type() == QEvent::KeyPress)
{
// Do something
// ...
return true; // event handled by the class
}
else
{ // ignore this event and pass it to the dialog as usual
return QObject::eventFilter(obj, event);
}
}
return false;
};
QDialog* dlg = new QDialog;
MyEventHandler evtHandler = new MyEventHandler;
dlg->installEventFilter(evtHandler);
Read-only is a strange term to apply to a dialog. Disabling all widgets as above does the trick. If you only wanted to make the input part of a QInputDialog read-only (while leaving scrollbars, buttons, etc. enabled), you could adapt that code as below:
QInputDialog dialog(this);
dialog.setOptions(QInputDialog::UsePlainTextEditForTextInput);
dialog.setWindowTitle("Title");
dialog.setLabelText("Label");
dialog.setTextValue("1\n2\n3\n");
QList<QWidget *> widgets = dialog.findChildren<QWidget *>();
foreach(QWidget* widget, widgets) {
if (strcmp(widget->metaObject()->className(),"QPlainTextEdit")==0) {
QPlainTextEdit *t = static_cast<QPlainTextEdit*>(widget);
t->setReadOnly(true);
}
}
dialog.exec();

auto select first proposition of QCompleter in PopupCompletion mode

I didn't manage to select the first item of the completer when the popup is displayed in PopupCompletion mode.
My current code that doesnt work:
completer->setCompletionPrefix(text);
QItemSelectionModel* sm = new QItemSelectionModel(completer->completionModel());
sm->select(completer->completionModel()->index(0,0), QItemSelectionModel::Select);
completer->popup()->setSelectionModel(sm);
Any suggestions?
I would try changing the order of the last 2 lines:
completer->popup()->setSelectionModel(sm);
sm->select(completer->completionModel()->index(0,0), QItemSelectionModel::Select);
Probably the change of the selection for the popup (its a view) ocurs when selectionChanged() is emited.
So you have to set first the selection model, then do the select.
void QItemSelectionModel::select ( const QModelIndex & index,
QItemSelectionModel::SelectionFlags command ) [virtual slot]
Selects the model item index using the specified command, and emits
selectionChanged().
BTW, u dont have to create a new selection model, just ask the popup for it (Againt, its a view):
completer->popup()->selectionModel();
http://qt-project.org/doc/qt-5.0/qtwidgets/qabstractitemview.html#selectionModel
I don't know if this is what you wanted, but in my case I wanted to be able to press enter and auto-select the first item in the pop-up list (as it does with UnfilteredPopupCompletion).
What worked for me was:
class AutoSelectFirstFilter : public QObject
{
Q_OBJECT
protected:
virtual bool eventFilter(QObject *obj, QEvent *event) override
{
if (event->type() == QEvent::KeyPress)
{
if(static_cast<QKeyEvent *>(event)->key() == Qt::Key_Return)
{
QAbstractItemView* l = static_cast<QAbstractItemView*>(obj);
QModelIndex i = l->model()->index(0,0);
if(i.isValid())
l->selectionModel()->select(i, QItemSelectionModel::Select);
}
}
return false;
}
};
and than:
AutoSelectFirstFilter tmp;
completer->popup()->installEventFilter(&tmp);
PS: Don't forget to re-run qmake.

How to change value of QProgressBar in QTreeWidgetItem?

I'm receiving a signal with parametres (Current, total) and each time I'm suppose to
alter the value of progressbar which is inside the QTreeWidgetItem.
That is my source code.
I have:
QMap<QXmppTransferJob*, TransferItemWidget*> widget_map;
And I add here new items
void MainWindow::addItem(QXmppTransferJob *job)
{
QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
widget_map[job] = new TransferItemWidget;
widget_map[job]->fileNameLabel->setText(job->fileName());
widget_map[job]->bareJidLabel->setText(job->jid());
ui->treeWidget->setItemWidget(item,0,widget_map[job]);
}
and each time when I receive a signal there implemented the following slot:
void MainWindow::progress(qint64 &current, qint64 &total)
{
QXmppTransferJob *job = (QXmppTransferJob*)QObject::sender();
widget_map[job]->progressBar->setMaximum(total);
widget_map[job]->progressBar->setValue(current);
}
Progressbar isn't changing by value but remains the same? Can anyone guide me through to find my mistake

Resources