I'm trying to make a simple "Cookie Clicker" game and I'm having trouble with this. When I press the button I want the label to print out "You have mined (VALUE) FSCoins" but the label won't update for some reason. Console shows no errors :(
Here's my code:
mainwindow.cpp
void MainWindow::on_pushButton_clicked(int num, int numplus)
{
num = numplus + 1;
QString qstr = QString::number(numplus);
ui->label->setText("You have mined " + qstr + " FSCoins");
}
Any help would be appreciated, I've only started working with Qt yesterday and I'm "Sort of" getting the hang of it.
num = numplus + 1;
What is the point of this line? num is a local variable that is never used. Did you mean to pass it by reference?
You need to connect a SIGNAL to a SLOT, but that function you wrote there does not seem like a SLOT. Somewhere in your code there shall be something like this in your header file:
class ...
{
// ...
private slots:
void onPushButtonClicked();
};
and in your source file:
// For example in the constructor.
connect( ui->PushButton, SIGNAL( clicked() ), this, SLOT( onPushButtonClicked() ) );
// The implementation of your SLOT.
Class::onPushButtonClicked()
{
// Your implementation.
updateLabel( /* Your arguments */ );
}
The SLOT function cannot have more arguments than the SIGNAL, so in this case your SLOT cannot have any.
And something else. I prefer this version of creating a QString:
QString( "You have mined %1 coins" ).arg( value );
I think it's more readable.
So the point is that that you need store that integers somewhere. Maybe in your class as a member variable.
Related
I've done quite a thorough research as I've been struggling with a slot issue, but as the Google search results steadily grew more and more purple, I decided just to ask the SO pals =) Please mind that I am not using QtCreator nor any dynamic stuff. I need to:
declare some QStrings which are constant
get some QStrings out of QLineEdits
add 1 and 2
finally, put them into QTextEdit when a button is clicked.
For the step 1, I declare QStrings like this:
QString set_1 = "ООО «Хеллманн» (129343, г. Москва, ул. Уржумская, д. 4, стр. 14, ИНН 7722637955, ОГРН 1087746168476) доверяет забор груза - ";
QString set_2 = " - перегружаемого из контейнера ";
QString set_3 = ", в количестве ";
QString set_4 = " паллет, весом ";
QString set_5 = " кг, водителю ";
QString set_6 = ", паспорт ";
QString set_7 = " выдан ";
QString set_8 = ".";
QString set_9 = " На автотранспортном средстве марки ";
QString set_10 = " - ";
QString set_11 = ", прицеп: ";
Then, for the step 2, I make QStrings out of QLineEdits like this (e.g. line_b_b is the name of a QLineEdit):
QString a = line_b_b.text();
QString b = line_b_a.text();
QString c = line_b_c.text();
QString d = line_b_d.text();
QString e = line_a_b.text();
QString f = line_a_a.text();
QString g = line_a_c.text();
QString h = line_a_d.text();
QString i = line_c_b.text();
QString j = line_c_a.text();
QString k = line_c_c.text();
For the step 3, I add the QStrings from the step 1 with those from the step 2 into a variable named "doverka" (please don't mind this cyrillic stuff):
QString doverka = set_1+a+set_2+b+set_3+c+set_4+d+set_5+e+set_6+f+set_7+g+h+set_8+set_9+i+set_10+j+set_11+k+set_8;
Finally, in the step 4, I try to put the whole into QTextEdit when a button is pushed. And I guess the problem is here. I create a QTextEdit named "text":
QTextEdit text (&dw);
text.show();
And then I try to create a slot and I presume I am doing this in a totally wrong way as it simply doesn't work:
QPushButton btn_t ("Создать текст", &dw);
QObject::connect(
&btn_t,
SIGNAL(clicked()),
&text,
SLOT([dover](){return text.setText(doverka)}));
btn_t.show();
I am new to Qt as well as to C++ and that's why poor at slot creation. Here I've tried this with a lambda function but I am obviously doing something wrong. Maybe I should just put the lambda function somewhere else before SLOT? My slot is not recognized as such when the prog is being compiled, I get the "no such slot" notification. Or maybe the problem is somewhere earlier, e.g. in making QStrings out of QLineEdits (step2)?.. I'm pretty helpless and appreciate any useful tips greatly! Very many thanks.
You are trying to mix old style Qt signal/slot connection with new style which obviously does not work. lambdas can be used only with new style of connections. If you are using Qt 5 the connection could be like:
QObject::connect(
&btn_t,
&QPushButton::clicked,
[&text, &doverka](){
text.setText(doverka);
});
You should be careful that text and doverka objects should not be destroyed before the lambda is invoked, as they are captured by reference.
In case of using Qt 4.* you should use the old syntax. In your case just provide a slot in your class and connect the signal it:
QObject::connect(
&btn_t,
SIGNAL(clicked()),
this,
SLOT(onClicked()));
Your class should inherit from QObject containing a slot like:
public slots:
void onClicked() {
text.setText(doverka);
}
Also note that text and doverka should be members of the class.
How can I pull the names of my spinBoxes? I tried looking at a lot of the documentation, however, I couldn't find anything that would show the names of each of the child spinBoxes. I've tried changing the result to a string. However, I just get a Hex or Long Int, of the address I’d imagine, returned instead.
QList<QSpinBox*> spinBoxes= findChildren<QSpinBox*>();
//create the QSignalMapper object
QSignalMapper* signalMapper= new QSignalMapper(this);
//loop through your spinboxes list
QSpinBox* spinBox;
foreach(spinBox, spinBoxes){
//setup mapping for each spin box
connect(spinBox, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
signalMapper->setMapping(spinBox, spinBox);
}
//connect the unified mapped(QWidget*) signal to your spinboxWrite slot
connect(signalMapper, SIGNAL(mapped(QWidget*)), this, SLOT(spinboxWrite(QWidget*)));
.
.
.
void GuiTest::SpinBoxChanged(QWidget* wSp){
QSpinBox* sp= (QSpinBox*)wSp; //now sp is a pointer to the QSpinBox that emitted the valueChanged signal
int value = sp->value(); //and value is its value after the change
//do whatever you want to do with them here. . .
qDebug() << value << "SpinBoxChanged";
}
void GuiTest::spinboxWrite(QWidget* e){
SpinBoxChanged(e);
QString* value = (QString*)e;
qDebug() << e << value << " SpinBoxWrite";
}
Please note qDebug() << e as this is where I'm having trouble getting some information about the spinboxes
The name you are trying to retrieve is the objectName property, which every QObject and QObject-derived class has. Call objectName() to retrieve this value.
You can also use this with the QObject::findChild() function.
This should get what you want:
void GuiTest::spinboxWrite(QWidget* e){
SpinBoxChanged(e);
qDebug() << e->objectName() << " SpinBoxWrite";
And will output:
"norm_spinBox_10" SpinBoxWrite
Note
This line is dangerous:
QSpinBox* sp= (QSpinBox*)wSp;
Use qobject_cast instead of C-style casts.
There is no direct way to get the name of a variable as a string.
However, you can use a QMap<QSpinBox*, QString> to map each spin-box to its name.
In the constructor you have to assign these manually:
map[ui->spinBox] = "spinBox";
map[ui->spinBoxWithStrangeName] = "spinBoxWithStrangeName";
Then you can simply get the strings using:
QString name = map[ui->spinBox];
Just give them names in the designer file and then use that name to retrieve them in the C++ code.
QSpinBox* mySpinner = findChild<QSpinBox*>("myGivenName");
Good time of day! I have a question you'll maybe find silly and obvious, but i've already broke my head trying to solve this.
I want to plot some curve by pressing a QPushButton. I wrote the slot and connected it to the corresponding signal of this button. But when I click on it, nothing happens on the plot, although this function executes, and it can be viewed on the debugger and qDebug() output.
On the other hand, if you call this function directly, and not as a slot, it works perfectly. The only difference is the calling method: as a slot in first case and as a method in the second case.
Some code examples:
//Slot
void MainWindow::buttonClick()
{
qDebug() << "Enter";
XRDDataReader *xrdr = new XRDDataReader();
xrdr->fromFile("/home/hippi/Документы/Sources/Qt/49-3.xy");
ui->plot->plotXRD(xrdr->xValues(), xrdr->yValues());
qDebug() << "Quit";
}
void Plotter::plotXRD(QVector<double> x, QVector<double> y)
{
QwtPlotCurve *curve = new QwtPlotCurve();
curve->setRenderHint
( QwtPlotItem::RenderAntialiased, true );
curve->setPen(Qt::black, 2);
curve->setSamples(x,y);
curve->attach(mainPlot);
}
As long as autoreplotting is not enabled, you have to call replot to make changes happen.
I am quite new to C++ and Qt. I've gotten pretty far on my current project, but I've been putting off this one part. I have a pushbutton that opens a new dialog like this:
void MainWindow::on_fillAll_clicked()
{
int yo;
BlockSelect bSelect;
bSelect.setModal(true);
bSelect.exec();
if( bSelect.exec() == QDialog::Accepted )
{
//Get stuff here?
//I want to fill yo with the spinbox value
yo = bSelect.stuff();
return;
}
qDebug() << yo;
}
This works fine. In the dialog I have a spin box. I want to send that value inputted to the spin box to my main window when the user clicks OK.
I have been trying to get "int yo;" to have that value from the spinbox but everything I try just gets an error.
I added this to my BlockSelect public class:
int stuff();
And I made this function in my blockselect.cpp:
int BlockSelect::stuff()
{
qDebug() << "The function was called";
return ui->yolo->value();
}
But qDebug never shows anything???
So how can I fill yo from the main window with yolo from the dialog?
Sorry if I didn't explain this well :( I'm still learning.
Thanks for your time :)
First of all, there is no need to call exec() twice, just use it once within the if statement.
To answer your question, you still have the bSelect dialog object (and I'm assuming BlockSelect is a class you define?), so make an accessor function inside it to retrieve the values you want.
if( bSelect.exec() == QDialog::Accepted )
{
//Get stuff here?
//I want to fill yo with the spinbox value
yo = bSelect.stuff();
return;
}
EDIT:
Your BlockSelect class needs to contain an accessor function, this means a function that returns a value.
int stuff() { return ui->yolo->value();}
What I'm doing here is retrieving the spinbox's value (assuming it is named 'yolo') and returning it as a result of calling the 'stuff' function.
I want to use QLineEdit to get an integer value that I want to work with. My problem is that I want to wait till the text is entered. It would also be nice if I can give a default text at the begining that will automatically be deleted after clicking on the QEditLine, like :
for the first point I tried this and it didn't work:
......
int num =0;
QLineEdit *qtest = new QLineEdit();
........
mailayout->addWiget(qtest);// when I use the while loop the QLineEdit won't be added !!
while(num ==0 ){
num = qtest->text.toInt();
}
.............
the program stays in the while loop, any Idea I'm doing wrong?
Use setPlaceholderTest(const QString&) for text to show when the user has not entered anything.
Don't poll the QLineEdit for changes, this is Qt so use signals.
connect( qtest, SIGNAL( editingFinished() ),
someContainerObj, SLOT( myLineEditSlot() ) );
...
ContainerObj::myLineEditSlot()
{
int num = qtest->text().toInt();
...
}