gpt4 book ai didi

c++ - 如何防止 QDialog 类关闭

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:38 25 4
gpt4 key购买 nike

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

最佳答案

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

因此,显而易见的解决方案是在满足必要的先决条件之前禁用该按钮。对于完成对话框的按钮,您应该使用 QDialogBu​​ttonBox 而不是离散按钮,因为在不同的平台上,这些按钮将根据按钮的角色/类型在框中以不同方式排列。

下面是如何完成的示例。适用于 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 方法 - 如果有的话,它将分派(dispatch)到特定类型的重载:

   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"

关于c++ - 如何防止 QDialog 类关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22404318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com