Domanda

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 ?

È stato utile?

Soluzione

  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.

Altri suggerimenti

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!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top