我在 Qt 中编写了一个程序,它工作正常,但单击按钮不起作用。当我在类声明之后使用 Q_OBJECT 时,它给了我编译错误。
这是我的代码:
#include <QApplication>
#include <QPushButton>
#include <QLabel>
#include <QWidget>
class Communicate : public QWidget
{
// Q_OBJECT
public:
Communicate(QWidget *parent = 0);
private slots:
void OnPlus();
void OnMinus();
private:
QLabel *label;
};
Communicate::Communicate(QWidget *parent)
: QWidget(parent)
{
QPushButton *plus = new QPushButton("+", this);
plus->setGeometry(50, 40, 75, 30);
QPushButton *minus = new QPushButton("-", this);
minus->setGeometry(50, 100, 75, 30);
label = new QLabel("0", this);
label->setGeometry(190, 80, 20, 30);
connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));
}
void Communicate::OnPlus()
{
int val = label->text().toInt();
val++;
label->setText(QString::number(val));
}
void Communicate::OnMinus()
{
int val = label->text().toInt();
val--;
label->setText(QString::number(val));
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Communicate window;
window.setWindowTitle("Communicate");
window.show();
return app.exec();
}