我想通過QColor從C++傳遞給QML來設置自定義QQuickPaintedItem的QColor屬性。我曾嘗試以下方法:Qml QColor類型錯誤
- 將QColor轉換爲QVariant。在JS調試器中,顏色對象是空的。
- 將QColor轉換爲顏色字符串「#RRGGBB」。這仍然會引發類型錯誤。
QML代碼:
m_DisplayScreens[m_DisplayScreens.length].backgroundColor = m_Model.getBackgroundColor(i_Timer);
m_DisplayScreens是我的自定義QML插件的列表。我可以通過做類似的事情來設置backgroundColor屬性。
DisplayScreen
{
backgroundColor: "Red"
}
「m_Model」對象只是一個QObject,它是QML表單的'後端'。對於getBackgroundColor的代碼如下:
Q_INVOKABLE QString getBackgroundColor(int index);
QString CountDownPanelModel::getSegmentColor(int index)
{
return "#003300";
}
特定的錯誤是:xxx.js:19:類型錯誤:錯誤類型
任何幫助,將不勝感激。我現在一直在抨擊我的頭幾個小時。
感謝,
JEC
1日編輯:
好的人,這是我返回的QColor時嘗試;
class CountDownPanelModel : public QObject
{
Q_OBJECT
public:
explicit CountDownPanelModel(QObject *parent = 0);
~CountDownPanelModel() = default;
Q_INVOKABLE QColor getBackgroundColor(int index);
Q_INVOKABLE QColor getSegmentColor(int index);
};
QColor CountDownPanelModel::getBackgroundColor(int index)
{
return QColor(44, 44, 44);
//return m_TimerList->at(index)->getTimerData()->getBackgroundColor();
}
QColor CountDownPanelModel::getSegmentColor(int index)
{
return QColor(200, 200, 200);
//return m_TimerList->at(index)->getTimerData()->getSegmentColor();
}
使用QColor的結果與使用QString的結果相同。我在我分配顏色的那一行出現「Type Error」。例如:
var m_DisplayScreens = [];
function createDisplays()
{
m_DisplayScreens = [];
var timerCount = m_Model.getTimerCount();
var bg = m_Model.getBackgroundColor(0);
var fg = m_Model.getSegmentColor(0)
for (var i_Timer = 0;
i_Timer < timerCount;
++i_Timer)
{
var component = Qt.createComponent("DynamicSevenSegmentDisplay.qml");
var display = component.createObject(m_Panel);
display.initialize(m_Model.getSevenSegmentDisplayInitializer())
display.y = 100 * (i_Timer);
m_DisplayScreens[m_DisplayScreens.length] = display;
m_DisplayScreens[m_DisplayScreens.length].backgroundColor = m_Model.getBackgroundColor(i_Timer);
m_DisplayScreens[m_DisplayScreens.length].segmentColor = m_Model.getSegmentColor(i_Timer)
}
m_Panel.height = 100 * timerCount;
}
只是爲了完整性,這裏是DynamicSevenSegmentDisplay.qml
SevenSegmentDisplayScreen
{
y: 0
height: 100
width: parent.width - x
backgroundColor: "Black"
borderPercentage: 10
displayCount: 20
text: "1234567890"
anchors.left: m_SettingsButton.right
anchors.leftMargin: 8
}
我爲完全困惑,爲什麼我不能assignthe的QColor來的backgroundColor。調試器在「值」列中不顯示任何內容。我認爲這是'null'的JS版本。
你能否提供getBackgroundColor的實現? – MrEricSir 2014-09-29 00:38:56
來自Qt文檔:當與C++集成時,請注意從C++傳入QML的任何QColor值會自動轉換爲顏色值,反之亦然。因此,您必須從'getBackgroundColor'返回QColor,而不是QString – folibis 2014-09-29 02:06:34
我試過了一個QColor以前。當我嘗試這種方法時,JS調試器顯示對象是空的,我仍然有類型錯誤。這恰好是我最近的嘗試。我在嘗試使用字符串,因爲我知道你可以使用字符串來設置顏色。例如顏色:「#003300」是QML中的合法語法。我只是不確定在從C++傳遞它時是否會發揮作用。 – jecjackal 2014-09-29 14:13:25