QT4: How to get access to an object what is on mainwidow from an other class?
If Im in mainwindow.cpp then i can get every obj开发者_StackOverflow中文版ect on it with:
this->ui->textBox ...
What if there is another class (myclass2.cpp) and I would like to get the value of one the textBoxes. But they are on my mainwindow. I cant use this->ui->textBox
Whats the way to get access to the objects?
Thank You
In general, this is not a problem specific to Qt. There are several ways you can do this:
Provide a method on
mainwindow
that encapsulates what you want, and call that frommyclass2
.// In mainwindow.cpp: QString mainwindow::valueOfTheTextEditYouAreInterestedIn() const { return ui->textBox->toPlainText(); }
This has lots of benefits: clean design, easy to change later, and highly self-documenting, just to name a few. For this to work, your
myclass2
object will still need a pointer to the main window, though. Then you would call it like this:// In myclass2.cpp: { // we're in some function of myclass2 QString value = theMainWindow->valueOfTheTextEditYouAreInterestedIn(); // Use the value... }
Provide an accessor for the text edit. This is not such a good idea, because then
myclass2
can alter the text edit withoutmainwindow
knowing about it. However, it would look like:QTextEdit *getTheInterestingTextEdit() { return ui->textBox; }
This can be made more acceptable by returning a constant pointer, so that
myclass2
will be able to read, but not modify, the values of the text edit:const QTextEdit *getTheInterestingTextEdit() const { return ui->textBox; }
Qt provides yet another way to do the same thing, but you don't have to write your own method for it:
// In myclass2.cpp: QTextEdit *textBox = theMainWindow->findChild<QTextEdit *>("textBox");
where
mainwindow
is a pointer to the main window object thatmyclass2
will need to obtain somehow, and"textBox"
is the Qt object name you gave the interesting text box in Designer. And it will only work if the text edit object is a child widget of the main window object, which it should be in this case. You may run into trouble if you rely on this technique in general, though.You could always make
myclass2
a friend ofmainwindow
. This is so much not recommended, that I'm not going to post some code, though. :-)
精彩评论