how to trigger a signal in Qt - qt

I've got an easy GUI window: a QLineEdit with a QPushButton. I want to trigger a signal when when the push button is clicked AND the input is validated (it meets a conditional statement, nevermind the details).
Normally I would use connect (object, signal, subject, slot). I guess that QPushButton clicked should trigger the middle-signal which is handled inside the widget slot. And the widget slot could trigger another signal - to my destination point. But how?

You have to declare your signal in class:
class myClass
{
/* stuff */
public signals:
void mySignal();
}
and in your code after validation:
void myClass::dataValidation()
{
/*validate data*/
emit mySignal();
}

Related

QComboBox: the addItem function trigger index change signal

I am using QComboBox in my project. And I find that the addItem function would trigger currentIndexChanged signal.
The minimum code to reproduce this problem is:
class Test: public QWidget
{
public:
QComboBox * m_box;
Test()
{
m_box = new QComboBox;
connect(m_box, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &Test::IndexChangeSlot);
m_box->addItem("test");
}
public slots:
void IndexChangeSlot(int index)
{
std::cout<<"index changed"<<std::endl;
}
}
Why addItem would trigger currentIndexChanged signal?
How can I avoid this signal caused by addItem?
CurrentIndex was -1 (nothing is selected) and become 0.
To avoid disconnect before adding items and connect back, or use variable to ignore signal temporary, or connect after initialisation.

How to get the result of QDialog::show()?

I want to convert exec usages to show method in my projects. Because, when I use the exec for windows (dialogs) I can not open another window. This is the basic difference between exec() and show() method.
The exec and show work in different ways and I am wondering how can I change the below code with using show() instead of exec().
For example:
int result = exampleWindow->exec();
if ( result == QDialogButtonBox::Ok )
{
exampleWindow->UpdateCalibrationData(&data);
exampleWindow->UpdateFilterData(&filterData);
exampleWindow();
}
show() shows a non-modal window;
exec() shows a modal window.
If you want to get the result of show(), then go with Qt signals/slots:
ExampleWindow::ExampleWindow(QWidget *parent) : QDialog(parent)
{
// Assuming the QDialogButtonBox name is "buttonBox":
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
MainWindow.h:
class MainWindow : public QMainWindow {
Q_OBJECT
private slots:
void updateData();
}
MainWindow.cpp:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
connect(exampleWindow, SIGNAL(accepted()), this, SLOT(updateData()));
}
void MainWindow::updateData()
{
// Your code:
exampleWindow->UpdateCalibrationData(&data);
exampleWindow->UpdateFilterData(&filterData);
exampleWindow();
}
show() simply makes the dialog window visible. It is a QWidget method.
exec(), when provided in a class, always spins an event loop. In case of dialogs specifically, it'll make the dialog visible before spinning the event loop.
You could implement a functionally equivalent exec() yourself, as follows:
void myExec(QDialog * dialog) {
QStateMachine sm;
QState s1(&sm), s2(&sm);
sm.setInitialState(&s1);
QEventTransition transition(dialog, QEvent::Close);
s2.addTransition(&transition);
QEventLoop loop;
QObject::connect(&s2, &QState::entered, &loop, &QEventLoop::quit);
sm.start();
dialog->show();
loop.exec();
}
Generally speaking, you should never use exec() to create a nested event loop, since you're exposing a lot of your own code to possible reentrancy requirements. In case of dialogs, it is always possible to show a modal dialog box without using exec(), so there's really no point to it.
exec() method shows modal dialog as described here
You can use for example closeEvent() of your dialog. In it you can write something like:
void ExmpleWin::closeEvent(QCloseEvent *event)
{
if (/*Your condition*/) {
emit signalUpdateMyData();
event->accept();
}
}
Also you have to connect signal signalUpdateMyData() with apropriate slot where you can make:
exampleWindow->UpdateCalibrationData(&data);
exampleWindow->UpdateFilterData(&filterData);
exampleWindow();

Qt - two signals and modal dialog window

