QT Creator Main window - how to change the interface for each element from the menu?
I am new to QT Creator. I did create a menu: Login || Open. When login is clicked I would like to see a line edit and a press button. When Open is clicked I would like to see a picture in the window.开发者_StackOverflow中文版 Can I change the interface of the same window depending on what I click in the menu bar? How can I do that?
I did something similar to this - an app with several major areas, toggled by an icon bar at the top.
I used a QStackWidget
to stack the different application areas on top of each other, a set of QAction
s that I created using the designer, and a QActionGroup
to implement the toggling.
When the actions are marked as "checkable" and grouped in a QActionGroup
, theQToolBar
only lets one be active at the time.
Here's a simplified extract of my code:
// MyApp.h
#include <QMainWindow>
class QAction;
class QActionGroup;
namespace Ui {
class MyApp;
}
class MyApp: public QMainWindow
{
Q_OBJECT
public:
explicit MyApp(QWidget *parent = 0);
~MyApp();
public slots:
void showSection(QAction* a);
private:
Ui::MyApp *ui;
QActionGroup* sections;
};
//MyApp.cpp
#include "structureapp.h"
#include "ui_structureapp.h"
#include <QActionGroup>
MyApp::MyApp(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MyApp),
sections(new QActionGroup(this)),
{
ui->setupUi(this);
/* Populate section list */
/* Page indices for the stack widget*/
ui->actionSectionOne-> setData(0);
ui->actionSectionTwo-> setData(1);
ui->actionSectionThree-> setData(2);
sections->addAction(ui->actionSectionOne);
sections->addAction(ui->actionSectionTwo);
sections->addAction(ui->actionSectionThree);
ui->mainToolBar->addSeparator();
connect(sections, SIGNAL(triggered(QAction*)), this, SLOT(showSection(QAction*)));
/* Show the default section */
ui->actionContentSection->trigger();
}
MyApp::~MyApp()
{
delete ui;
}
void MyApp::showSection(QAction *a)
{
ui->mainArea->setCurrentIndex(a->data().toInt());
}
Yes, you can. As I explained earlier, each menu entry is a signal, and that's connected to a slot. With two different menu entries, you have two signals, and you'd connect them to two different slots. So, you could name your first slot onLogin
, and the second slot onOpen
. (It helps to choose descriptive names, so you'll understand your program when you come back on mondays).
Now, it the slot onLogin
, you put the code for login. In the slot onOpen
, you put the other code. But do consider what happens if you click the two menu entries one after another. Should that even be possible? If not, you may need another solution. It's quite common to use a QDialog
for a login. When a dialog is active, you can't use the menu of the main application, so you can't accidentily hit onOpen
when you're busy with the login.
精彩评论