Including a button in a WTableView - c++

I'm working on a Wt-based gui, and struggling with something that feels like it should be very simple:
The gui displays 'events'. In our project we have a model (ActiveEventsModel, based on WStandardItemModel) and a view, (ActiveEventsView, based on WTableView). Currently the view simply shows some text corresponding to various properties of the 'events'. The aim is to add an additional column to the table, contain a button (for example, a WPushButton) which allows the user to "acknowledge" the event shown in that row (in context, this essentially translates to dismissing the event - i.e. each event has a button, and clicking the button will remove that event from the model).
I searched online and found this discussion on the Wt-forum, which contains some guidance on putting a button in (derive from WAbstractItemDelegate and use setItemDelegateForColumn) and a code example for creating a button in an item delegate. After some minor changes for Wt-4.0 compatibility I now have my button in the table.
I've defined a very simple class, EventDelegate, derived from WAbstractItemDelegate:
header:
#include <Ui/WebToolkit.h> //convenience header containing all of the Wt elements we use
class EventDelegate : public Wt::WAbstractItemDelegate
{
public:
EventDelegate();
std::unique_ptr<Wt::WWidget> update(Wt::WWidget *widget, const Wt::WModelIndex &index,
Wt::WFlags<Wt::ViewItemRenderFlag> flags) override;
void acknowledge(Wt::WModelIndex &index);
};
source:
#include <Ui/EventDelegate.h>
EventDelegate::EventDelegate()
: WAbstractItemDelegate()
{
}
std::unique_ptr<Wt::WWidget> EventDelegate::update(Wt::WWidget *widget, const Wt::WModelIndex &index,
Wt::WFlags<Wt::ViewItemRenderFlag> flags)
{
std::unique_ptr<Wt::WWidget> w = std::make_unique<Wt::WPushButton>("acknowledge");
Wt::WPushButton *button = dynamic_cast<Wt::WPushButton*>(w.get());
button->clicked().connect(std::bind(&EventDelegate::acknowledge,this,index));
return w;
}
void EventDelegate::acknowledge(Wt::WModelIndex &index) {
//how do I interact with the model?
}
This seemed promising at first, but I just can't figure out how to actually make the button do anything to the model. I thought maybe I need to override WAbstractItemDelegate::setModelData, but for that I need the model, which the ItemDelegate doesn't seem to know anything about.
I do have the ModelIndex, and the ModelIndex knows which Model it belongs to - but will only give me it as const, which is no use to me because setModelData needs to alter it.
Should I just be giving the Model to the Delegate directly, for example as a constructor parameter? That seems an easy solution but feels very inelegant. Or am I just barking up the wrong tree entirely with how I'm trying to do this? I'm extremely new to Wt (and my colleagues only a little less so - this is a relatively new project and the first in our company that's used Wt) so that's very possible.
(I've not included a whole mcve because I'm pretty sure that what I'm missing here is conceptual. I can add one later if people feel it's really necessary to answer the question)

Related

Too deep hierarchy of signals-slots in Qt

I am writing GUI applicaton in Qt. Currently I waste too much time on routine. It seems something wrong with my architecture. Please tell me how can I change my approach to improve code.
What I am doing:
My program can be decomposed as hierarchy of classes (not inheritance but composition). In example:
class D { /* something */ };
class C { /* something */ };
class B { C c1; C c2; D d1; };
class A { D d1; C c1; };
So, actually it is a tree hierarchy where leaf nodes (class C, class D) are "models" in Qt terminology which hold data. At the top of hierarchy MainWindow (class A) is placed, which holds first level of "views" (class D, i.e. subwidget) and leaf node with data (class C, i.e. text field).
To pass information down from main window to data I use function calls from mainwindow (pushbuttons) to leaf nodes. After that data changes and tells parents about it with signal slot mechanism. Parents continue to pass message up with signaling.
I am really bored by establishing all these communication. Now I have up to 5 levels, however it is not that much in usual code when using composition. Please tell me how can I change my approach. Due to complexity of these connections, development of the code extremely slow, almost stopped.
It is hard to give a concrete example, because there are a lot of code, but the idea of problem which is very difficult to solve is following:
There are two QTreeView, which differently shows data from own model inherited from QAbstractItemModel (tree inside model is not that tree in previous discussion, this tree is only single level of hierarchy). I want to select objects in one QTreeView and change by that selection in second QTreeView. There are total 2 QTreeView, 2 different QAbstractItemModel instances, 2 trees of own objects (for each QAbstractItemModel), and single data.
Sounds like you might have become a victim of going through too many examples. Examples tend to cram functionality where it doesn't belong, creating the possibility to develop bad programming habits.
In actual production things need to be more compartmentalized. The main window should not be the container of the "application logic", all it needs to concern itself with is holding together the main widgets.
But that doesn't seem to be your case, judging by the necessity to delegate things "from mainwindow (pushbuttons) to leaf nodes" as you put it.
On a grander scale, it is not advisable to mix application logic with UI at all, much less cram it all in the main window. The application logic should be its own layer, designed so that it can work without any GUI whatsoever, and then the GUI is another layer that simply hooks up to the logic core.
The logic core should not be monolith either, it should be made of individual components focusing on their particular task.
Your use case doesn't really require any crazy amount of connections, just some basic handlers for the UI elements, which should target the logic core API rather than GUI elements as you appear to be doing now.
Your clarification unfortunately makes absolutely no sense to me, it is still completely unclear what you exactly you want to do.
Let's assume your situation is something like this:
Tree 1 shows a folder structure.
Tree 2 shows the file content of the folder, selected in tree 1.
Data is an editor for the file, assuming a text file, selected in tree 2.
So, in pseudocode, presuming that app is your application core logic object:
Clicking an item in tree 1 says app.setFolder(tree1.selectedItem())
Clicking an item in tree 2 says app.setFile(tree2.selectedItem())
Clicking the editor "save" button says app.save(editorUI.dataField.text())
logic layer gui layer
app mainWindow
folder <-----------select----------- tree1
file <-----------select----------- tree2
save(newData) { editor
if (file) file.rewrite(newData) textField
} saveBtn: app.save(textField.text())
Since there is only a single data source, you could do the following:
Create a general model for that data source. The model should represent the data source generally, without consideration of what the views need.
Create two proxy viewmodels that adapt the general model to the needs of the views.
Couple the selection models of the views that display the viewmodels.
Given the selection models on top of the two proxy models that map to the same source, we can propagate the selection change between them. We leverage the selection mapping provided by the proxy. The QAbstractProxyModel has a functional implementation of mapSelectionxxxx.
void applySel(const QItemSelectionModel *src, const QItemSelection &sel,
const QItemSelection &desel, const QItemSelectionModel *dst) {
// Disallow reentrancy on the selection models
static QHash<QObject*> busySelectionModels;
if (busySelectionModels.contains(src) || busySelectionModels.contains(dst))
return;
busySelectionModels.insert(src);
busySelectionModels.insert(dst);
// The models must be proxies
auto *srcModel = qobject_cast<QAbstractProxyItemModel*>(src->model());
auto *dstModel = qobject_cast<QAbstractProxyItemModel*>(dst->model());
Q_ASSERT(srcModel && dstModel);
// The proxies must refer to the same source model
auto *srcSourceModel = srcModel->sourceModel();
auto *dstSourceModel = dstModel->sourceModel();
Q_ASSERT(srcSourceModel && (srcSourceModel == dstSourceModel));
// Convey the selection
auto const srcSel = srcModel->mapSelectionToSource(sel);
auto const srcDesel = srcModel->mapSelectionToSource(desel);
auto const dstSel = dstModel->mapSelectionFromSource(srcSel);
auto const dstDesel = dstModel->mapSelectionFromSource(srcDesel);
// we would re-enter in the select calls
dst->select(dstSel, QItemSelectionModel::Select);
dst->select(dstDesel, QItemSelectionModel::Deselect);
// Allow re-entrancy
busySelectionModels.remove(src);
busySelectionModels.remove(dst);
}
The above could be easily adapted for a list of destination item selection models, in case you had more than two views.
We can use this translation to couple the selection models of the views:
void coupleSelections(QAbstractItemView *view1, QAbstractItemView *view2) {
auto *sel1 = view1->selectionModel();
auto *sel2 = view2->selectionModel();
Q_ASSERT(sel1 && sel2);
connect(sel1, &QItemSelectionModel::selectionChanged,
[=](const QItemSelection &sel, const QItemSelection &desel){
applySel(sel1, sel, desel, sel2);
});
connect(sel2, &QItemSelectionModel::selectionChanged,
[=](const QItemSelection &sel, const QItemSelection &desel){
applySel(sel2, sel, desel, sel1);
});
}
The above is untested and written from memory, but hopefully will work without much ado.

How to break the tab order chain of widgets in Qt?

In Qt you can define the tab order by using the Qt Designer or by using C++. The relationships between widgets are set relatively to each other, so there is no index or such thing. What I want right now is to "break" the circular chain of widgets so that I get a beginning and an end of the chain.
A circular tab order would be:
A - B
| |
D - C
I want (note missing link between A and D):
A - B
|
D - C
which is more like a line instead of a circle:
A - B - C - D
So the user "stops" at one end and has to go back using the other direction.
Update: I have another idea now. What if i reimplement:
bool QWidget::focusNextPrevChild(bool next)
According to the documentation one can use this to implement custom focus behavior.
In my dynamic scenario where buttons in the GUI are adjusted at run-time I will have to overload the function and set, for example, an internal flag allowFocusNext and allowFocusPrev which then ignores the focus request if necessary. I will report back here, when I have tried it. Meanwhile any comments are welcome!? :-)
I found a solution, but it is a bit hacky. The QWidget::setTabOrder will not allow to chain a widget with itself, so this approach won't help (even if you are using focus proxies)
However, you can define a "Focus Forwarder":
class FocusForwarder : public QWidget
{
public:
explicit FocusForwarder(QWidget *proxy) :
QWidget((QWidget *) proxy->parent()),
m_proxy(proxy)
{
setFocusPolicy(Qt::TabFocus);
}
protected:
void focusInEvent(QFocusEvent *) {
m_proxy->setFocus();
}
private:
QWidget *m_proxy;
};
And add them at the beginning and end of you chain:
FocusForwarder *w1 = new FocusForwarder(ui->bA);
FocusForwarder *w2 = new FocusForwarder(ui->bD);
QWidget::setTabOrder(w1, ui->bA);
QWidget::setTabOrder(ui->bA, ui->bB);
QWidget::setTabOrder(ui->bB, ui->bC);
QWidget::setTabOrder(ui->bC, ui->bD);
QWidget::setTabOrder(ui->bD, w2);
Details
For setTabOrder to work, the widgets must be in the same window. To ensure this, the Forwarder is placed in the proxy's parent (in the initializer list).
For this mechanism, the focus direction (Tab or Shit+Tab) does not matter. As soon as a FocusFowarder receives the focus, it will "forward" it to its proxy.
The direction is handled by Qt internally. You just add "sentinels" around your chain.
Use in QtDesigner
When you want to use it in QtDesigner, you'd create a Widget and promote it to the forwarder. As you cannot set the proxy directly, you could add a dynamic property for the proxy's name, like this:
class FocusForwarderDesigner : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString proxyName READ proxyName WRITE setProxyName)
public:
QString proxyName() {
return (m_proxy) ? m_proxy->objectName() : QString::null;
}
void setProxyName(QString name) {
m_proxy = parent()->findChild<QWidget *>(name);
}
explicit FocusForwarderDesigner(QWidget *parent = NULL) :
QWidget(parent) {}
protected:
void focusInEvent(QFocusEvent *) {
if (m_proxy) m_proxy->setFocus();
}
private:
QWidget *m_proxy;
}
In the designer, you would add a string-property with name proxyName and set it to the proxy's name. Don't forget to set the focus policy to Tab Focus in designer.
After some additional thoughts I post an answer to my own question because it is a working solution but it is not ideal. Therefore, I'm still searching for a better one! As a note, my application mainly relies on mouse wheel interactions for changing the focus of widgets.
In my question I mentioned that overriding:
bool focusNextPrevChild(bool next)
could lead to a working system. The "receiving" widget would simply ignore the focus by returning "true" if it is marked as "last item" or "first item" and the "next" parameter would lead to a circular behavior. Although this works for the tab and space+tab key combinations, there are cases where focusNextPrevChild is not called explicitly. In my case it is not called for focus changes related to mouse wheel events.
What I do instead is overriding:
void wheelEvent(QWheelEvent* event)
This gives me direct control over all the focus events related to the mouse wheel. My overridden function looks like this:
void SelectionIconButton::wheelEvent(QWheelEvent* event)
{
bool next = event->delta() > 0;
if (m_IsLastInFocusChain && next) {
event->accept();
return;
}
if (m_IsFirstInFocusChain && !next) {
event->accept();
return;
}
QPushButton::wheelEvent(event);
}
So this system's requirements are:
Each widget has to somehow implement two bools and handle their
state.
Each of those widgets has to be configured either at startup
or in dynamic screens during appliation use
Listening only to
wheelEvent does not allow me to handle tab key and space+tab key
combinations
You see that this solution works but it involves some effort to apply it to a large application. I was thinking about a more general solution. Maybe a global list that is updated when a screen is changing. This global list would then somehow decide if a focus change is allowed or not. Unfortunately, this again is problematic with mouse wheel events because some widgets are "active" and the wheel event does not even want to change focus but alter the value in an input field, for example, instead.
Edit:
I might have to add that the default implementation of QWidget::wheelEvent() and QPushButton::wheelEvent() and many more Qt-Widgets just ignore the event by setting event->ignore().
In my application all those ignored events are caught at a high level widget which then interprets the QWheelEvent and uses its delta to call focusPreNextChild() the right amount of time.

