Passing data between 2 windows. Qt

泪湿孤枕 提交于 2019-12-08 11:26:41

问题


I am new to qt, so I didn't quite get the signal slot mechanism. here is my setup. Dialog class (its a dialog with a lineEdit called "lineEdit") mainwindow class (that has a lineEdit too)

I have this :

void MainWindow::keyPressEvent(QKeyEvent *event) {


    int i=event->key();
    //char z=(char)i;



   // connect(ui->lineEdit, SIGNAL(textChanged(QString)), dialog, SLOT(setText(QString)));

if(i>=48&&i<=57)

{
    QString s= QString::number(i-'0');


    q+=s;
    ui->lineEdit->setText(q);

}

I want to set the text of dialog's lineEdit to q too. how do I got about that ?


回答1:


  1. You will not go anywhere with Qt unless you understand the fundamentals. Read the plentiful example code that came with it if understanding documentation isn't your thing. Some people are better at reading prose, some at reading code, there's nothing wrong with that. Just be sure to do it :)

  2. A QLineEdit already processes its own keystrokes. There's no need to reimplement that functionality.

  3. Signal-slot connections should be static unless your application is changing states. If you connect a signal on an object to a slot on another object multiple times, then the slot will be called as many times as there are connections.

  4. The idiomatic way of passing data between a pair of QLineEdits is as follows:

    connect(ui->lineEdit, SIGNAL(textEdited(QString)),
            dialog, SLOT(setText(QString)));
    connect(dialog, SIGNAL(textEdited(QString)),
            ui->lineEdit, SLOT(setText(QString)));
    

    You'd probably want to set this connection up in the constructor of MainWindow, but in any case you only want it to be done once.

    You should be using the textEdited signal, not textChanged signal. The former is emitted when the user interacts with the control to change it. The latter is emitted whether the text was changed by the user or programmatically by calling setText. If you connected textChanged to setText between a pair of controls, you'd get an endless loop. QML is clever enough to detect it, but widgets code AFAIK isn't.




回答2:


a little late but to the others that come to see this page, you can watch a little (~30min!) youtube video that I've prepared...

(shows: connecting to a database, dialogs, signal and slots between dialogs, ...)

https://www.youtube.com/watch?v=TEq15So3fUg

Cheers!



来源:https://stackoverflow.com/questions/19200598/passing-data-between-2-windows-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!