Qt Signals & Slots: How do I get the data which was changed? - c++

I have a QStandardModel. I connect its itemChanged signal to my own slot.
m_model = new QStandardItemModel(this);
connect(m_model, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(changed(QStandardItem*)));
The slot looks like this:
void Class::changed(QStandardItem * item) {
// ui->pushButton->setText("change");
QString name = item->parent()->data().toString();
ui->pushButton->setText(item->data().toString());
}
The pushButton text will change to "change", so my slot seems to work. However, item->data().toString() is always empty.
How do I do this right?

I think you should use QStandardItem::text() method. Like this: QString name = item->parent()->text();

Related

Qt push button is calling 2 slots and I only need one

I need to call a 2 functions with different buttons
I have this code:
signalMapperSelections = new QSignalMapper();
QPushButton *selected_type_button = new QPushButton();
selected_type_button->setObjectName("selected_type_button");
selected_type_button->setText(get_selected_type().replace(" ", "\n"));
selected_type_button->setMinimumHeight(80);
selected_type_button->setMinimumWidth(80);
selected_type_button->setMaximumHeight(80);
selected_type_button->setMaximumWidth(80);
selected_type_button->setStyleSheet(style_toolbutton);
ui->verticalLayout_selections->addWidget(selected_type_button);
connect(selected_type_button, SIGNAL(clicked()), signalMapperSelections, SLOT(map()));
signalMapperSelections->setMapping(selected_type_button, get_selected_type());
connect(signalMapperSelections, SIGNAL(mapped(QString)), this, SLOT(show_brands(QString)));
QPushButton *selected_brand_button = new QPushButton();
selected_brand_button->setObjectName("selected_brand_button");
selected_brand_button->setText(get_selected_brand().replace(" ", "\n"));
selected_brand_button->setMinimumHeight(80);
selected_brand_button->setMinimumWidth(80);
selected_brand_button->setMaximumHeight(80);
selected_brand_button->setMaximumWidth(80);
selected_brand_button->setStyleSheet(style_toolbutton);
ui->verticalLayout_selections->addWidget(selected_brand_button);
connect(selected_brand_button, SIGNAL(clicked()), signalMapperSelections, SLOT(map()));
signalMapperSelections->setMapping(selected_brand_button, get_selected_brand());
connect(signalMapperSelections, SIGNAL(mapped(QString)), this, SLOT(show_models(QString)));
When I click "selected_type_button" I only want to run "show_brands". But it's running both functions, "show_brands" and "show_models"...
I tried Qt::UniqueConnection, but it doesn't fix this problem.
I think this is happening because both buttons are using the same signal... But I don't know how to fix it.
How can I fix this?
When I click "selected_type_button" I only want to run "show_brands".
There is no reason to use QSignalMapper in your situation at all. You just have to connect clicked signal from selected_type_button to the show_brands slot, and clicked signal from selected_brand_button to the show_models slot.
QString is the selected type or selected brand....
This QString argument has nothing to do with the clicked signal's source (So, it does not need any mapping using QSignalMapper, read about QSignalMapper in the docs here). The mapping you are currently using is set up at the connection time (not at emit time) , this means that get_selected_type()/get_selected_brand() will return the selected items at the time of calling setMapping (this is obviously not what you meant).
To get the item at the time of clicking the button, you can call your get_selected_type()/get_selected_brand() functions in your slots directly, your code will be something like this:
QPushButton *selected_type_button = new QPushButton();
selected_type_button->setObjectName("selected_type_button");
selected_type_button->setText(get_selected_type().replace(" ", "\n"));
selected_type_button->setMinimumHeight(80);
selected_type_button->setMinimumWidth(80);
selected_type_button->setMaximumHeight(80);
selected_type_button->setMaximumWidth(80);
selected_type_button->setStyleSheet(style_toolbutton);
ui->verticalLayout_selections->addWidget(selected_type_button);
//Qt 5 new connect syntax (replace ClassName with the current class's name)
connect(selected_type_button, &QPushButton::clicked, this, &ClassName::show_brands);
QPushButton *selected_brand_button = new QPushButton();
selected_brand_button->setObjectName("selected_brand_button");
selected_brand_button->setText(get_selected_brand().replace(" ", "\n"));
selected_brand_button->setMinimumHeight(80);
selected_brand_button->setMinimumWidth(80);
selected_brand_button->setMaximumHeight(80);
selected_brand_button->setMaximumWidth(80);
selected_brand_button->setStyleSheet(style_toolbutton);
ui->verticalLayout_selections->addWidget(selected_brand_button);
//replace ClassName with the current class's name)
connect(selected_brand_button, &QPushButton::clicked, this, &ClassName::show_models);
and your show_brands slot should look something like:
//no need for the QString argument
void ClassName::show_brands(){
QString selectedType= get_selected_type();
//show_brands here
}
the same thing for show_models slot:
void ClassName::show_models(){
QString selectedBrand= get_selected_brand();
//show_models here
}

