Home > other >  How to access ui element from another dialog
How to access ui element from another dialog

Time:07-25

I have a this code for get avaiable serial ports on Main Window.

 QString parsedPortName = QSerialPortInfo::availablePorts().at(ui -> comboBoxDevices -> currentIndex()).portName();

I need access this avaiable ports from another Page. Hiw can I do that?

Here, on my Second Window I need replace avaiable comports with (QString("COM3")

if (serialStartStop.begin(QString("COM3"), 9600, 8, 0, 1, 0, false))
{
     serialStartStop.send("B"   ui->baslatmaedit->text().toLatin1()   "D"   ui->durdurmaedit->text().toLatin1());

}

CodePudding user response:

The usual way would be to have something like this in the first dialog:

QString parsedPortName = QSerialPortInfo::availablePorts().at(ui -> comboBoxDevices -> currentIndex()).portName();
emit portNameChanged(parsedPortName); // add this signal to the class

And then in the second window, you would have a slot, which receives the port name, and stores it in a member variable. Then in the code where you create these two windows or dialogs, you add the connect call for the signal and the slot.


Since this port is something, which you might want to save between different times the application is run, you could also use QSettings to store the combo box selection, and restore it to the combo box when application starts, and change it when user changes it in the combo box.

In this case, you'd probably want to move the QSerialPortInfo::availablePorts() call to the second window, done just before the port name is actually used.

In my experience, the best way to use QSettings is to first set it up in main():

QCoreApplication::setOrganizationName("MyImaginaryOrganization");
QCoreApplication::setApplicationName("MyComPortApp");

After that, it will store the settings in operating system specific, generally good, way. And then you can just use it like this anywhere in your application:

QSettings().setValue("serial/portname", parsedPortName);

and elsewhere

auto port = QSettings().value("serial/portname").toString();

Instead of using QSettings, you might create your own singleton class like that, but really, QSettings exists and is quite nice for the purpose, so just use it unless you have some compelling reason to write your own.


You can of course also combine these two things: use QSettings with the combo box only, and still emit a signal when it is changed.

  •  Tags:  
  • c qt
  • Related