QT 主窗口中调用子窗口控件和信号传递
文件目录
Headers:
Souces:
实现:
由mainwindow菜单栏弹出dialog,该子窗口dialog中的buttonbox在按键ok/cancel后,mainwindow返回相应的值。
方法:
dialog的按键动作通过emit发送SIGNAL作为主窗口槽的触发信号,主窗口接收到子窗口SIGNAL信号后,触发SLOT信号,判断QAbstractButton格式的内容(ok/cancel)作响应。
该方法的要求如下:
在要声明子窗口的RenderDialog类renderdialog,并定义响应的槽函数btnbox(QAbstractButton *),因为传送的信号类型就是QAbstractButton,用来判断buttonbox的内容ok/cancel.
#include ""
#include "ui_renderdialog.h"
private:
Ui::MainWindow *ui;
private:
RenderDialog *renderdialog;
private slots:
// void hellook();
// void hellocancel();
void btnbox(QAbstractButton *);//SLOT信号
// connect(renderdialog,SIGNAL(buttonbox_ok()),this,SLOT(hellook()));
// connect(renderdialog,SIGNAL(buttonbox_cancel()),this,SLOT(hellocancel()));
connect(renderdialog,SIGNAL(buttonbox(QAbstractButton *)),this,SLOT(btnbox(QAbstractButton *)));
/*
void MainWindow::hellook()
{
qDebug()<<"okya";
}
void MainWindow::hellocancel()
{
qDebug()<<"cancelya";
}
*/
void MainWindow::btnbox(QAbstractButton *button)
{
if(button == renderdialog->ui->buttonBox->button(QDialogButtonBox::Ok))
{
qDebug()<<"ok";
}else if(button == renderdialog->ui->buttonBox->button(QDialogButtonBox::Cancel))
{
qDebug()<<"cancel";
}
}
该方法在中,要将ui定义成公有才可在mainwindow中调用。定义signals void button(QAbstractButton *)作为传递信号,用来发送子窗口的信号,QAbstractButton要根据传送信号的格式来定义,这里是因为buttonbox控件的ok/cancel的格式而定。
private slots:
void on_buttonBox_clicked(QAbstractButton *button);
public:
Ui::RenderDialog *ui;
signals:
void buttonbox(QAbstractButton *);
renderdialog的buttonbox在clicked()时通过emit发送传递的信号,如上文所述,然后在通过connect得到renderdialog传递过来的QAbstractButton信号,然后将该信号在主窗口中进行判断即可。
void RenderDialog::on_buttonBox_clicked(QAbstractButton *button)
{
/*
if(ui->buttonBox->button(QDialogButtonBox::Ok)==button)
{
emit buttonbox_ok();
qDebug()<<"ok";
}else if(ui->buttonBox->button(QDialogButtonBox::Cancel)==button)
{
emit buttonbox_cancel();
qDebug()<<"cancel";
}
*/
emit buttonbox(button);
}
注释掉的代码大同小异,只是将buttonbox的ok/cancel分开发送,原理相同,只是为了学习中方便调试。