I have a QDialog based class.
I have one QEditLine *editLine and QButton *button.
I use clicked() signal of button. And editingFinished() signal of editLine.
When I change the text in the editLine and press the button firstly editingFinished() signal is emitted. In the slot method I call QMessageBox::question().
After that I can't receive clicked() signal of my button.
I tried to use Qt::QueuedConnection for connect method, but it does not help.
How to solve my problem?
I think the issue is that the event loop for the message box is blocking the main event loop so your button's signal is not emitted. But how do you plan to click the button anyway if you have a modal dialog open?
Here is the code:
Window::Window(QWidget *parent)
: QDialog(parent)
{
setupUi(this);
appPath = QApplication::applicationDirPath();
connect(pButton, SIGNAL(clicked()), this, SLOT(build()), Qt::QueuedConnection);
connect(pLineEdit, SIGNAL(editingFinished()), this, SLOT(pathChanged()), Qt::QueuedConnection);
}
void Window::pathChanged()
{
QString path = pLineEdit->text();
if(createPath(path))
updatePath(path);
}
bool Window::createPath(QString path)
{
if(!QDir(path).exists())
{
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Folder is not exist"), "Folder " + path + " is not exist. Do you want to create it?", QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes)
{
QDir dir;
dir.mkpath(path);
}
}
return true;
}
class Window : public QDialog, public Ui::GLConverterDialogUI
{
Q_OBJECT
public:
Window(QWidget *parent = 0);
~Window(void);
......
}
I have the same problem in another application. I use some library. I guess that this library use pressed() signal of QAbstractButton instead of clicked(). And when I call QFileDialog::getSaveFileName() after button is pressed it seems that mouseReleaseEvent() is also not called. So after closing of dialog button is still pressed and I have to send MouseButtonRealese event manually.
Maybe I should call dialog with some special parameters?

how to access a widget from another class

I have two classes(MyWidget,ViewContact). In MyWidget, there is a QLineEdit and QListWidget. The contents in the QListWidget changes dynamically while changes in QLineEditt.
In ViewContact class there is many widgets.The ViewContact class is called by MyWidget class.
void MyWidget::viewbind(QListWidgetItem *item)
{
LblNames *widget = (LblNames*)( listWidget->itemWidget(item) );
ViewContacts *v=new ViewContacts(widget->getLabelId());
v->show();
}
then ViewContact widget shown as a window,no problem.works fine.
while clicking an update button inside ViewContact class i need to close that window and change the text inside MyWidget .now i just close the ViewContact by this.close(); function.
I give QLineEdit as public and try to change the text. No errors occur. But no changes display in QLineEdit inside MyWidget
Add a signal in the ViewContact class and emit a signal while close ViewContact Widget.The signal should contain a string to bind your list view.Before initiating ViewContact Widget from MyWidget ,should connect the signal and setText(const QString) slot.
Add the MyWidget as a parent to your ViewContacts instance. This will allow you to call a function to update the text (and it will also fix the memory leak which you currently have in your code).
You need a constructor for your ViewContacts that takes both a parent and the labelId.
class ViewContacts : public QWidget // or whatever it is, you didn't tell
{
Q_OBJECT
public:
// I don't know the class of "LabelId" either
explicit ViewContacts(LabelId id, QObject* parent = 0) : QWidget(parent)
{
// ...
}
void updateTextInParent()
{
MyWidget* w = qobject_cast<MyWidget*>(this->parent());
if (NULL != w)
{
// w is a valid pointer to a MyWidget instance
// you can access any public fields and function through it.
}
}
};
You should also use qobject_cast or dynamic_cast in the snippet you provided because a blind cast is not safe.
This seems like a perfect time to take advantage of Qt's signals and slots. You can connect a signal that emits the value you want to update in your MyWidget object, from your ViewContacts widget.
First you'll need to create a signal that emits the changed value when the ViewContacts widget is closed.
Something like:
Q_SIGNALS:
void value_changed_signal( QString value );
Next you'll want to add a slot, it can be private, in your MyWidget parent class
The declaration would look something like:
private Q_SLOTS:
void update_text( QString value );
Finally, in your MyWidget class, somewhere after you have instantiated your ViewContacts object, connect the signal and slot with something like:
connect(new_view_contacts_object, SIGNAL( value_changed_signal( QString ) ),
this, SLOT( update_text( QString ) ) );

QT EventTransition implementation

