【问题标题】:Implement slots in derived class - qt4/c++在派生类中实现插槽 - qt4/c++
【发布时间】:2013-05-20 01:30:02
【问题描述】:

我正在尝试制作示例 Communicate(可以在网络教程First program in qt4 中找到),但方式不同:“加号”和“减号”按钮是不是在构造函数中构建,而是通过调用继承QWidget类属性的子类的成员函数:

mywidget.h 中的 myWidget 类

#ifndef _MYWIDGET_H
#define _MYWIDGET_H
#include <QApplication>
#include <QDesktopWidget>
#include <QWidget>
#include <QIcon>
#include <QPushButton>
#include <QLabel>
class myWidget : public QWidget{

    public:
        myWidget(QWidget *parent = 0);

        void setPMButton(int,int,int,int,int,int);
    private:
        QLabel *label;
    private slots:
        void OnPlus();
        void OnMinus();   
};
#endif

Mywidget.cpp 中的方法实现

#include "mywidget.h"
myWidget::myWidget(QWidget *parent) : QWidget(parent){
    label = new QLabel("0", this);
    label->setGeometry(190, 80, 20, 30);
}
void myWidget::OnPlus(){
    int val = label->text().toInt();
    val++;
    label->setText(QString::number(val));
}
void myWidget::OnMinus(){
    int val = label->text().toInt();
    val--;
    label->setText(QString::number(val));
}
void myWidget::setPMButton(int x1, int y1, int x2, int y2, int w, int h){
    QPushButton *plus = new QPushButton("+", this);
    plus->setGeometry(x1, y1, w, h);

    QPushButton *minus = new QPushButton("-", this);
    minus->setGeometry(x2, y2, w, h);

    connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
    connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));
}

并且在主文件test.cpp中是这样写的:

#include "mywidget.h"
int main(int argc, char *argv[]){

    QApplication app(argc, argv);

        myWidget window;

        window.setPMButton(50,120,50,200,75,30);        
        window.show();

    return app.exec();
}

但是一旦我运行应用程序,它会显示窗口,但按钮不起作用。在终端显示消息:

Object::connect: No such slot QWidget::OnPlus()
Object::connect: No such slot QWidget::OnMinus()

有什么办法可以做到吗?

【问题讨论】:

    标签: c++ qt user-interface qt4


    【解决方案1】:

    您忘记添加 Q_OBJECT 宏。

    #includes here
    ...
    
    class myWidget : public QWidget{
    
    Q_OBJECT   ///      <---- Here
    
    public:
        myWidget(QWidget *parent = 0);
    
    ...
    ...
    

    【讨论】:

    • 是的! ¬¬' 现在可以了!但是怎么没有编译错误呢?
    • 我想是因为没有非法代码。它只是无法按预期工作,没有信号/插槽连接,没有子 QObjects 管理..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多