Good design practice concerning MVC view interface

I don't often have to create GUI's but today I do so I was hoping for some design input.
Basically I have a backend which I intend to add a GUI too using the MVC pattern. The issue is I feel whatever class encapsulates the main GUI window is going to have A LOT of state (all of the sub elements); and on top of that it's going to have a lot of setters, and possibly getter, clear, colour, size, position and refresh functions too.
One option is to march ahead with this idea and have a very large public interface which deals with the types the GUI uses (std::string, std::vector<std::string>...) the more control I want over the UI the more public member function I am going to need.
The other option would be to pass the program state to the GUI and have it decide how it display it, I fear doing this would mean it would give me less fine detail control and would break down the separation of concerns and would mean any changes to the representation of the program state would require changes in the GUI too.
Any input on the matter would be of great help.
If it makes any difference this is a C++ gui using an ncurses abstraction.
It sounds like to me you've thought alot about the M and the V, but not much about the C. The pattern should really be called MCV because the whole idea is that the controller IS the bridge between your model (data) and view (GUI). It sounds like you need a controller with most of the functionality you've mentioned.
Simply put though, your model obviously should know nothing about display and your display (view) should not know how to access the model. You need a controller that reads the data (model) and gives instructions to the display (view). If you have user interaction within the view, the controller can interpret that and modify the model as necessary.
The idea is that you never have to change all 3, but if you change the model or the view, you almost always have to update the controller.
Hope that helps...
There is at least one alternative to the giant interface. Instead of having a function that handles each thing (size, font, color, what-to-display, etc...) have a singular function that accepts a "role" and data that represents the role. This requires some sort of wrapper that can contain multiple data types.
QT's QAbstractItemModel Class Reference has a good example:
QVariant QAbstractItemModel::data ( const QModelIndex & index, int
role = Qt::DisplayRole ) const [pure virtual]
What that function will do is return the QVariant that represents the role indicated at the index provided.
The downside of this approach, is you have to know what roles exist, and what they do. QT's default roles are shown here.
I like to have parts of the model able to instrument themselves:
class Model {
private:
int value;
public:
void instrument(Instrumenter& instrumenter);
};
The Instrumenter manages the creation of controls. The model will tell it how it can be controlled and give it access to the data.
void Model::instrument(Instrumenter& instrumenter) {
instrumenter.addRangeController(0, 100, 5, value);
}
Then for different input devices (e.g keyboard, touchscreen) you can create appropriate controls:
class KeyboardInstrumenter : public Instrumenter {
public:
void addRangeController(int min, int max, int increments, int& controlled) {
// create 3 widgets, up arrow, down arrow, and value
}
};
class TouchscreenInstrumenter : public Instrumenter {
public:
void addRangeController(int min, int max, int increments, int& controlled) {
// create slider with min, max and increments
}
};
Instead of passing in the int directly we could have wrapped it in a controlling object, to aid encapsulation.

