开发者

Cannot connect QMainWindow and QDialog

I have a QMainWindow displaying a QDialog:

CalibrationDialog d(this);
d.exec();

My QMainWindow class has a signal:

signals:
void PenOn( QPoint p );

And QDialog has a slot:

public slots:
void on_PenON( QPoint p );

I tried connecting PenOn event to on_PenOn in two ways:

  1. After instantiating QDialog

   void MainWindow::on_actionC_triggered()
   {
     appState = CALIBR;

     CalibrationDialog d(this);
     connect( this, SIGNAL(PenOn(QPoint)), &d,SLOT(on_PenOn(QPoint)) );
     d.exec();
   }
  1. In QDialog constructor

    CalibrationDialog::CalibrationDialog(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::CalibrationDialog)
    {
        ui->setupUi(this);

        [...]

        connect( parent, SIGNAL(PenOn(QPoint)), this,SLOT(on_PenOn(QPoint)) );
    }

None of this works :(. I'm emitting Pe开发者_如何学CnOn signal from MainWindow slot activated by another thread.

What am I doing wrong?


Still does not know what's going on. I made use of QEvent and solved problem this way.


My first guess on the problem is that you don't have the Q_OBJECT macro in one of your classes, or possibly both. If you do but added it after you generated your makefile, you may need to re-run qmake to regenerate the makefile (or whatever you use on your platform) to let it know that the moc needs to be run on those classes. If the moc isn't run over your classes, it doesn't generate the code required to add the signal and slot information to the class, and the connections will fail.


I think you need to use a blocking direct connection, although be aware that the slot will be executed in the MainWindow's thread:

connect(this, SIGNAL(PenOn(QPoint)), &d, SLOT(on_PenOn(QPoint)), Qt::BlockingQueuedConnection);

See https://doc.qt.io/qt-5/qt.html#ConnectionType-enum for more info.

The problem with using the default Qt::ConnectionType for the connect method is that since the objects are in different threads, the slot will not be called until the dialog thread gets back to it's main loop, which will only happen after the d.exec() loop is finished.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