以下代碼片段打開兩個視窗 w1 和 w2。當用戶關閉 w1 時,如何強制 w2 關閉?與評論中一樣,該connect功能并沒有那樣作業。
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w1;
w1.setWindowTitle("w1");
w1.show();
QWidget w2;
w2.setWindowTitle("w2");
w2.show();
// when w1 is closed by the user, I would like w2 to close, too.
// However, it won't happen, even though the code compiles fine.
QObject::connect(&w1, &QObject::destroyed, &w2, &QWidget::close);
return a.exec();
}
編輯就我而言,這兩個小部件設計在兩個單獨的庫中,因此它們無法相互通信。因此,關閉事件不適用。
編輯最終,我對問題的解決方案基于@JeremyFriesner 的回答:closed在closeEventof 中發出信號w1,并將其(而不是QObject::destroyed)連接到w2.
uj5u.com熱心網友回復:
程式的這個修改版本顯示了如何通過覆寫小部件closeEvent(QCloseEvent *)上的方法來實作它w1:
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget * closeHim) : _closeHim(closeHim)
{
// empty
}
virtual void closeEvent(QCloseEvent * e)
{
QWidget::closeEvent(e);
if (_closeHim) _closeHim->close();
}
private:
QWidget * _closeHim;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w2;
w2.setWindowTitle("w2");
w2.show();
MyWidget w1(&w2);
w1.setWindowTitle("w1");
w1.show();
return a.exec();
}
如果你想做得更優雅,你可以讓你的closeEvent()方法覆寫發出一個信號,而不是在一個指標上呼叫一個方法;這樣你就不會在兩個類之間有直接的依賴關系,這會在未來給你更多的靈活性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378518.html
上一篇:Qt從影片中洗掉鍵值
