Qt toolbar/qtoolbutton action never triggered - c++

I have the following piece of code, for some reason, from the UI window, MyActionDock inherited from QToolBar, it is displayed without any problem, when clicked on the button, the button color also changed, but the slots (a1ActionSlot(), and a2ActionSlot()) connected to the signals are never called, feel like the action is never triggered. I'm using Qt 4.7.2. What's wrong with it? Thanks a lot.
I believe the code used to work properly for Qt4.6 or earlier. Don't know when the problem happens.
MyActionDock::MyActionDock (QWidget *parent) :
QToolBar (parent)
{
setOrientation (Qt::Vertical);
setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
setFixedWidth(canvas()->toolsDockWidth());
// ACTIONS
QToolButton * a1btn= new QToolButton (this);
a1btn->setText("Action 1");
a1btn->setIcon(QIcon("a1.png"));
a1btn->setToolTip ("Some action a1");
a1btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
QAction *a1Action = addWidget(a1btn);
connect (a1Action , SIGNAL (triggered()), this, SLOT(a1ActionSlot()));
addAction (a1Action);
QToolButton * a2Btn = new QToolButton (this);
a2Btn ->setText("A2");
a2Btn ->setIcon(QIcon("a2.png"));
a2Btn ->setToolTip ("something");
QAction *a2Action= addWidget(a2Btn );
connect (a2Action, SIGNAL (triggered()), this, SLOT(a2ActionSlot()));
addAction (a2Action);
}
void MyActionDock::a1ActionSlot()
{
//do something
}
void MyActionDock::a2ActionSlot()
{
//do something
}

As Jay suggested, directly connect to the QToolButton and don't addAction, then it works. Think this is a Qt upgrade related problem. The code used to work in Qt 4.6 or earlier, but it stopped working after 4.7. So for 4.7 if you want to use QToolButton, direct connect the button's signal.
QToolButton * a2Btn = new QToolButton (this);
a2Btn ->setText("A2");
a2Btn ->setIcon(QIcon("a2.png"));
a2Btn ->setToolTip ("something");
addWidget(a2Btn );
connect (a2Btn , SIGNAL (clicked()), this, SLOT(a2ActionSlot()));

The slot is in the wrong class.
You declare the slot a1ActionSlot is in the class MyActionDock here:
connect (a1Action , SIGNAL (triggered()), this, SLOT(a1ActionSlot()));
The third parameter is 'this' (which points to the MyActionDock class).
You instantiate the a1ActionSlot method in the class QtCanvasActionDock.
void QtCanvasActionDock::a1ActionSlot()

Related

Qt error - Cannot send events to objects owned by a different thread,that is corrected by MouseTracking

I am programming with Graphics View Framework. I use a customized class which inherit from QGraphicsView to show QGraphicsScene. I new QGraphicsScene in main thread and new QGraphicsItem in another thread. When I call scene.addItem()--here QT will emit signal to scene and it is not allowed by QT. But if I write setMouseTracking(true) in my QGraphicsView that would correct the QT's error. Why?
My code:
//centralWidget.cpp
pGraphicsScene_ = new QGraphicsScene(this);
pMonitorView_ = new MonitorView(pGraphicsScene_);
//monitorView.cpp
MonitorView::MonitorView(QGraphicsScene *scene, QWidget *parent):
QGraphicsView(scene, parent)
{
setMouseTracking(true);//If I comment this line,will get error--for this I don't confuse but write this statement will correct error!
}
//another thread start by std::thread
pItem = new GoodsItem();
pGraphicsScene_->addItem(pItem);

C++ GUI how to use private data from one window in the second one

