QTreeWidget; Disabling ui Features when multiple Items are selected in QTree - c++

I'm a student programmer and I am using Qt to build a GUI for work and I have ran into an issue of sorts. In my main interface I have a QTreeWidget that holds data. Also in this GUI I have the buttons Edit, copy, and delete which are already perspectively connected to functions. I would like the edit button to be disabled when multiple items are selected. Here is where I am having my issue. I assume that the best way to do this (once again I am a student) would be some type of connect statement but I have been looking through the Qt Documentation for this widget and cant find anything that seems right for this. I was hoping someone more experienced to be able to provide some direction with this.
I was wondering if I should/can use
void QTreeWidget::itemSelectionChanged () [signal]
If I could use this signal please shed some light because I'm hitting a blank here as I wouldn't know where to begin to relate it to multiple items being selected.

Yea this is the right signal. For example here is trivial implementation of the slot for your question:
void disableItems() {
QList<QTreeWidgetItem*> selection = treeWidget->selectedItems();
if(selection.size() > 1) {
//disable the gui items here
} else {
//maybe reenable items otherwise
}
}

I don't think you can do it solely in QtDesigner, if that's what you're trying to do.
You could define you own slot to handle itemSelectionChanged signal. In that slot you can use selectedItems method of QTreeWidget to check the number of selected items and enable/disable buttons based on that.

Related

QComboBox::showPopup() steals focus from its QLineEdit

In order to create a QComboBox that can filter its values list when typing in it, I attached a slot to the QComboBox's editTextChanged-event, to open its list view popup when the user starts typing. This is done like so:
void SearchableComboBox::slotEditing(QString in_text)
{
this->showPopup();
}
Unfortunately, this immediatly steals the focus from the QLineEdit and I can't type anymore.
Calling lineEdit()->setFocus() makes no difference, and I don't want to grabKeyboard() since this creates a whole other world of pain.
Any recommendations?
This isn't really a combobox then, more of a completion listview for a lineedit. I implemented exactly that in ruqola (KDE client for rocket chat), you can see the source code at https://lxr.kde.org/source/network/ruqola/src/widgets/common/completionlistview.cpp. Notice the little dance with the focus proxy thing:
setFocusPolicy(Qt::NoFocus);
textWidget->setFocusPolicy(origPolicy);
setFocusProxy(textWidget);
and the long method slotCompletionAvailable() for positioning the completion popup at the right place...
Use the Focus Proxy method for this purpose. See https://doc.qt.io/qt-5/qwidget.html#setFocusProxy
With this the pop-up would relay its inputs to the lineedit.
In your case you could try something like
this->setFocusProxy( this->lineEdit() );
But maybe you should read how to use a QCompleter. This would provide Autocompletion while typing and is maybe also useful for you.

How to get UI objects to only appear in dialog AFTER button is clicked

