i have a QLineEdit on my main screen define by QDialog.along with it i have a table which contains dynamic data displayed by QThread with 50 data in every 2 seconds.when i input any value in QLinrEdit and then press enter then the screen terminates.
value = new QLineEdit(this);
m_label = new QLabel(tr("&Enter Preference Value:"));
m_label->setBuddy(value);
m_preLayout->addWidget(m_label);
m_preLayout->addWidget(value);
m_preferenceGroup->setLayout(m_preLayout);
connect(value, SIGNAL(returnPressed()), this, SLOT(preferentialData()));
void appWindow::preferentialData()
{
valuee = (value->text()).toInt();
}
here i am taking the input from user and then converting that input into an integer which will be further used for some other purpose.Now after taking that input as per signal i press enter and as soon as after that the screen closes.
the value is converted to int and no errors are coming on compiling but why is the window closing? because if it closes then the thing that i will further do with that converted int will be like of no use as with the help of that int i will change some display on my table as i mentioned that i have a table too in that window.
thanks for any help in advance
I'm almost certain (can't be sure without seeing more code) that the dialog is taking the "Enter" keypress and calling its accept() method, which closes the dialog. If you made the dialog in Qt Creator and chose one of the dialog types that places a button box on the form for you, then this connection is wired up by default.
Check your dialog's signal/slot connections and make sure that the accept() slot isn't connected to a QPushButton or QDialogButtonBox signal.
Related
I am new to Qt and understands the concept of signal and slots. However I am not able to implement it.
My objective is:
Form1 has a button Config. So when I click Config it should open another form Form2( without closing Form1) and send a string strData to Form2.
In Form2 I set some value in the string strData. Then I click Ok button in Form2, Form2 should close and return back the string to Form1.
When the call returns back to Form1, it should continue from where it emitted the signal to invoke Form2.
Any help is highly appreciated.
You can't do this using signals/slots; the signal is emitted, and all of the connected slots are executed, and then the code continues from where the signal is emitted and eventually returns to the event loop. That's when your second form is actually shown and the user can respond to it, but by then, your code is long past where the signal was emitted.
What I believe you're looking for is the QDialog::exec method; use it in place of the signal. The basic pattern of the code is:
// This is the response to click on Config...
Form2Dialog form2;
form2.setSomeStringValue (some_value);
if (form2.exec() == QDialog::Accepted)
{
QString some_new_value = form2.newValue();
}
The Form2Dialog is a subclass of QDialog where you've added your own setSomeStringValue and newValue methods. (What you actually name these is up to you.)
The important thing is that the exec method blocks and doesn't return until the user selects OK or Cancel on the dialog, or closes it using the "close" button in the title bar (if there is one).
I'm having a strange problem in a game I'm building in Qt where each time I generate I call qrand() (or rand(), I tried both), a separate tiny window pops up and steals focus from my game. I want to 'roll' a pair of dice every 2 seconds so I'm generating a number between 1 and 12. I'm using a QTimer object in a GameBoard custom widget constructor to call the public slot updateDice() that resets a private variable to a random number.
void GameBord::updateDice(){
dice_int = qrand()%12 +1;
repaint();
QCoreApplication::processEvents();
return;
}
and in my repaint()
...
dice_roll->clear();
dice_roll->setText(QString::number(dice_int));
...
where dice_roll is the label that displays what number the roll was for the player.
With the debugger I found that every time dice_int is assigned the window pops up. The weirdest part to me is that I have other random numbers generated and they don't cause this problem.
I know you can setAttribute so that the window comes up without activating, but I don't know where the window is coming from.
And if there is no solution to this problem, is there a way to set Focus on a widget so that it never changes? I tried Qt::StrongFocus but that doesn't help.
I'd be happy to post more code if you want it, and thanks in advance.
I'm a beginner in programming in C++/Qt.
I created a widget called wexample in Qt. When displayed, there is an button event that will open another window of the same widget wexample, and so on. My question is how to close all the windows of that widget?
I open my first widget as follows:
wexample *w = new wexample;
w-> show();
Inside the widget, I also have these events:
void wexample::on_pushButton1_clicked()
{
wexample *w = new wexample;
w -> show();
}
void wexample::on_pushButton2_clicked()
{
QWidget::close();
}
So when button 1 is pressed, it will open a new window and so on. When button 2 is pressed, it will close the window where the button is. Is there a way to close all of the windows from that widget all at once? Or even better, is there a way to close specific windows (for example, all the windows after the 3rd one)?
I have tried using signal and slot but I can't connect them since they are all of the same name. I would have to declare all of the widgets beforehand for it to work but I cannot know how many of them the user will need.
I'm sorry if my question isn't clear. I am really a beginner and have been searching for a while but couldn't find an answer. Maybe the structure as a whole doesn't make sense. Please help. Thanks.
You should add your newly created wexample's to a list and then iterate through them when you'd like to close them:
class wexample : public QDialog
{
...
private Q_SLOTS:
void on_pushButton1_clicked() {
wexample *w = new wexample(this);
m_wexamples.append(w);
w->show();
}
void wexample::on_pushButton2_clicked() {
foreach (wexample *w, m_wexamples)
w->close();
}
private:
QList<wexample*> m_wexamples;
};
A few extra points here:
Notice that I added (this) to the wexample constructor above. This ensures that the dialog is properly parented (and therefore will be cleaned up if you don't manually delete the object yourself). Previously, you would have been leaking memory every time you showed the dialog
The slot for the second button simply iterates through the list of dialogs and closes them. This does NOT mean that the dialogs have been deleted (and in fact are still in the list after closing them). If you'd prefer to fully remove them, then use of the "take" methods of QList, removing the dialog from the list and then call dialog->close(); dialog->deleteLater(); on it
This is a somewhat contrived example, you probably won't be opening the dialog from within the dialog's implementation in practice
I've built an app for a game, simple to start. It's a game in which the system randomly chooses a number and a gamer (player) tries to find out the number. Everything is almost done. The app consists of a QLineEdit, a label and three buttons. Once the app tells the player the range of the wanted number, he/she types a bet_number and clicks on the play button. And according to this number he/she gets a message about how close or far the wanted number is away from the bet_number.
But I find it a little disgusting to click a button. Instead I want to use Enter key to play. So to achieve this, it comes down to specifically two questions:
How could one change to using Enter to play (I mean I need know when QLineEdit detects enter key is pressed)? In this way I'll code properly to point the play method.
If the play button's got the focus, how do you use enter key on this button? (make Button accept Enter key)
For the QLineEdit connect to the returnPressed signal.
Alternatively, if you use the setAutoDefault method on your QPushButtons you emit the clicked signal when Enter is pressed on a focused QPushButton:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.pushButtonOK = QtGui.QPushButton(self)
self.pushButtonOK.setText("OK")
self.pushButtonOK.clicked.connect(self.on_pushButtonOK_clicked)
self.pushButtonOK.setAutoDefault(True)
self.lineEditNumber = QtGui.QLineEdit(self)
self.lineEditNumber.returnPressed.connect(self.pushButtonOK.click)
self.layoutHorizontal = QtGui.QHBoxLayout(self)
self.layoutHorizontal.addWidget(self.pushButtonOK)
self.layoutHorizontal.addWidget(self.lineEditNumber)
#QtCore.pyqtSlot()
def on_pushButtonOK_clicked(self):
inputNumber = self.lineEditNumber.text()
if inputNumber.isdigit():
info = "You selected `{0}`"
else:
info = "Please select a number, `{0}` isn't valid!"
print info.format(inputNumber)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
QLineEdit will emit the signal returnPressed() whenever the user presses the enter key while in it: http://qt-project.org/doc/qt-4.8/qlineedit.html#signals. You can either connect this signal to your button's click() slot or directly call whatever your button's clicked() signal was connected to.
A slight C++ variation on other answers, it's not significantly different, but I thought i would include it anyway because how you lay things in QT code can be very different from codebase to codebase and I wanted to strip out the extraneous stuff to give the shortest and easiest to understand excerpt of code.
QLineEdit *TextSend = new QLineEdit("");
QPushButton *SendPB = new QPushButton("Send!");
connect(TextSend, &QLineEdit::returnPressed, this, &CLITab::SendCommand);
connect(SendPB, &QPushButton::released, this, &CLITab::SendCommand);
So what this is doing is we create a QLineEdit textbox and a QPushbutton.
We do cosmetic things like set the string label for them and add them to our layout.
Then we setup a callback handler, which will be triggered when the QLineEdit returns "returnPressed", which then calls automatically into a function which i wrote called "CLITab::SendCommand()", and then it's upto this function to extract the data out of QLineEdit and do whatever needs to be done. In practice the TextSend and SendPB pointers would live in the parent class, so that SendCommand() has visibility over these objects.
Just putting this here, along side an example pushbutton, because essentially they work in precisely the same way, all that's different is the signal name emitted.
How to use signal and slots for handling events i.e when a pushButton is clicked some number should be displayed in QLineEdit.Just like in caluculator application when a number is clicked the corresponding is displayed .
connect a widget's signal to other's widget slot.
Signal = Emitted when the button (for instance) is pressed.
Slot = called when a certain singal is fired, and this signal is connected to this slot.
If You use QtCreator here is the procedure:
right click on the pushbutton. Select go to slot.
Select clicked()
QtCreator will open C++ editor with new empty member function defined that implements
your slot. This function will be called whenever someone clicks this button.
Now in this function you can call method of another widget ot modify its contants.
This book is quite good for starters:
http://www.amazon.com/Book-Qt-Art-Building-Applications/dp/1593271476/ref=sr_1_8?ie=UTF8&qid=1300905855&sr=8-8
Good luck.