I have got problem in Qt. I have to make two windows:
In the first one you can click on 10 buttons and each button have to add an item(name of the button) in comboBox in the second window. But I can't refer to this comboBox. I am out of any ideas :(
I tried to make the variable protected and public, but it doesn't work. I had included window2.h to window1 and I'm trying to do something like this:
//this is in window1
void window1::on_button1_clicked() {
window2::combo->addItem("button1");
}
You can connect the button's click signals to a slot in the second window. This slot will add the information to the combobox.
To do that, you will need to distinguish the signals from each other. The best way to do this is to use a QSignalMapper.
class window1 {
Q_OBJECT
... // your other definitions...
QSignalMapper* signalMapper;
};
window1::window1 (/*your constructor's parameters*/) {
signalMapper = new QSignalMapper(this); // Will map each buttons' signals to a signal with a QString parameter.
// You can do an iteration instead of this if your buttons are on a container.
signalMapper->setMapping(button1, QString("button1"));
signalMapper->setMapping(button2, QString("button2"));
// ...
signalMapper->setMapping(button10, QString("button10"));
// Same comment as above applies here.
connect(button1, SIGNAL(clicked()),
signalMapper, SLOT(map());
connect(button2, SIGNAL(clicked()),
signalMapper, SLOT(map());
// ...
connect(button10, SIGNAL(clicked()),
signalMapper, SLOT(map());
connect(signalMapper, SIGNAL(mapped(QString)),
window2, SLOT(updateCombo(QString)));
}
class window2 {
Q_OBJECT
... // your other definitions...
public slots:
void updateCombo(QString);
};
void window2::updateCombo(QString str) {
combo->addItem(str);
}
Alternatively to the QSignalMapper approach you could name the button objects in window1 (setName("buttonXYZ")), connect the clicked signals to a slot in window2 and ask for the object name of the sender (sender()->name()).
So in the receiving slot you could do :
m_combo->addItem(sender()->name());
or
if(sender()->name() == "Button1") {
m_combo->addItem("Foo");
}

How does QSignalMapper work?

After my post here : Associate signal and slot to a qcheckbox create dynamically I need to associate :
• The signal clicked() when I click on a qCheckBox to my function cliqueCheckBox(QTableWidget *monTab, int ligne, QCheckBox *pCheckBox)
To do so, I have to use QSignalMapper, after two hours of trying to understand how it works, I can't have a good result, here's the code I make, this is obviously wrong :
QSignalMapper *m_sigmapper = new QSignalMapper(this);
QObject::connect(pCheckBox, SIGNAL(mapped(QTableWidget*,int, QCheckBox*)), pCheckBox, SIGNAL(clicked()));
QObject::connect(this, SIGNAL(clicked()), this, SLOT(cliqueCheckBox(QTableWidget *monTab, int ligne, QCheckBox *pCheckBox)));
m_sigmapper->setMapping(pCheckBox, (monTab,ligne, pCheckBox));
QObject::connect(m_sigmapper, SIGNAL(clicked()),this, SLOT(cliqueCheckBox(QTableWidget *monTab, int ligne, QCheckBox *pCheckBox)));
Can you explain to me, how QSignalMapper works ? I don't really understand what to associate with :(
QSignalMapper class collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal. So you can have one like:
QSignalMapper * mapper = new QSignalMapper(this);
QObject::connect(mapper,SIGNAL(mapped(QWidget *)),this,SLOT(mySlot(QWidget *)));
For each of your buttons you can connect the clicked() signal to the map() slot of QSignalMapper and add a mapping using setMapping so that when clicked() is signaled from a button, the signal mapped(QWidget *) is emitted:
QPushButton * but = new QPushButton(this);
QObject::connect(but, SIGNAL(clicked()),mapper,SLOT(map()));
mapper->setMapping(but, but);
This way whenever you click a button, the mapped(QWidget *) signal of the mapper is emitted containing the widget as a parameter.
First I will explain you how QSignalMapper works. Then I will explain you why you don't need it.
How QSignalMapper works:
Create s QSignalMapper. Lets assume that you want to assign an integer value to each checkbox, so every time you click on any checkbox, you will get a signal with the integer value assigned to it.
Connect the mapper signal to your SLOT, that you will implement:
connect(mapper, SIGNAL(mapped(int)), this, SLOT(yourSlot(int)));
Now you can write slot, that will take integer argument. The argument will be different for each checkbox you have.
While you create checkboxes, for each checkbox you need to do following:
mapper->setMapping(checkBox, integerValueForThisCheckbox);
connect(checkBox, SIGNAL(clicked()), mapper, SLOT(map()));
From now on, every time you click on a checkbox, it will emit clicked() signal to the QSignalMapper, which will then map it to the assigned integer value and will emit mapped() signal. You connected to that mapped() signal, so yourSlot(int) will be called with the proper integer value.
Instead of integers, you can assign QString, QWidget* or QObject* (see Qt documentation).
This is how QSignalMapper work.
You don't need it:
The QTableWidget *monTab is the single object, it doesn't change. Keep it as a class member field and use it from your slot function.
The QCheckBox *pCheckBox - you can get it by casting sender() to QCheckBox*.
Like this:
void supervision::yourSlot()
{
QCheckBox* pCheckBox = qobject_cast<QCheckBox*>(sender());
if (!pCheckBox) // this is just a safety check
return;
}
The sender() function is from QObject, which you do inherit from, so you have access to it.
The int linge (it's a line number, right?) - when you create checkboxes, you can store pointers to that checkboxes in QList class field and use it from your slot function find out which line is it, like this:
In class declaration:
private:
QList<QCheckBox*> checkboxes;
When creating checkboxes:
QCheckBox* cb = new QCheckBox();
checkboxes << cb;
In your slot function:
void supervision::yourSlot()
{
QCheckBox* pCheckBox = qobject_cast<QCheckBox*>(sender());
if (!pCheckBox) // this is just a safety check
return;
int linge = checkboxes.indexOf(pCheckBox);
}
If you want, you can skip that QList and use QSignalMapper and assign lines to checkboxes using mapper. That's just a matter of what you prefer.

MDI window and QSignalMapper basics

First of all my apologies for big looking question but indeed it's not. I’m reading Foundation of qt development book and while reading fourth chapter author tells the basics of MDI window by showing this example :
MdiWindow::MdiWindow( QWidget *parent ) : QMainWindow( parent ) {
setWindowTitle( tr( "MDI" ) );
QWorkspace* workspace = new QWorkspace;
setCentralWidget( workspace );
connect( workspace, SIGNAL(windowActivated(QWidget *)), this, SLOT(enableActions()));
QSignalMapper* mapper = new QSignalMapper( this );
//my problem is in this line
connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );
createActions();
createMenus();
createToolbars();
statusBar()->showMessage( tr("Done") );
enableActions();
}
His this para of explanation completely eluded me (is it me or others having problem understanding it too?) :
Next, a signal mapping object called QSignalMapper is created and
connected. A signal mapper is used to tie the source of the signal to
an argument of another signal. In this example, the action of the menu
item corresponding to each window in the Window menu is tied to the
actual document window. The actions are in turn connected to mapper.
When the triggered signal is emitted by the action, the sending action
has been associated with the QWidget* of the corresponding document
window. This pointer is used as the argument in the mapped(QWidget*)
signal emitted by the signal mapping object.
My question : I still don’t get what is signal mapper class, how it’s used and what's functionality it's doing in the example above?. Can anyone please explain the above para using easy terms? also It’d be awesome if you could please teach me about mapper class’s basics with simple example? possibly in layman’s term?
P.S : A confusion is when we have MDI window, do menu changes (though actions are disabled/enabled) e.g suppose for one particular document we have menu “File/close” and for other document we have “File/remaper” ?
The QSignalMapper is used to re-emit signals with optional parameters. In other words (from the documentation):
This class collects a set of parameterless signals, and re-emits them
with integer, string or widget parameters corresponding to the object
that sent the signal.
A good example (also from the doc - take a look at it) is set as follows:
Suppose we want to create a custom widget that contains a
group of buttons (like a tool palette). One approach is to connect
each button's clicked() signal to its own custom slot; but in this
example we want to connect all the buttons to a single slot and
parameterize the slot by the button that was clicked.
So imagine you have a number of buttons encapsulated in a class, say ButtonWidget, with a custom signal void clicked(const QString &text). Here is the definition:
class ButtonWidget : public QWidget {
Q_OBJECT
public:
ButtonWidget(QStringList texts, QWidget *parent = 0);
signals:
void clicked(const QString &text);
private:
QSignalMapper *signalMapper;
};
The constructor could then be defined like the following:
ButtonWidget::ButtonWidget(QStringList texts, QWidget *parent)
: QWidget(parent)
{
signalMapper = new QSignalMapper(this);
QGridLayout *gridLayout = new QGridLayout;
for (int i = 0; i < texts.size(); ++i) {
QPushButton *button = new QPushButton(texts[i]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, texts[i]);
gridLayout->addWidget(button, i / 3, i % 3);
}
connect(signalMapper, SIGNAL(mapped(const QString &)),
this, SIGNAL(clicked(const QString &)));
setLayout(gridLayout);
}
So what happens here? We construct a grid layout and our buttons of type QPushButton. The clicked() signal of each of these is connected to the signal mapper.
One of the forces using QSignalMapper is that you can pass arguments to the re-emitted signals. In our example each of the buttons should emit a different text (due to the definition of our signal), so we set this using the setMapping() method.
Now all that's left to do is map the signal mapper to the signal of our class:
connect(signalMapper, SIGNAL(mapped(const QString &)),
this, SIGNAL(clicked(const QString &)));
Assume we have a testing class called TestClass then ButtonWidget can be used thusly:
TestClass::TestClass() {
widget = new ButtonWidget(QStringList() << "Foo" << "Bar");
connect(widget, SIGNAL(clicked(const QString &)),
this, SLOT(onButtonClicked(const QString &)));
}
void TestClass::onButtonClicked(const QString &btnText) {
if (btnText == "Foo") {
// Do stuff.
}
else {
// Or something else.
}
}
By using the signal mapper this way you don't have to declare and manage all the buttons and their clicked signals, just one signal pr. ButtonWidget.
The buttom line is that the signal mapper is great for bundling multiple signals and you can even set parameters when it re-emits them. I hope that gave some intuition about the usage of QSignalMapper.
Your example code
The explanation (your "para") states that all the actions are each individually mapped to a specific QWidget*. When triggering an action its respective QWidget* will be passed to the slot QWorkspace::setActiveWindow(QWidget*) of workspace, which in turn activates the widget.
Also note that the mapping from action to widget has to happen somewhere in your code. I assume it is done in createActions() or enableActions() perhaps.
A QSignalMapper allows you to add some information to a signal, when you need it. This object internally have a map like QMap<QObject*,QVariant>. Then you connect an object to it, and when the slot is called, it re-emit the signal with the associated value.
Workflow:
mySignalMapper:
[ obj1 -> 42 ]
[ obj2 -> "obiwan" ]
[ obj3 -> myWidget ]
connect(obj1,mySignal,mySignalMapper,SLOT(map())); // idem for obj2 and obj3
(obj2 emits "mySignal")
-> (mySignalMapper::map slot is called)
-> (sender() == obj2, associated data = "obiwan")
-> (mySignalMapper emits mapped("obiwan"))
I was going to add a more detailed example, but Morten Kristensen was faster than me ;)

How to make QDialogButtonBox NOT close its parent QDialog?

I have a QDialog with a QDialogButtonBox widget, and I've connected the button box's accepted signal to a slot in my QDialog subclass, like so:
void MyDialog::on_buttonBox_accepted()
{
QString errorString = this->inputErrorString();
if (errorString.isEmpty())
{
// Do work here
// code code code...
this->accept();
}
else
{
QMessageBox::critical(this, tr("Error"), tr("The following input errors have occurred:") + errorString);
}
}
However, the dialog is closes after the message box is displayed; apparently the button box automatically connects its accepted signal to QDialog's accept slot (I want to call that slot manually). How can I prevent this so I can take the manual approach outlined above?
You can implement MyDialog::accept(). The function is virtual in QDialog.