IscanderChe
IscanderCheSept. 8, 2023, 5:12 p.m.

Кастомная QAbstractListModel и цвет фона, цвет текста и шрифт

Добрый день.

Пытаюсь поменять в модели цвет фона и текста, а так же шрифт и его размер. Получаю для всех трёх ролей - Qt::FontRole, Qt::BackgroundRole и Qt::ForegroundRole - однотипную ошибку. Что-то похожее у меня уже было когда-то давно, но я забыл, в чём там было дело.

QVariant MyAbstractListModel::data(const QModelIndex& index, int role) const
{
    if(!index.isValid())
        return QVariant();

    if(index.row() >= stringList.size())
        return QVariant();

    if(role == Qt::DisplayRole || role == Qt::EditRole)
    {
        QVariant value = QVariant::fromValue(stringList.at(index.row()));
        return value;
    }

    if(role == Qt::FontRole)
    {
        QFont font = QAbstractListModel::data(index, Qt::FontRole).value<QFont>();
        font.setFamily("Courier");
        font.setPointSize(10);
        return font;
    }

    if(role == Qt::BackgroundRole)
    {
        QBrush brush = QAbstractListModel::data(index, Qt::BackgroundRole).value<QBrush>();
        QColor color("#293134");
        brush.setColor(color);
        return brush;
    }

    if(role == Qt::ForegroundRole)
    {
        QBrush brush = QAbstractListModel::data(index, Qt::ForegroundRole).value<QBrush>();
        QColor color("#e0e2e4");
        brush.setColor(color);
        return brush;
    }

    return QVariant();
}
D:\workcopies\dev_qt2\SimpleCodeEditor\myabstractlistmodel.cpp:37: ошибка: undefined reference to `__imp__ZNK18QAbstractItemModel4dataERK11QModelIndexi'

P.S. Ругается, соот-но, на строки 17, 25, 33 по приведённому коду.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

5
Павел Дорофеев
  • Sept. 8, 2023, 6:56 p.m.
  • (edited)

Я бы так сделал:
QVariant var = QAbstractListModel::data(index, Qt::ForegroundRole).value();

потом проверил var на тип - может в value ничего нет?

Обычно роли типа Qt::ForegroundRole надо реализовывать самому (прямо тут же в ::data), то сть создавать и отдавать QFont.

    IscanderChe
    • Sept. 8, 2023, 7:38 p.m.

    Обычно роли типа Qt::ForegroundRole надо реализовывать самому (прямо тут же в data)

    Поясните подробнее этот момент.

    Когда я наследовался от QSqlTableModel, там такой код нормально работал.

      Павел Дорофеев
      • Sept. 8, 2023, 7:40 p.m.

      Промотрите просто так : QVariant var = QAbstractListModel::data(index, Qt::ForegroundRole).value();
      что в var?

        Павел Дорофеев
        • Sept. 8, 2023, 7:43 p.m.
        • (edited)

        Еще обратил внимание, что QAbstractListModel:: это же абстрактный класс. Похоже надо не абстрактный , а "реальный" типа QSqlTableModel .

          IscanderChe
          • Sept. 8, 2023, 10:07 p.m.

          Похоже надо не абстрактный , а "реальный" типа QSqlTableModel

          Да, но не совсем. Решилось с помощью стайлшитов и setFont.

          Спасибо за отлик!

            Comments

            Only authorized users can post comments.
            Please, Log in or Sign up
            Ua

            Qt - Test 001. Signals and slots

            • Result:84points,
            • Rating points4
            Ua

            Qt - Test 001. Signals and slots

            • Result:42points,
            • Rating points-8
            ОК

            Qt - Test 001. Signals and slots

            • Result:47points,
            • Rating points-6
            Last comments
            ИМ
            Игорь МаксимовNov. 22, 2024, 9:51 p.m.
            Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
            Evgenii Legotckoi
            Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
            Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
            A
            ALO1ZEOct. 19, 2024, 5:19 p.m.
            Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
            ИМ
            Игорь МаксимовOct. 5, 2024, 4:51 p.m.
            Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
            d
            dblas5July 5, 2024, 8:02 p.m.
            QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
            Now discuss on the forum
            AH
            Abdul HadiFeb. 13, 2025, 3:21 p.m.
            Are you Looking for best painter services in Qatar? Looking for top painter Services in Qatar? Get high-quality, affordable, and professional painting for homes & offices. Contact expert painters today!
            d
            dubaicushionsFeb. 13, 2025, 3:17 p.m.
            Are Looking for custom swing cushions in Dubai for home decor? Looking for Custom Swing Cushions in Dubai? Get high-quality, weather-resistant, and stylish cushions for your outdoor swing. Order now for comfort & elegance!
            d
            dubaicustomizedsofaFeb. 13, 2025, 3:11 p.m.
            Are you Looking for a custom sofa in Dubai? Looking for a Custom Sofa in Dubai ? Get high-quality, stylish, and tailor-made sofas to match your space. Order now for comfort, luxury, and perfect design!
            b
            blinds12Feb. 11, 2025, 4:08 p.m.
            Why Bamboo Blinds Are the Perfect Choice for Your Home When it comes to enhancing the aesthetics and functionality of your living space, choosing the right window treatment is crucial. Bamboo blinds have emerged as a popular choice for homeowners wh…
            i
            imperial3130Feb. 11, 2025, 3:40 p.m.
            How to Select the Right Carpet for Your Bedroom Aesthetic Choosing the perfect carpet for your bedroom involves more than just picking a color or pattern you like. Carpets can transform the ambiance of your space, adding warmth, comfort, and style. How…

            Follow us in social networks