I have a dialog that initially has several buttons, let's call them Write, View, OK, and Cancel.
The way it should to is to have the dialog upon creation only have those three buttons and nothing more.
When the Write button is cancelled, it's supposed to create a QLineEdit object in the window above the buttons where the user can enter a new string,which when OK is then clicked will be added to an external QStringList.
When View is clicked, LineEdit should go away (if it's up) and a QListView to come up instead to view everything in that list.
The problem is, I know how to use hide() to get objects that are already in the dialog to NOT appear.
but I am having trouble figuring out how to get an object not currently on the table to appear. I'm new to using Qt so it may be something easy I'm just accidentally overlooking (in fact I hope it is).
Could anyone please offer advice? Thanks!
Just create the items normally and then set:
ui->control->setVisible(false);
after you have created the UI (after ui->setupUi(this);) possibly in the constructor (in case you use code generated by Qt Creator).
And when you need them:
ui->control->setVisible(true);
Doc for this:
http://qt-project.org/doc/qt-4.8/qwidget.html#visible-prop
when using a QListView you should also have a QListModel that provides the data to it, if you only have QStrings then a QStringListModel is premade for you to use
to add a row you can do:
int rows = model->rowCount();
model->addRow(rows,1);
QModelIndex index = model->index(rows,0);
model->setData(index, string);

Qt Signal Slot Architecture Unwanted Infinite Loop

I've problem with qt signal-slot system.
First I've created a class which is called System in Singleton pattern, so I can access it's instance where I want. System has a signal SelectionChanged.
I've a list widget and I am connecting it's itemSelectionChanged signal to my custom slot which is called onSelectionChanged. In onSelectionChanged slot, I am emitting System's SelectionChanged signal. There is no problem yet.
In my software design, a selection of object(s) can be used by many GUI widgets or custom classes and System's SelectionChanged signal can be emited by widgets other then the list widget.
So I am creating a slot called OnSystemSelectionChanged in the list widget then connect it to the System's SelectionChanged signal. The OnSystemSelectionChangedSlot is like this.
void MyListWidget::OnSystemSelectionChanged(QObject *sender)
{
if (sender == this) return;
// Then I want to get a list of selected objects and set them as selection of this widget like this:
this->SetSelection(System::Instance()->GetSelectedObjects());
}
But the problem is when I start to set the list widget's selected items, it is going to emit itemSelectionChanged signal and my onSelectionChanged slot will be called. Then the slot will emit System's SelectionChanged signal and then OnSystemSelectionChanged will be called too. It will stop through sender parameter but there is no method for setting list widget's selected items at once.
How can I figure this problem out.
I hope I did explain my problem well. Thanks in advance.
Edit: Spelling and grammer errors are corrected.
There are a few ways of dealing with this in Qt.
Idioms
Use multiple views with one underlying model. This handles propagation of changes to multiple view controls automatically and you don't need to do anything extra. You can use QDataWidgetMapper to link "plain old" widgets to the data elements in a model. I'd say that this should be the preferred way of doing things. Having an underlying model for all of your UI is a step in the direction of good software design anyway.
When propagating changes between data models, implement both a DisplayRole and an EditRole. The views will nominally modify the models using one of the roles (say, the EditRole), while you can, programmatically, modify the models using the other role (say, the DisplayRole). You handle the dataChanged signals from the model in your own slot, properly dealing with the roles, and call setData on the other models with the other role. This prevents the loops.
For controls that are not QAbstractItemViews, implement two signals: one emitted on any change, another one emitted only on changes based on keyboard/mouse input. This is the interface exposed by QAbstractButton, for example: the toggled(bool) signal is the former, the clicked() is the latter. You then only connect to the input-based signals.
Your own code must propagate programmatic changes to all the interlinked controls, since changing one control from your code won't modify the others. This should not be a problem, since well designed code should encapsulate the implementation details of UI controls from rest of the code. Your dialog/window class will thus expose its properties in a way that's not coupled to the number of controls showing a particular property.
Hackish Let's-Hope-They-Won't-Become Idioms
Use a flag inhibiting signal emission (Bartosz's answer).
Break the signal/slot connections for the duration of the change (Bartosz's answer).
Use QObject::blockSignals().
There are two possible solutions I can think of:
add a flag which makes possible to ignore particular signals:
void MyListWidget::OnSystemSelectionChanged(QObject *sender)
{
if (sender == this || inhibitSelectionChanged)
return;
this->inhibitSelectionChanged = true;
this->SetSelection(System::Instance()->GetSelectedObjects());
this->inhibitSelectionChanged = false;
}
disconnect the slot from the signal, and reconnect it after changing the selection:
void MyListWidget::OnSystemSelectionChanged(QObject *sender)
{
if (sender == this)
return;
this->disconnect(SIGNAL(SelectionChanged()));
this->SetSelection(System::Instance()->GetSelectedObjects());
this->connect(
this, SIGNAL(SelectionChanged()),
this, SLOT(OnSystemSelectionChanged(QObject*)));
}
I found my solution in QObject::blockSignals() method. It will prevent emitting signals from the list widget while I am setting selected items.
Thanks for all the answers and solutions especialy for BartoszKP's. This solution is looks like the official way of his first solution.
The problem: you've tried to cut corners and created a singleton. Not a classic case for singleton.
Signals and slots are used for notifications, each object notifies interested objects about what it did or to reflect its new state.
I'm suggesting changing the design as follows:
No singleton signal.
Each Object has its own signal and slot for a relevant event (e.g. selection change).
The application or a higher level object (that created the widgets/objects) performs the signal to slot connection. If those widgets are placed in a list, this is very simple.

Move QToolButton to different layouts by just pressing it?

I have here two different layouts, and one QToolButton. My goal is to transfer that button between the two layouts when I click it. I figured this code would work,
snippet:
void DominionLinux::on_toolButton_clicked(string state)
{
if (state=="Disabled"){
ui->verticalLayout_Enabled->addWidget(ui->toolButton);
state = "Enabled";
}
else if (state=="Enabled"){
ui->verticalLayout_Disabled->addWidget(ui->toolButton);
state = "Disabled";
}
}
By default, state == "Disabled". When I test the UI in QTCreator, the first time I click, it works; the button dissapears from one template, and appears on the other. The second time I click when its on the other template, it doesn't. When compiling, I get this warning:
*QMetaObject::connectSlotsByName: No matching signal for on_toolButton_clicked(string)*
Any ideas why the slot stops working?
Any ideas why the slot stops working?
You are missing the signal declaration at the place of the connect as the warning also hints. Also, it seems that you are passing either the slot as the signal to the connect method. A signal should not have the same name as a slot in a Qt application.
Other than that, you may wanna reconsider your design about disabling and enabling a button. Putting them into separate layers is not the appropriate way of doing it.
Moreover, you should probably avoid raw strings for representing states in general. It is better to use enumerations, or boolean for "toggle states".

Qt/C++: Signal for when a QListWidgetItem is checked?

In my form I have a QListWidget which contains checkable QListWidgetItems. I'm looking for a way to capture the event of a QListWidgetItem being checked/unchecked. I don't see any such signal existing for this but maybe I'm wrong. What I'm currently doing is using the QListWidget::itemClicked() signal and checking the checkState of the QListWidgetItem, but this isn't what I want because this event happens any time the item is clicked, not just went the checkmark is toggled. Can anyone give some assistance? Thanks!
Apparently no such signal is provided, your best bet is to use QListWidget::itemChanged(QListWidgetItem* item) , and scan the resulting item->checkState(). This should be a slight improvement over using itemClicked
An extra option is to use your own QAbstractListModel with a QListView. At first this does add some extra code as you need to add your own management code . But you do get a lower level access. Basically because the QListView will ask your model what to do. It will also relay input back to your listmodel where you can hook into it.
Alternatively you could subclass QStandardItemModel and catch certain edits related to changing the checkbox.