Do I need to implement my own QAbstractTableModel?

I found this question: How to change the background color for a QTreeView Header (aka QHeaderView)?
I want to be able to set the color for each header section. So the question seen above seems to be my solution!
The solution says "the easiest way to do that is probably to derive a new model from QAbstractItemModel or another model class and reimplement the headerData()". I went and looked at the Qt source tree for QTableWidget, QTableModel, QTableWidgetItem... these classes are supposedly "default models" so I thought they would be a good example and then I would go implement my own QAbstractTableModel.
The 3 files I saw are a whopping 3300 lines of code. That is definitely NOT "the easiest way" IMO!!!
I would like the functionality of QTableWidget but then I want to add the following ability:
horizontalHeader.setSectionColor(index,color)
verticalHeader.setSectionColor(index,color)
Do I really need to inherit/implement QAbstractTableModel if all I want is to change the color of a section header?
Update:
I am not using my own custom view and model classes. I am using the convenience class QTableWidget right now (it is called a convenience class b/c it implements the view and model). The function headerData() is part of the model. The model class, QTableModel, is not accessible via Qt lib/headers so I can't inherit from it.
Update:
I tried creating a new item with background brush QBrush(QColor(Qt::red)) and then setting the table's header with the new item (using QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem *item). I also tried inheriting QTableWidgetItem and overriding the virtual data() method with:
QVariant HeaderItem::data(int role) const
{
if(role==Qt::BackgroundRole) {
return QVariant(QBrush(QColor(Qt::red)));
} else if(role==Qt::ForegroundRole) {
return QVariant(QBrush(QColor(Qt::green)));
} else {
return QTableWidgetItem::data(role);
}
}
I can change the header sections foreground. But when I try to change the header's background brush... nothing happens... it's like the QTableWidgetItem's background brush that I set for the header section is ignored.
Instead of creating model with custom headerData() from scratch create subclass of QTableWidgetItem with desired implementation of QTableWidgetItem::data() and use the instances of this class for QTableWidget::setHorizontalHeaderItem.

