I am a newbie at Qt programming and I have some issues with the code below. I wanted to create a simple two button application with one label. One button is for positive increment one, and the other button is for decrement one. The label should be updated once I click the plus or minus button. But it doesn’t work. Any ideas why the code doesn’t work? I get a compiler error for an element function void. But the error message is rather unspecific.
I checked the internet (intensive google search and also here on stackoverflow) for a solution but I could not find one. I very much appreciate any direct help or linkage to other websites / links. Please let me know in case I should rephrase the question or add some more information. Thanks for your time. Stefan
#include "widget.h"
int counter = 0;
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
setFixedSize(200, 120);
QPushButton *Plus = new QPushButton(tr("+"), this);
Plus -> setGeometry(62, 40, 75, 30);
Plus -> setFont(QFont("Times", 10, QFont::Bold));
QPushButton *Minus = new QPushButton(tr("-"), this);
Minus -> setGeometry(62, 40, 75, 30);
Minus -> setFont(QFont("Times", 10, QFont::Bold));
QLabel *MyLabel = new QLabel();
MyLabel ->setAlignment(Qt::AlignCenter);
MyLabel ->setGeometry(62, 40, 75, 30);
MyLabel ->setNum(counter);
QVBoxLayout *layout = new QVBoxLayout;
layout ->addWidget(MyLabel);
layout ->addWidget(Plus);
layout ->addWidget(Minus);
setLayout(layout);
connect(Plus, SIGNAL(clicked()), this, SLOT(myClickPlus()));
connect(Minus, SIGNAL(clicked()), this, SLOT(myClickMinus()));
}
void Widget::myClickPlus(){
counter ++;
qDebug("Das ist der Plus-Button");
MyLabel -> setNum(counter);
}
void Widget::myClickMinus()
{
counter --;
qDebug("Das ist der Minus-Button");
MyLabel ->setNum(counter);
}
The MyLabel that you are creating in the Widget’s constructor is a local variable. The MyLabel that you are using in the myClickPlus and myClickMinus member functions is a member variable. So they are completely different instances.
If your code compiles, then this change in the Widget’s constructor will probably fix the problem:
–>