所以我在Qt 5.2.1中制作了一个程序。我需要的是,当用户点击按钮时,如果用户点击“确定”,则会出现警告。然后程序继续,如果他点击“取消”'没有任何反应。
我该怎么做?我是Qt的新手。
答案 0 :(得分:4)
这是一种sscce方法。我努力使它尽可能正确和最小化。我注意到以下几点:
阻止重新进入事件循环的方法必然是错误的来源,永远不应该使用。因此,我们不使用QMessageBox::exec()
。
使用标准按钮。
提供文本和信息性文本是为了符合跨平台的人机界面指南。
根据我们的实际要求设置消息框的模态。它是窗口模式,阻止与底层窗口的交互,但不与应用程序的其余部分交互。
子窗口小部件是常规成员,不直接在堆上分配。这使得内存管理变得更加容易,并且可以利用RAII。在内部,无论如何,他们将堆分配PIMPLs。
添加到布局的小部件是而不是传递给父级。这样做会是多余的。
为插槽指定了描述性名称,以指示它们所处理的小部件和信号。结合给出小部件对象名称,这可以让我们利用connectSlotsByName
机制。它还简化了调试,因为调试助手可以在调试Qt应用程序时看到对象名称。
P.S。 QDrag
,我正在盯着你。你知道,盯着。
// main.cpp
#include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
#include <QtGui>
#else
#include <QtWidgets>
#endif
class MyUi : public QWidget {
Q_OBJECT
QBoxLayout m_layout{QBoxLayout::TopToBottom, this};
QLabel m_label;
QPushButton m_button{"Change Message"};
QMessageBox m_warning{QMessageBox::Warning, "Message Change",
"The message will change.",
QMessageBox::Yes | QMessageBox::No,
this},
Q_SLOT void on_button_clicked() {
m_warning.show();
}
Q_SLOT void on_warning_finished(int rc) {
// The `finished()` signal is emitted with a
// QDialogButtonBox::StandardButton value - the same that would
// be retuned by QMessageBox::exec().
// A QMessageBox does *not* accept the dialog,
// so we can't simply use the `accepted` signal.
if (rc != QDialogButtonBox::Yes) return;
m_label.setText(m_label.text() + "*v*");
}
public:
MyUi(QWidget * parent = {}) : QWidget(parent) {
m_button.setObjectName("button");
m_warning.setObjectName("warning");
m_warning.setWindowModality(Qt::WindowModal);
m_warning.setInformativeText(
"Are you sure you want the message to change?");
m_layout.addWidget(&m_label);
m_layout.addWidget(&m_button);
QMetaObject::connectSlotsByName(this);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyUi ui;
ui.show();
return a.exec();
}
#include "main.moc"