Which model to subclass / view to use for a list of custom objects

I don't have enough experience with Qt yet to make a good design choice. Any help by experienced Qt programmers would be very appreciated.
I'm trying to find out which model to subclass, which view to use, what delegate subclassing / extending I should do...
My problem is similar to: I have these zones I would like to display, 1 per row:
class Zone{
//inputs
string country; //edited with a QComboBox
string city; //edited with a QComboBox
int ageMin;
//stored result
int nbInhabitantsOlderThanMin;
}
Here's what I'd like to do, and the design choices each requirements makes me think of:
I would like to display a list of them (--> QListView )
But to display 1 item I need several columns (--> QTableView )
I would like a double click on a row to trigger editing in a custom widget, since nbInhabitantsOlderThanMin can not be edited, and choosing a country restricts the list of cities that can be chosen in the QComboBox (and vice versa in my real example) (--> I should probably use a QDataWidgetMapper (or subclass?) somewhere...)
So whereas the edition of a row should happen in a widget, the display is simple / not custom, and subclassing a delegate (QStyledItemDelegate for instance) (I'm not so sure about this one) doesn't seem to be the right way to have 1 custom widget with many child input widget to edit the 3 fields at the same time.
I think the data to model would favor a model subclassing QAbstractListModel, but the display with many columns compatible with default delegate viewing favors a QAbstractTableModel..
So I don't really know which design to go for. Any experienced help connecting the dots is very welcome :)
QDataWidgetMapper is a slightly different thing. It is a way to display one item from a Model (ex. QStandardItemModel), using custom controls. You can read more about it here, with accompanying snapshots and an example of how to implement one.
While it is certainly cool, I don't think it is what you want here. Mostly because you specified that you want to view your items in a list format. However, you could display all your items in a simple list, double-click which would open a dialog using the QDataWidgetMapper. In which case all you would need to do with a QListView/QListWidget is implement the double-click event.
Still, I personally don't like the added burden of the extra window on a user. I prefer to use popups sparingly. But if you like that approach, then go ahead. This is another example of the QDataWidgetMapper which is pretty nice.
My preferred approach is still to use the QTableView, and provide delegates for the columns that need specialized editing. Here is a great walk-through of all things Model/View. So if you decide to use the QListView or QTableView it will give you a great start. It also talks about how you can create delegates to edit fields however you want.
So, how do you create a custom delegate? Basically, you just inherit from QItemDelegate. There are some examples in the link above, but I'll highlight a few salient points.
QWidget *ComboBoxDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/* option */,
const QModelIndex &index) const
{
QComboBox *editor = new QComboBox (parent);
// Add items to the combobox here.
// You can use the QModelIndex passed above to access the model
// Add find out what country was selected, and therefore what cities
// need to be listed in the combobox
return editor;
}
void ComboBoxDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
int value = index.model()->data(index, Qt::EditRole).toInt();
QComboBox *comboBox= static_cast<QComboBox *>(editor);
int _SelectedItem = // Figure out which is the currently selected index;
comboBox->setCurrentIndex(_SelectedItem);
}
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QComboBox *comboBox= static_cast<QComboBox *>(editor);
comboBox->interpretText();
int value = comboBox->currentIndex();
// Translate the current index to whatever you actually want to
// set in your model.
model->setData(index, value, Qt::EditRole);
}
Fill in the gaps that I left in my example and you have your Delegate.
Now, how to use this in your QTableView:
You can set a delegate for a particular column of your table as follows:
setItemDelegateForColumn(_ColumnIndex, new ComboBoxDelegate(_YourTableModel));
And, if you want to prevent certain columns from being editable:
_YourTableModel->setColumnEditable(_ColumnIndex, false);
Once you have your model set up, everything else should take care of itself.
Hope that helps.
First, you should subclass QAbstractItemDelegate (or QItemDeleage, that could be more convenient), where reimplement createEditor, setEditorData and setModelData.
Than, you should set your own itemDelegate (see QAbstractItemView::setItemDelegate).
It's commonly no difference, what widget to use to present data: It could be either QTreeWidet, or QTreeView, or QTableWidget, or QTableView. Note, that "widgets" are easier to use, than "views", but they are not so powerfull
I just finished something very similar to this in that I needed multiple fields for each object which I wanted in a row. The way I did it, which worked out very well, was to subclass QAbstractListmodel and use a custom ListItem. I kind of faked the columns by having a custom delegate and using some javascript to figure out the size of the largest thing in each field, and then set the column size to that width. I think this is the easiest way of doing it.
For the comment below, zone would inherit from:
class ListItem: public QObject {
Q_OBJECT
public:
ListItem(QObject* parent = 0) : QObject(parent) {}
virtual ~ListItem() {}
virtual QString id() const = 0;
virtual QVariant data(int role) const = 0;
virtual QHash<int, QByteArray> roleNames() const = 0;
signals:
void dataChanged();
};