gpt4 book ai didi

c++ - Qt 应用程序名称占位符

转载 作者:行者123 更新时间:2023-11-30 02:28:56 24 4
gpt4 key购买 nike

在 Qt 4.8.6 中,是否有一种机制来显示 QCoreApplication::applicationName() 的值?在 GUI 中无需编程?我的意思是,是否有一组可用于 QWidget::windowTitle() 的占位符? , QLabel::text()和其他属性,将被一些常见的字符串替换,如应用程序名称或版本?类似于 QWidget::windowTitle() 中的 [*] 占位符.

最佳答案

不,不存在执行此操作的现有机制。幸运的是,您可以自己实现。

要替换控件中的文本,您可以使用代理样式来替换所有出现的您指定的“宏”。

要替换窗口标题中的文本,您必须拦截 QEvent::WindowTitleChange

要使此类宏独一无二,您应该用一些 control codes 将它们包裹起来:在这里,美国/RS。下面是一个完整的示例。

// https://github.com/KubaO/stackoverflown/tree/master/questions/text-wildcard-40235510
#include <QtWidgets>

constexpr auto US = QChar{0x1F};
constexpr auto RS = QChar{0x1E};

class SubstitutingStyle : public QProxyStyle
{
Q_OBJECT
QMap<QString, QString> substs;
public:
static QString _(QString str) {
str.prepend(US);
str.append(RS);
return str;
}
void add(const QString & from, const QString & to) {
substs.insert(_(from), to);
}
QString substituted(QString text) const {
for (auto it = substs.begin(); it != substs.end(); ++it)
text.replace(it.key(), it.value());
return text;
}
virtual void drawItemText(
QPainter * painter, const QRect & rect, int flags, const QPalette & pal,
bool enabled, const QString & text, QPalette::ColorRole textRole = QPalette::NoRole) const override;
};

void SubstitutingStyle::drawItemText(
QPainter * painter, const QRect & rect, int flags, const QPalette & pal,
bool enabled, const QString & text, QPalette::ColorRole textRole) const
{
QProxyStyle::drawItemText(painter, rect, flags, pal, enabled, substituted(text), textRole);
}

template <typename Base> class SubstitutingApp : public Base {
public:
using Base::Base;
bool notify(QObject * obj, QEvent * ev) override {
if (ev->type() == QEvent::WindowTitleChange) {
auto w = qobject_cast<QWidget*>(obj);
auto s = qobject_cast<SubstitutingStyle*>(this->style());
if (w && s) w->setWindowTitle(s->substituted(w->windowTitle()));
}
return Base::notify(obj, ev);
}
};

int main(int argc, char ** argv) {
SubstitutingApp<QApplication> app{argc, argv};
auto style = new SubstitutingStyle;
app.setApplicationVersion("0.0.1");
app.setStyle(style);
style->add("version", app.applicationVersion());

QLabel label{"My Version is: \x1Fversion\x1E"};
label.setWindowTitle("Foo \x1Fversion\x1E");
label.setMinimumSize(200, 100);
label.show();
return app.exec();
}
#include "main.moc"

另请参阅:control text elision .

关于c++ - Qt 应用程序名称占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235510/

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