问题描述
我想创建自定义 QT 对话框(非模态)。我的实现的问题是它只显示带有标题的对话框窗口,没有我添加的小部件。
主窗口.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
/// some other stuff
private:
std::unique_ptr<ui::DialogAddUpdateItem> addItemDialog;
/// some other stuff
}
MainWindow.cpp
/// some stuff
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
/// some stuff
addItemButton = new QPushButton(tr("Add item"));
QObject::connect(addItemButton,&QPushButton::pressed,this,&MainWindow::openAddItemDialog);
navLay->addWidget(addItemButton);
addItemDialog = make_unique<ui::DialogAddUpdateItem>(this);
/// some stuff
}
void MainWindow::openAddItemDialog() {
addItemDialog->show();
//addItemDialog->raise(); does not work with or without those functions
//addItemDialog->activateWindow();
//QApplication::processEvents();
}
DialogAddUpdateItem.h
namespace ui {
class DialogAddUpdateItem : public QDialog
{
Q_OBJECT
public:
DialogAddUpdateItem(QWidget *parent = nullptr);
private:
QPushButton *buttonAcc,*buttonRevert,*buttonCancel;
qgroupbox *centralWidget,*buttonsWidget;
QLabel *labelName,*labelDescription;
QLineEdit *textName;
QPlainTextEdit *textDescription;
}
}
DialogAddUpdateItem.cpp
namespace ui {
DialogAddUpdateItem::DialogAddUpdateItem(QWidget *parent) : QDialog(parent)
{
if (!item) {
setwindowTitle(tr("New object"));
}
centralWidget = new qgroupbox;
QHBoxLayout *itemLay = new QHBoxLayout;
centralWidget->setLayout(itemLay);
labelName = new QLabel(tr("Name"));
itemLay->addWidget(labelName);
textName = new QLineEdit;
if (item) {
textName->setText(QString::fromStdString(item->getName()));
}
itemLay->addWidget(textName);
labelDescription = new QLabel(tr("Description"));
if (item) {
textDescription = new QPlainTextEdit(QString::fromStdString(item->getDescription()));
} else {
textDescription = new QPlainTextEdit;
}
itemLay->addWidget(textDescription);
buttonAcc = new QPushButton(tr("Save"));
buttonAcc->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
QObject::connect(buttonAcc,&QPushButton::clicked,&DialogAddUpdateItem::acceptItem);
buttonRevert = new QPushButton(tr("Revert"));
buttonRevert->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
QObject::connect(buttonRevert,&DialogAddUpdateItem::revertItem);
buttonCancel = new QPushButton(tr("Cancel"));
buttonCancel->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
QObject::connect(buttonCancel,&DialogAddUpdateItem::cancelItem);
buttonsWidget = new qgroupbox;
itemLay->addWidget(buttonsWidget);
QVBoxLayout *buttonsLay = new QVBoxLayout;
buttonsLay->addWidget(buttonAcc);
buttonsLay->addWidget(buttonRevert);
buttonsLay->addWidget(buttonCancel);
}
}
解决方法
在 DialogAddUpdateItem.cpp
中,centralWidget
没有父级,因此它没有绑定到任何东西,因此不会显示。你应该修改这个:
centralWidget = new QGroupBox;
进入这个:
centralWidget = new QGroupBox(this);
现在 DialogAddUpdateItem
将成为 centralWidget
的父级,它应该显示它。
此外,您似乎要在没有父级的情况下留下其他一些小部件 - 这可能会导致麻烦。例如,QLineEdit textName
有这个问题。