Changing data in a QTableView depending on the selection of a QComboBox

I have a QComboBox in one of the columns of a QTableView. How can I change the other columns depending on what I selected in the ComboBox? I am using the QComboBox as a delegate.
There are at least 2 approaches.
Use natural for Qt's model itemChanged signal.
emit signal from your delegate and catch it inside your main window.
If your delegate is standard which means that inside setModelData() method you have something like:
QComboBox *line = static_cast<QComboBox*>(editor);
QString data = line->currentText();
//...
model->setData(index, data);
then I think you should use just natural way. For example:
connect(model,&QStandardItemModel::itemChanged,[=](QStandardItem * item) {
if(item->column() == NEEDED_COLUMN)
{
//you found, just get data and use it as you want
qDebug() << item->text();
}
});
I used here C++11 (CONFIG += c++11 to .pro file) and new syntax of signals and slots, but of course you can use old syntax if you want.
I already reproduced your code(delegate with combobox) and my solution works if I select something in combobox and confirm that by enter clicking for example. But if you want to get solution where data will be changed automatically, when you select another item in combobox(without pressing enter) then see next case:
Create special signal onside delegate:
signals:
void boxDataChanged(const QString & str);
Create connection inside createEditor() method:
QWidget *ItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QComboBox *editor = new QComboBox(parent);
connect(editor,SIGNAL(currentIndexChanged(QString)),this,SIGNAL(boxDataChanged(QString)));
return editor;
}
And use it!
ItemDelegate *del = new ItemDelegate;
ui->tableView->setItemDelegate( del);
ui->tableView->setModel(model);
connect(del,&ItemDelegate::boxDataChanged,[=](const QString & str) {
//you found, just get data and use it as you want
qDebug() << str;
});

Qt, PushButton, id attribute? Any way to know which button was clicked

void MainWindow::addRadioToUI()
{ int button_cunter=4;
while(!database.isEmpty())
{ button_cunter++;
QPushButton *one = new QPushButton("Play: "+name(get_r.getTrackId()));
one->setIcon(QIcon(":/images/play_button.png"));
one->setMaximumWidth(140);
one->setFlat(true);
QGroupBox* get_rGB = new QGroupBox("somethink");
QFormLayout* layout = new QFormLayout;
if(button_cunter%5 == 0){
layout->addWidget(one);
}
get_rGB->setLayout(layout);
scrollAreaWidgetContents->layout()->addWidget(get_rGB);
}
}
I have a few QPushButtons which are added automaticlly.
Is there a way to add "id attribute or sth else" to button and next know which button was clicked? I have different action for each button.
QApplication offers sender() which contains which object sent the signal. So you can do:
//slot, this could also be done in a switch
if(button[X] == QApplication::sender()){
doX();
}else if(button[Y] == QApplication::sender()){
doY();
}
http://doc.qt.io/qt-4.8/qobject.html#sender
QSignalMapper is pretty good for this type of thing.
You would define your slot like this for instance:
public slots:
void clicked(int buttonId); // or maybe trackId
Then add a QSignalMapper* member to your class and connect it to that slot:
signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)),
this, SLOT(clicked(int)));
In the addRadioToUI, after creating your push button, do:
signalMapper.setMapping(one, button_cunter);
// or trackId if that's more practical
If all you need is a pointer to the object that triggered the signal though, you can use the static QOjbect::sender function in your slot to get a handle to that.
Use QButtonGroup. It takes id as a parameter when a button is added and provides the id to a slot when a button in the group is pressed.

