如何防止QDialog类关闭

时间:2014-03-14 11:56:08

标签: c++ qt qt-creator

如何在按下“确定”按钮后阻止QDialog类关闭?只有在此对话框中正确执行某些操作时才需要关闭窗口,在其他情况下我不需要关闭此窗口。

3 个答案:

答案 0 :(得分:3)

一般来说,欺骗用户是一种坏习惯。如果没有禁用某个按钮,那么当用户点击它时它会更好用。

因此,显而易见的解决方案是禁用按钮,直到满足必要的前提条件。对于完成对话框的按钮,您应该使用QDialogButtonBox而不是离散按钮,因为在不同平台上,这些按钮将在框内以不同方式排列 - 基于按钮的角色/类型。

以下是如何完成的示例。适用于Qt 4和5。

已经注意代码与现有样式表互操作。

screenshot

// https://github.com/KubaO/stackoverflown/tree/master/questions/buttonbox-22404318
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif
#include <type_traits>

首先,让我们有一些样式表操作助手:

void styleSheetSet(QWidget *w, const QString &what) {
   auto const token = QStringLiteral("/*>*/%1/*<*/").arg(what);
   if (what.isEmpty() || w->styleSheet().contains(token)) return;
   w->setStyleSheet(w->styleSheet().append(token));
}

void styleSheetClear(QWidget *w, const QString &what) {
   const auto token = QStringLiteral("/*>*/%1/*<*/").arg(what);
   if (what.isEmpty() || ! w->styleSheet().contains(token)) return;
   w->setStyleSheet(w->styleSheet().remove(token));
}

void styleSheetSelect(QWidget *w, bool selector,
                      const QString & onTrue,
                      const QString & onFalse = {})
{
   styleSheetSet(w, selector ? onTrue : onFalse);
   styleSheetClear(w, selector ? onFalse : onTrue);
}

template <typename T, typename U>
void setSelect(QSet<T> &set, bool b, const U &val) {
   if (b) set.insert(val); else set.remove(val);
}

递归父搜索:

    bool hasParent(QObject *obj, QObject *const parent) {
       Q_ASSERT(obj);
       while (obj = obj->parent())
          if (obj == parent) return true;
       return obj == parent;
    }

DialogValidator管理单个对话框的验证器。首先,当QLineEdit和通用小部件的内容发生变化时调用的插槽:

class DialogValidator : public QObject {
   Q_OBJECT
   QSet<QWidget*> m_validWidgets;
   int m_needsValid = 0;
   Q_SLOT void checkWidget() {
      if (sender()->isWidgetType())
         checkValidity(static_cast<QWidget*>(sender()));
   }
   Q_SLOT void checkLineEdit() {
      if (auto *l = qobject_cast<QLineEdit*>(sender()))
         checkValidity(l);
   }
   void checkValidity(QLineEdit *l) {
      indicateValidity(l, l->hasAcceptableInput());
   }
   void checkValidity(QWidget *w) {
      auto validator = w->findChild<QValidator*>();
      if (!validator) return;
      auto prop = w->metaObject()->userProperty();
      QVariant value = prop.read(w);
      int pos;
      QString text = value.toString();
      bool isValid =
            validator->validate(text, pos) == QValidator::Acceptable;
      indicateValidity(w, isValid);
   }
   void indicateValidity(QWidget *w, bool isValid) {
      auto *combo = qobject_cast<QComboBox*>(w->parentWidget());
      setSelect(m_validWidgets, isValid, combo ? combo : w);
      styleSheetSelect(w, !isValid,
                       QStringLiteral("%1 { background: yellow }")
                       .arg(QLatin1String(w->metaObject()->className())));
      emit newValidity(m_validWidgets.count() == m_needsValid);
   }

使用add方法将验证器添加到对话框验证器中。如果我们希望对动态类型的窗口小部件进行特殊处理,则应使用addPoly方法 - 它将调度到特定于类型的重载,如果有的话:

