这里使用QSharedMemory可以实现信号与槽中跨界面传输数据的功能!
原理是:
(相关资料图)
发送界面获取到数据就写到SharedMemory中
而获取端,用个记时器,时时去多,奇淫技巧啊!
运行截图如下:
源码如下:
sharedwidget.h
#ifndef SHAREDWIDGET_H#define SHAREDWIDGET_H#include QT_BEGIN_NAMESPACEclass QSharedMemory;QT_END_NAMESPACEnamespace Ui {class SharedWidget;}class SharedWidget : public QWidget{Q_OBJECTpublic:explicit SharedWidget(QWidget *parent = 0);~SharedWidget();protected slots:void LineEditTextChanged(QString text);private:Ui::SharedWidget *ui;QSharedMemory *m_sharedMemory;};#endif // SHAREDWIDGET_H
widget.h
#ifndef WIDGET_H#define WIDGET_H#include QT_BEGIN_NAMESPACEclass QSharedMemory;QT_END_NAMESPACEnamespace Ui {class Widget;}class Widget : public QWidget{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();protected:void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE;protected slots:void btnClicked();private:Ui::Widget *ui;QSharedMemory *m_sharedMemory;int m_timerId;};
#endif // WIDGET_H
sharedwidget.cpp
#include \"sharedwidget.h\"#include \"ui_sharedwidget.h\"#include #include #include #include SharedWidget::SharedWidget(QWidget *parent) :QWidget(parent),ui(new Ui::SharedWidget){ui->setupUi(this);m_sharedMemory = new QSharedMemory(\"123456\");connect(ui->lineEdit, SIGNAL(textChanged(QString)),this, SLOT(LineEditTextChanged(QString)));}SharedWidget::~SharedWidget(){delete ui;}void SharedWidget::LineEditTextChanged(QString text){if(m_sharedMemory->isAttached()){if(!m_sharedMemory->detach()){return;}}QBuffer buffer;buffer.open(QBuffer::ReadWrite);QDataStream out(&buffer);out << text;if(!m_sharedMemory->create(buffer.size())){qDebug()<< \"create failed!\";return;}m_sharedMemory->lock();char *to = static_cast(m_sharedMemory->data());const char *from =text.toStdString().c_str();memcpy(to, from, qMin(m_sharedMemory->size(), (int)buffer.size()));m_sharedMemory->unlock();}
widget.cpp
#include \"widget.h\"#include \"ui_widget.h\"#include \"sharedwidget.h\"#include #include #include #include Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget){ui->setupUi(this);m_sharedMemory = new QSharedMemory;m_sharedMemory->setKey(\"123456\");m_timerId = startTimer(0);connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(btnClicked()));}Widget::~Widget(){delete ui;delete m_sharedMemory;}void Widget::timerEvent(QTimerEvent *event){if(event->timerId() == m_timerId){if(!m_sharedMemory->attach()){return;}QBuffer buffer;m_sharedMemory->lock();buffer.setData((char*)m_sharedMemory->constData(), m_sharedMemory->size());buffer.open(QBuffer::ReadOnly);QString data = buffer.readAll();m_sharedMemory->unlock();m_sharedMemory->detach();ui->label->setText(data);}}void Widget::btnClicked(){SharedWidget *sharedWidget = new SharedWidget;sharedWidget->show();}
main.cpp
#include \"widget.h\"#include \"sharedwidget.h\"#include int main(int argc, char *argv[]){QApplication a(argc, argv);Widget w;w.show();return a.exec();}
【领 QT开发教程 学习资料, 点击下方链接莬费领取↓↓ ,先码住不迷路~】
点击这里: