如何将小部件变量传递给插槽?

时间:2013-08-01 23:28:46

标签: qt events variables slot

我是QT初学者,我正在编写一个GUI应用程序,它有两个QPushButtons和两个QTextEdits。当单击按钮1时,我只想要QTextEdit 1来显示某些内容,当单击按钮2时,我只想要QTextEdit 2来显示某些内容,下面是我的代码,但它不起作用,因为它似乎无法将参数传递给插槽方法......

class EventProcessor: public QObject {

    Q_OBJECT

public slots:

    void PopulateEditTest(QTextEdit *textEdit, QString text)
    {
        textEdit->setText(text);
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget *window = new QWidget;

    QTextEdit *result1 = new QTextEdit();
    QTextEdit *result2 = new QTextEdit();
    QPushButton *btFacility1 = new QPushButton("Facility 1");
    QPushButton *btFacility2 = new QPushButton("Facility 2");

    EventProcessor eventprocessor;


    QObject::connect(btFacility1, SIGNAL(clicked()), &eventprocessor, SLOT(PopulateEditTest
                    (result1, "textEdit1")));
    QObject::connect(btFacility2, SIGNAL(clicked()), result, SLOT(PopulateEditTest
                    (result2, "textEdit2")));

    ..........


    return app.exec();
}

我想知道是否有类似的方法让这个工作?谢谢你的回答。

1 个答案:

答案 0 :(得分:1)

你是正确的,因为你不能指定在调用QObject::connect时传递给插槽的参数。您提供的只是函数定义,而不是函数调用。

完成您尝试做的最简单的方法是在事件处理器类中添加几个插槽:

class EventProcessor: public QObject {

    Q_OBJECT

public slots:

    void PopulateEditTest(QTextEdit *textEdit, QString text) { ...  }
    void button1Clicked() {
        PopulateEditTest(dynamic_cast<QTextEdit*>(sender()), "textEdit1");
    }

    void button2Clicked() {
        PopulateEditTest(dynamic_cast<QTextEdit*>(sender()), "textEdit1");
    }
};

...

QObject::connect(btFacility1, SIGNAL(clicked()), &eventprocessor, SLOT(button1clicked()));
QObject::connect(btFacility2, SIGNAL(clicked()), &eventprocessor, SLOT(button2Clicked()));

有很多原因可以解释为什么它通常被认为是邪恶的&#34;以这种方式使用QObject::sender()函数,但这是完成您尝试做的事情的最简单方法,无需重写所有代码,如果不知道你的长期,这将是毫无意义的。术语目标是。