问题描述
我想将 QPushButton
连接到同一个类中的函数。该类只是通过代码生成 qgridLayout
的 ui
。我不知道该怎么办。实际上我不知道在 reciever
中为 QObject::connect
参数输入什么。
我不想使用一堆 h
和 cpp
文件,以便代码尽可能简单易读。
这是我的 main.cpp
文件:
#include <QApplication>
#include <QtWidgets>
#include <iostream>
using namespace std;
class ConnectPage
{
public:
void login_clicked(){
cout<<"login pressed"<<endl;
}
qgridLayout *main_layout = new qgridLayout;
// user interface Labels
QLabel *username_label = new QLabel("username");
QLabel *password_label = new QLabel("password");
QLabel *host_label = new QLabel("host");
QLabel *port_label = new QLabel("port");
QLabel *status_bar = new QLabel;
// user interface lineedits
QLineEdit *username_lineedit = new QLineEdit;
QLineEdit *password_lineedit = new QLineEdit;
QLineEdit *host_lineedit = new QLineEdit;
QLineEdit *port_lineedit = new QLineEdit;
// user interface buttons
QPushButton *login = new QPushButton("Connect");
QPushButton *reset = new QPushButton("Clear form");
ConnectPage()
{
QObject::connect(login,SIGNAL(clicked()),&app,SLOT(login_clicked()));
main_layout->addWidget(username_label,1,1);
main_layout->addWidget(username_lineedit,1);
main_layout->addWidget(password_label,1);
main_layout->addWidget(password_lineedit,1);
main_layout->addWidget(host_label,2,1);
main_layout->addWidget(host_lineedit,1);
main_layout->addWidget(port_label,3,1);
main_layout->addWidget(port_lineedit,1);
main_layout->addWidget(reset,4,1);
main_layout->addWidget(login,1);
main_layout->addWidget(status_bar,5,2);
}
};
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QWidget *window = new QWidget;
ConnectPage start_connecting;
qgridLayout *main_layout = start_connecting.main_layout;
window->setLayout( main_layout );
window->setwindowTitle("Login Page");
window->show();
return app.exec();
}
这里是 .pro
文件:
QT += core gui widgets
SOURCES += \
main.cpp \
HEADERS += \
任何仅涉及这两个文件的帮助将不胜感激。
解决方法
如果您使用 Qt link
简单的答案是:
- 您的类应该从 Qobject 继承,并且您应该将
QObject
makro 放在这个类的顶部和私有部分。
class example : public QObject
{
Q_OBJECT
public: ...
public slots: ...
private: ...
};
- 槽函数,应该在类的
public slots:
部分。喜欢:
public slots:
void login_clicked(){
cout<<"login pressed"<<endl;
}
- 您可以像这样在类构造函数中捕获此函数:
connect(login,&QPushButton::pressed,this,&ConnectPage::login_clicked);
您可以在 connect
中使用 lambda 表达式。
connect(login,[&](){
cout<<"login pressed"<<endl;
});
最后一句话。如果你想使用你现在拥有的语法,你需要记住函数签名。从文档: “关于是否在 SIGNAL() 和 SLOT() 宏中包含参数的规则,如果参数具有默认值,则传递给 SIGNAL() 宏的签名的参数不得少于传递给SLOT() 宏。"
所以这个语法应该有效:
connect(login,SIGNAL( clicked(bool)),SLOT(login_clicked()));
但我不喜欢这种语法。
最好的问候!