I am trying to build an QT State Maschine. I have some States, and for those States i need Transition that alter the Graphics on my gui.
The Problem i having and the only reason i am asking, i am Stuck and Point 1.
The compiler cant identifie the QTEventTransition. I have QT 4.6 wroking with QT Creator on Windows.
The compiler does not find Header #include < QtEventTransition >
This is what i did i never did this bevor but i think it should be correct, I have A Header File where i have my Transitions Declareted like this:
class validateBoatTransition : public QtEventTransition
{
public:
validateBoatTransition(Widget *widget,ServerSkeleton* server);
protected:
bool eventTest(QEvent *e);
void onTransition(QEvent *);
private:
Chart* ourChart;
Message current;
BarelySocket* myBarelySocket;
};
Than i have my Cpp File where i have this:
validateBoatTransition::validateBoatTransition(Widget *widget,ServerSkeleton* server)
{
}
void validateBoatTransition::onTransition(QEvent *e)
{
/*
My Logik should go here
*/
}
What i want is that if the Transition is activated by an Button (clicked) it should fire this transition!
I searched the net, but cant find an solution. Can i do that? I should i think.
Yours Thomas
Maybe you should take a look to signals/slot mechanism. I think this is what you need to achieve what you want.
Make your onTransition function a slot instead of an event handler and connect it to the signal clicked of the button.
class validateBoatTransition : public QtEventTransition
{
...
public slots:
void onTransition();
...
}
Somewhere in your code, connect the button to the slot:
QObject::connect(myButton, signal(clicked()), myValidateBoatTransition, slot(onTransition());
Each time the button will be clicked the execution will go through the onTransition function.
I think you're trying to use wrong classes/mechanisms to achieve your goals. If I understand you correctly, you have some GUI and after clicking some button you want to validate some stuff and if this validation is successful the state machine should change it's state. I'd write it this way:
Create some class to handle validation:
class BoatValidator : public QObject
{
Q_OBJECT
// boring stuff like constructor, etc.
public slots:
void validate()
{
if ( /*your validation logic goes here*/ ) {
emit boatTransition();
}
}
signals:
void boatTransition(); // emitted if validation is succesful
};
Then you connect your QPushButton::clicked() to BoatValidator::validate() and use BoatValidator::boatTransition() signal to drive the state machine:
QStateMachine machine;
QState *state1 = new QState(&machine);
QState *state2 = new QState(&machine);
// more state machine setup
// connect validator and button
QPushButton button;
BoatValidator validator;
connect(&button, SIGNAL(clicked()), &validator, SLOT(validate()));
// use validator to change states
state1->addTransition(&validator, SIGNAL(boatTransition()), state2);
Generally I'd use signal to drive state machine, unless some transitions are obviously event driven (for example some QEvent::Enter/QEvent::Leave on GUI widgets, etc.).
What i wanted to do is build a Qt State Machine. The Problem was that i could not trigger my own Transitions (let alone with my own Events). The answers given are good but would lead to a messy code. Why should i use a QT State Machine if i could not use the QT Transitions?
The First Problem above is solved, if you create a new Project. QT Creater is very annoying.
But here now my solution , may it help others.
First my State:
class ServerState : public QState
{
Q_OBJECT
public:
ServerState(QPushButton * pushButton);
~ServerState();
public slots:
void buttonWasClicked();
protected:
void onEntry(QEvent *e);
void onExit(QEvent *e);
private:
QPushButton * pushButton;
};
Normal, but you see i added an Slot. This slot enables me to connect a bottom signal or a Widget Mouse Press Signal to it !
Like this:
QStateMachine *machine = new QStateMachine(this);
ServerState *s1 = new ServerState(connectButton);
connect(connectButton, SIGNAL(clicked()), s1, SLOT(buttonWasClicked()));
machine->addState(s1);
s1->addTransition(connectTransition);
all i needed to to is now fire a declared Event like this one :
#define RegisterToServerEventIndex User+5
class ConnectToServerEvent : public QEvent
{
public:
ConnectToServerEvent() : QEvent(QEvent::Type(QEvent::ConnectToServerEventIndex))
{}
};
when the slot was called:
void ServerState::buttonWasClicked()
{
this->machine()->postEvent(new ConnectToServerEvent());
qDebug("ServerState::buttonWasClicked");
}
The QT State Machine would now call all the Transitions , link with this state:
ConnectToServerTransition::ConnectToServerTransition(QPushButton * pushButtonB,ServerSkeleton* serverSkeleton)
{
this->pushButtonB = pushButtonB;
this->pushButtonB->hide();
this->serverSkeleton = serverSkeleton;
qDebug("ConnectToServerTransition::ConnectToServerTransition");
}
bool ConnectToServerTransition::eventTest(QEvent *e)
{
return (e->type() == QEvent::ConnectToServerEventIndex);
}
void ConnectToServerTransition::onTransition(QEvent *e)
{
if (true == this->serverSkeleton->initalisieren())
{
this->pushButtonB->show();
}else{
qDebug("Conection to Server faild");
}
emit kill();
return;
}
Whats so great that i dare to post?
Well first you can link a Qt SM to a widget where a mouse press event , or somthing else, is called and process the raw data to a an level you need later in your program. All you then need to do is, to emit the singal:
void Widget::mousePressEvent(QMouseEvent *event){
Coordinates current;
current.line = 0;
current.row = A;
current.row = (Row) (event->x() / 30); // 30 = breite von einen Feld
current.line = event->y() / 30; // 30 = länge von einen Feld
emit this->clicked(current);
return;
}
Then this enhenced information (current) is passed to the slot at my state, where i chose to call the correct transition that does the work. You could link more transitions to it, if you need it.
But most importend you dont need to reprogramm the Transition, a think i realy disliked.
Thank you for your help , i could not done it alone.

Resources