Problem with QSignalMapper and QAction never triger the Slot

Hi i try to bind slot with argument to QAction triggered SIGNAL
i have this code ,the context menu working great . BUT the OpenPublishWin never triggered .
void MyApp::ShowContextMenu(const QPoint& pos) // this is a slot
{
QString groupID;
QPoint globalPos = ui.treeView_mainwindow->mapToGlobal(pos);
QModelIndex modelIndx = ui.treeView_mainwindow->indexAt(pos);
groupID = modelIndx.model()->index(modelIndx.row(),0,modelIndx.parent()).data(Qt::UserRole).toString();
QMenu myMenu;
OpenPublishAction = new QAction(tr("Send"), this);
myMenu.addAction(OpenPublishAction);
connect(OpenPublishAction, SIGNAL(triggered()),m_SignalMapper, SLOT(map()) );
m_SignalMapper->setMapping(OpenPublishAction,groupID);
connect(m_SignalMapper, SIGNAL(mapped(QString)), this, SLOT(OpenPublishWin(QString)));
QAction* selectedItem = myMenu.exec(globalPos);
}
void MyApp::OpenPublishWin(QString gid)
{
WRITELOG(gid)
}
A quick look at the Qt docs for QSignalMapper (assuming that is what you're using based on the question title) states that the parameter for the mapped signal is const QString&. I can't recall if the parameter needs to be exact in this case for the connection but it may be a factor.
Additionally, double check that your connects are being made by wrapping them in an assert or some form of verify. Qt will also print out to the console if a connection cannot be made.

QSignalMapper and original Sender()

I have a bunch of QComboBoxes in a table. So that I know which one was triggered I remap the signal to encode the table cell location (as described in Selecting QComboBox in QTableWidget)
(Why Qt doesn't just send the cell activated signal first so you can use the same current row/column mechanism as any other cell edit I don't know.)
But this removes all knowledge of the original sender widget. Calling QComboBox* combo = (QComboBox* )sender() in the slot fails, presumably because sender() is now the QSignalMapper.
I can use the encoded row/column to lookup the QComboBox in the table widget but that seems wrong. Is there a more correct way to do it?
e.g.:
// in table creator
_signalMapper = new QSignalMapper(this);
// for each cell
QComboBox* combo = new QComboBox();
connect(combo, SIGNAL(currentIndexChanged(int)), _signalMapper, SLOT(map()));
_signalMapper->setMapping(combo, row);
// and finally
connect(_signalMapper, SIGNAL(mapped(int)),this, SLOT(changedType(int)));
// slot
void myDlg::changedType(int row)
{
QComboBox* combo = (QComboBox* )sender(); // this doesn't work !!
}
EDIT: Added for future search: there is a new book "Advanced Qt Programming" by Mark Summerfield that explains how to do this sort of thing.
Why not connect the QComboBox's signal straight to your slot?
QComboBox *combo = ...
connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changedType(int)));
And then in your slot you can use the sender() method to retrieve the QComboBox that was changed.
void myDlg::changedType(int row)
{
QComboBox *combo = qobject_cast<QComboBox *> sender();
if(combo != 0){
// rest of code
}
}
Alternatively, to use the QSignalMapper method you would just need to change your slot to use the mapping you set up:
void myDlg::changedType(int row)
{
QComboBox *combo = qobject_cast<QComboBox *>(_signalMapper->mapping(row));
if(combo != 0){
// rest of code
}
}
I don't know exact answer, but maybe you should use: QComboBox* combo = qobject_cast(sender()) instead of QComboBox* combo = (QComboBox* )sender(). Someting like this:
QObject* obj = sender();
QComboBox* combo = qobject_cast<QComboBox*>(obj);
if(combo)
{
doSomethingWithCombo(combo);
}
else
{
// obj is not QComboBox instance
}
But maybe QSignalMapper really substitutes itself instead of real sender...