   template<typename W>
   typename std::enable_if<!std::is_same<QWidget,W>::value, bool>::type
   addPoly(W* w, QValidator *v) {
      if (!w) return false;
      return (add(w,v), true);
   }
public:
   DialogValidator(QObject *parent = {}) : QObject(parent) {}
   Q_SIGNAL void newValidity(bool);
   void addPoly(QWidget *w, QValidator *v) {
      addPoly(qobject_cast<QLineEdit*>(w), v) ||
            addPoly(qobject_cast<QComboBox*>(w), v) ||
            (add(w, v), true);
   }

然后,静态类型add方法:

   void add(QComboBox *b, QValidator *v) {
      if (auto *l = b->lineEdit())
         add(l, v);
   }
   void add(QLineEdit *l, QValidator *v) {
      l->setValidator(v);
      connect(l, SIGNAL(textChanged(QString)), SLOT(checkLineEdit()));
      m_needsValid++;
      checkValidity(l);
   }
   void add(QWidget *w, QValidator *v) {
      Q_ASSERT(hasParent(v, w));
      auto prop = w->metaObject()->userProperty();
      auto propChanged = prop.notifySignal();
      static auto check = metaObject()->method(metaObject()->indexOfSlot("checkWidget()"));
      Q_ASSERT(check.isValid());
      if (!prop.isValid() || !propChanged.isValid())
         return qWarning("DialogValidator::add: The target widget has no user property with a notifier.");
      if (connect(w, propChanged, this, check)) {
         m_needsValid++;
         checkValidity(w);
      }
   }

最后,构造验证器的便捷方法:

   template <typename V, typename W, typename...Args>
   typename std::enable_if<
   std::is_base_of<QWidget, W>::value && std::is_base_of<QValidator, V>::value, V*>::type
   add(W *w, Args...args) {
      V *validator = new V(std::forward<Args>(args)..., w);
      return add(w, validator), validator;
   }
};

我们的验证对话框:

class MyDialog : public QDialog {
   Q_OBJECT
   QFormLayout m_layout{this};
   QLineEdit m_cFactor;
   QLineEdit m_dFactor;
   QDialogButtonBox m_buttons{QDialogButtonBox::Ok | QDialogButtonBox::Cancel};
   DialogValidator m_validator;
public:
   MyDialog(QWidget *parent = {}, Qt::WindowFlags f = {}) : QDialog(parent, f) {
      m_layout.addRow("Combobulation Factor", &m_cFactor);
      m_layout.addRow("Decombobulation Factor", &m_dFactor);
      m_layout.addRow(&m_buttons);
      connect(&m_buttons, SIGNAL(accepted()), SLOT(accept()));
      connect(&m_buttons, SIGNAL(rejected()), SLOT(reject()));
      connect(&m_validator, SIGNAL(newValidity(bool)),
              m_buttons.button(QDialogButtonBox::Ok), SLOT(setEnabled(bool)));
      // QLineEdit-specific validator
      m_validator.add<QIntValidator>(&m_cFactor, 0, 50);
      // Generic user property-based validator
      m_validator.add<QIntValidator, QWidget>(&m_dFactor, -50, 0);
   }
};

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   MyDialog d;
   d.show();
   return a.exec();
}
#include "main.moc"

答案 1 :(得分:1)

虽然您可能不应该创建一个在用户单击时无法执行任何操作的按钮,但如果您绝对必须覆盖默认关闭行为,则需要覆盖QDialog::accept()

答案 2 :(得分:-1)

与@ kuba-ober相同,但使用自定义属性。改变一个功能:

styleSheet...

现在d.setStyleSheet("*[invalid=\"true\"] { background: yellow }"); 函数不是必需的,但我们需要为对话框或应用程序添加常量样式表:

<property name="styleSheet">
 <string notr="true">*[invalid="true"] { border-style: solid; border-width: 1px; border-radius: 2px; border-color: yellow; }</string>
</property>

或者如果使用Qt设计器,请添加根小部件属性:

{{1}}